websocket-server.rb 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env ruby
  2. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  3. $LOAD_PATH << './lib'
  4. require 'rubygems'
  5. # load rails env
  6. dir = File.expand_path('..', __dir__)
  7. Dir.chdir dir
  8. RAILS_ENV = ENV['RAILS_ENV'] || 'development'
  9. require 'rails/all'
  10. require 'bundler'
  11. require File.join(dir, 'config', 'environment')
  12. require 'eventmachine'
  13. require 'em-websocket'
  14. require 'json'
  15. require 'fileutils'
  16. require 'optparse'
  17. require 'daemons'
  18. require 'sessions'
  19. def before_fork
  20. # remember open file handles
  21. @files_to_reopen = []
  22. ObjectSpace.each_object(File) do |file|
  23. @files_to_reopen << file if !file.closed?
  24. end
  25. end
  26. def after_fork(dir)
  27. Dir.chdir dir
  28. # Re-open file handles
  29. @files_to_reopen.each do |file|
  30. file.reopen file.path, 'a+'
  31. file.sync = true
  32. end
  33. $stdout.reopen( "#{dir}/log/websocket-server_out.log", 'w').sync = true
  34. $stderr.reopen( "#{dir}/log/websocket-server_err.log", 'w').sync = true
  35. end
  36. before_fork
  37. # Look for -o with argument, and -I and -D boolean arguments
  38. @options = {
  39. p: 6042,
  40. b: '0.0.0.0',
  41. s: false,
  42. v: false,
  43. d: false,
  44. k: '/path/to/server.key',
  45. c: '/path/to/server.crt',
  46. i: Dir.pwd.to_s + '/tmp/pids/websocket.pid'
  47. }
  48. tls_options = {}
  49. OptionParser.new do |opts|
  50. opts.banner = 'Usage: websocket-server.rb start|stop [options]'
  51. opts.on('-d', '--daemon', 'start as daemon') do |d|
  52. @options[:d] = d
  53. end
  54. opts.on('-v', '--verbose', 'enable debug messages') do |d|
  55. @options[:v] = d
  56. end
  57. opts.on('-p', '--port [OPT]', 'port of websocket server') do |p|
  58. @options[:p] = p
  59. end
  60. opts.on('-b', '--bind [OPT]', 'bind address') do |b|
  61. @options[:b] = IPAddr.new(b).to_s
  62. end
  63. opts.on('-s', '--secure', 'enable secure connections') do |s|
  64. @options[:s] = s
  65. end
  66. opts.on('-i', '--pid [OPT]', 'pid, default is tmp/pids/websocket.pid') do |i|
  67. @options[:i] = i
  68. end
  69. opts.on('-k', '--private-key [OPT]', '/path/to/server.key for secure connections') do |k|
  70. tls_options[:private_key_file] = k
  71. end
  72. opts.on('-c', '--certificate [OPT]', '/path/to/server.crt for secure connections') do |c|
  73. tls_options[:cert_chain_file] = c
  74. end
  75. end.parse!
  76. if ARGV[0] != 'start' && ARGV[0] != 'stop'
  77. puts "Usage: #{File.basename(__FILE__)} start|stop [options]"
  78. exit
  79. end
  80. if ARGV[0] == 'stop'
  81. pid = File.read(@options[:i]).to_i
  82. puts "Stopping websocket server (pid: #{pid})"
  83. # IMPORTANT: Use SIGTERM (15), not SIGKILL (9)
  84. # Daemons.rb cleans up the PID file automatically on termination;
  85. # SIGKILL ends the process immediately and bypasses cleanup.
  86. # See https://major.io/2010/03/18/sigterm-vs-sigkill/ for more.
  87. Process.kill(:SIGTERM, pid)
  88. exit
  89. end
  90. if ARGV[0] == 'start' && @options[:d]
  91. puts "Starting websocket server on #{@options[:b]}:#{@options[:p]} (secure: #{@options[:s]}, pidfile: #{@options[:i]})"
  92. # Use Daemons.rb's built-in facility for generating PID files
  93. Daemons.daemonize(
  94. app_name: File.basename(@options[:i], '.pid'),
  95. dir_mode: :normal,
  96. dir: File.dirname(@options[:i])
  97. )
  98. after_fork(dir)
  99. end
  100. @clients = {}
  101. Rails.configuration.interface = 'websocket'
  102. EventMachine.run do
  103. EventMachine::WebSocket.start( host: @options[:b], port: @options[:p], secure: @options[:s], tls_options: tls_options ) do |ws|
  104. # register client connection
  105. ws.onopen do |handshake|
  106. headers = handshake.headers
  107. remote_ip = get_remote_ip(headers)
  108. client_id = ws.object_id.to_s
  109. log 'notice', 'Client connected.', client_id
  110. Sessions.create( client_id, {}, { type: 'websocket' } )
  111. if !@clients.include? client_id
  112. @clients[client_id] = {
  113. websocket: ws,
  114. last_ping: Time.now.utc.to_i,
  115. error_count: 0,
  116. headers: headers,
  117. remote_ip: remote_ip,
  118. }
  119. end
  120. end
  121. # unregister client connection
  122. ws.onclose do
  123. client_id = ws.object_id.to_s
  124. log 'notice', 'Client disconnected.', client_id
  125. # removed from current client list
  126. if @clients.include? client_id
  127. @clients.delete client_id
  128. end
  129. Sessions.destroy(client_id)
  130. end
  131. # manage messages
  132. ws.onmessage do |msg|
  133. client_id = ws.object_id.to_s
  134. log 'debug', "received: #{msg} ", client_id
  135. begin
  136. data = JSON.parse(msg)
  137. rescue => e
  138. log 'error', "can't parse message: #{msg}, #{e.inspect}", client_id
  139. next
  140. end
  141. # check if connection not already exists
  142. next if !@clients[client_id]
  143. Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations
  144. @clients[client_id][:last_ping] = Time.now.utc.to_i
  145. # spool messages for new connects
  146. if data['spool']
  147. Sessions.spool_create(data)
  148. end
  149. if data['event']
  150. log 'debug', "execute event '#{data['event']}'", client_id
  151. message = Sessions::Event.run(
  152. event: data['event'],
  153. payload: data,
  154. session: @clients[client_id][:session],
  155. remote_ip: @clients[client_id][:remote_ip],
  156. client_id: client_id,
  157. clients: @clients,
  158. options: @options,
  159. )
  160. if message
  161. websocket_send(client_id, message)
  162. end
  163. else
  164. log 'error', "unknown message '#{data.inspect}'", client_id
  165. end
  166. end
  167. end
  168. # check unused connections
  169. EventMachine.add_timer(0.5) do
  170. check_unused_connections
  171. end
  172. # check open unused connections, kick all connection without activitie in the last 2 minutes
  173. EventMachine.add_periodic_timer(120) do
  174. check_unused_connections
  175. end
  176. EventMachine.add_periodic_timer(20) do
  177. # websocket
  178. log 'notice', "Status: websocket clients: #{@clients.size}"
  179. @clients.each_key do |client_id|
  180. log 'notice', 'working...', client_id
  181. end
  182. # ajax
  183. client_list = Sessions.list
  184. clients = 0
  185. client_list.each_value do |client|
  186. next if client[:meta][:type] == 'websocket'
  187. clients = clients + 1
  188. end
  189. log 'notice', "Status: ajax clients: #{clients}"
  190. client_list.each do |client_id, client|
  191. next if client[:meta][:type] == 'websocket'
  192. log 'notice', 'working...', client_id
  193. end
  194. end
  195. EventMachine.add_periodic_timer(0.4) do
  196. next if @clients.size.zero?
  197. #log 'debug', 'checking for data to send...'
  198. @clients.each do |client_id, client|
  199. next if client[:disconnect]
  200. log 'debug', 'checking for data...', client_id
  201. begin
  202. queue = Sessions.queue(client_id)
  203. next if queue.blank?
  204. log 'notice', 'send data to client', client_id
  205. websocket_send(client_id, queue)
  206. rescue => e
  207. log 'error', 'problem:' + e.inspect, client_id
  208. # disconnect client
  209. client[:error_count] += 1
  210. if client[:error_count] > 20
  211. if @clients.include? client_id
  212. @clients.delete client_id
  213. end
  214. end
  215. end
  216. end
  217. end
  218. def get_remote_ip(headers)
  219. return headers['X-Forwarded-For'] if headers && headers['X-Forwarded-For']
  220. nil
  221. end
  222. def websocket_send(client_id, data)
  223. msg = if data.class != Array
  224. "[#{data.to_json}]"
  225. else
  226. data.to_json
  227. end
  228. log 'debug', "send #{msg}", client_id
  229. if !@clients[client_id]
  230. log 'error', "no such @clients for #{client_id}", client_id
  231. return
  232. end
  233. @clients[client_id][:websocket].send(msg)
  234. end
  235. def check_unused_connections
  236. log 'notice', 'check unused idle connections...'
  237. idle_time_in_sec = 4 * 60
  238. # close unused web socket sessions
  239. @clients.each do |client_id, client|
  240. next if ( client[:last_ping].to_i + idle_time_in_sec ) >= Time.now.utc.to_i
  241. log 'notice', 'closing idle websocket connection', client_id
  242. # remember to not use this connection anymore
  243. client[:disconnect] = true
  244. # try to close regular
  245. client[:websocket].close_websocket
  246. # delete session from client list
  247. sleep 0.3
  248. @clients.delete(client_id)
  249. end
  250. # close unused ajax long polling sessions
  251. clients = Sessions.destroy_idle_sessions(idle_time_in_sec)
  252. clients.each do |client_id|
  253. log 'notice', 'closing idle long polling connection', client_id
  254. end
  255. end
  256. def log(level, data, client_id = '-')
  257. if !@options[:v]
  258. return if level == 'debug'
  259. end
  260. puts "#{Time.now.utc.iso8601}:client(#{client_id}) #{data}"
  261. #puts "#{Time.now.utc.iso8601}:#{ level }:client(#{ client_id }) #{ data }"
  262. end
  263. end