websocket-server.rb 7.7 KB

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