websocket-server.rb 7.6 KB

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