trabajo-afectivo/script/websocket-server.rb

316 lines
8.1 KiB
Ruby
Raw Normal View History

2013-03-10 23:14:31 +00:00
#!/usr/bin/env ruby
2016-10-19 03:11:36 +00:00
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
2012-07-23 22:22:23 +00:00
$LOAD_PATH << './lib'
require 'rubygems'
# load rails env
dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
Dir.chdir dir
RAILS_ENV = ENV['RAILS_ENV'] || 'development'
require 'rails/all'
require 'bundler'
require File.join(dir, 'config', 'environment')
require 'eventmachine'
require 'em-websocket'
require 'json'
require 'fileutils'
require 'optparse'
require 'daemons'
require 'sessions'
def before_fork
# remember open file handles
@files_to_reopen = []
ObjectSpace.each_object(File) do |file|
@files_to_reopen << file unless file.closed?
end
end
def after_fork(dir)
Dir.chdir dir
# Re-open file handles
@files_to_reopen.each do |file|
file.reopen file.path, 'a+'
file.sync = true
end
$stdout.reopen( "#{dir}/log/websocket-server_out.log", 'w')
$stderr.reopen( "#{dir}/log/websocket-server_err.log", 'w')
end
before_fork
2012-07-23 22:22:23 +00:00
# Look for -o with argument, and -I and -D boolean arguments
@options = {
p: 6042,
b: '0.0.0.0',
s: false,
v: false,
d: false,
k: '/path/to/server.key',
c: '/path/to/server.crt',
i: Dir.pwd.to_s + '/tmp/pids/websocket.pid'
2012-07-23 22:22:23 +00:00
}
2013-03-10 23:14:31 +00:00
2012-08-02 09:30:30 +00:00
tls_options = {}
2012-07-23 22:22:23 +00:00
OptionParser.new do |opts|
opts.banner = 'Usage: websocket-server.rb start|stop [options]'
2012-07-23 22:22:23 +00:00
opts.on('-d', '--daemon', 'start as daemon') do |d|
@options[:d] = d
end
opts.on('-v', '--verbose', 'enable debug messages') do |d|
2013-03-10 23:14:31 +00:00
@options[:v] = d
end
opts.on('-p', '--port [OPT]', 'port of websocket server') do |p|
@options[:p] = p
2012-07-23 22:22:23 +00:00
end
opts.on('-b', '--bind [OPT]', 'bind address') do |b|
@options[:b] = b
2012-07-23 22:22:23 +00:00
end
opts.on('-s', '--secure', 'enable secure connections') do |s|
@options[:s] = s
2012-08-02 09:17:22 +00:00
end
opts.on('-i', '--pid [OPT]', 'pid, default is tmp/pids/websocket.pid') do |i|
2013-01-15 22:46:35 +00:00
@options[:i] = i
end
opts.on('-k', '--private-key [OPT]', '/path/to/server.key for secure connections') do |k|
2012-08-02 09:30:30 +00:00
tls_options[:private_key_file] = k
2012-08-02 09:17:22 +00:00
end
opts.on('-c', '--certificate [OPT]', '/path/to/server.crt for secure connections') do |c|
2012-08-02 09:30:30 +00:00
tls_options[:cert_chain_file] = c
2012-08-02 09:17:22 +00:00
end
2012-07-23 22:22:23 +00:00
end.parse!
if ARGV[0] != 'start' && ARGV[0] != 'stop'
puts "Usage: #{File.basename(__FILE__)} start|stop [options]"
exit
end
2013-03-10 23:14:31 +00:00
if ARGV[0] == 'stop'
2015-07-16 19:56:54 +00:00
puts "Stopping websocket server (pid:#{@options[:i]})"
2013-03-10 23:14:31 +00:00
# read pid
pid = File.open( @options[:i].to_s ).read
pid.gsub!(/\r|\n/, '')
2013-03-10 23:14:31 +00:00
# kill
Process.kill( 9, pid.to_i )
exit
end
2015-11-24 02:33:40 +00:00
if ARGV[0] == 'start' && @options[:d]
2015-07-16 19:56:54 +00:00
puts "Starting websocket server on #{@options[:b]}:#{@options[:p]} (secure:#{@options[:s]},pid:#{@options[:i]})"
2013-03-10 23:14:31 +00:00
Daemons.daemonize
after_fork(dir)
2015-12-06 23:15:53 +00:00
2013-03-10 23:14:31 +00:00
# create pid file
daemon_pid = File.new(@options[:i].to_s, 'w')
daemon_pid.sync = true
daemon_pid.puts(Process.pid.to_s)
daemon_pid.close
2013-03-10 23:14:31 +00:00
end
2013-01-15 22:33:51 +00:00
2012-07-23 22:22:23 +00:00
@clients = {}
Rails.configuration.interface = 'websocket'
EventMachine.run do
EventMachine::WebSocket.start( host: @options[:b], port: @options[:p], secure: @options[:s], tls_options: tls_options ) do |ws|
2012-07-23 22:22:23 +00:00
# register client connection
ws.onopen do |handshake|
2016-01-05 08:29:15 +00:00
headers = handshake.headers
remote_ip = get_remote_ip(headers)
client_id = ws.object_id.to_s
log 'notice', 'Client connected.', client_id
Sessions.create( client_id, {}, { type: 'websocket' } )
2012-07-23 22:22:23 +00:00
if !@clients.include? client_id
@clients[client_id] = {
2015-05-10 20:53:15 +00:00
websocket: ws,
last_ping: Time.now.utc.to_i,
error_count: 0,
2016-01-05 08:29:15 +00:00
headers: headers,
2016-01-05 12:46:43 +00:00
remote_ip: remote_ip,
}
2012-07-23 22:22:23 +00:00
end
end
2012-07-23 22:22:23 +00:00
# unregister client connection
ws.onclose do
client_id = ws.object_id.to_s
log 'notice', 'Client disconnected.', client_id
2012-08-04 13:35:55 +00:00
# removed from current client list
2012-07-23 22:22:23 +00:00
if @clients.include? client_id
@clients.delete client_id
end
2012-08-04 13:35:55 +00:00
Sessions.destroy(client_id)
end
2012-07-23 22:22:23 +00:00
# manage messages
ws.onmessage do |msg|
2012-07-23 22:22:23 +00:00
client_id = ws.object_id.to_s
log 'debug', "received: #{msg} ", client_id
begin
data = JSON.parse(msg)
rescue => e
log 'error', "can't parse message: #{msg}, #{e.inspect}", client_id
next
end
2012-07-23 22:22:23 +00:00
2015-09-06 11:41:51 +00:00
# check if connection not already exists
2012-08-07 05:33:47 +00:00
next if !@clients[client_id]
2017-11-23 08:09:44 +00:00
Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations
2015-11-10 14:01:04 +00:00
@clients[client_id][:last_ping] = Time.now.utc.to_i
2012-11-02 16:10:22 +00:00
# spool messages for new connects
if data['spool']
2015-12-09 13:09:37 +00:00
Sessions.spool_create(data)
2012-11-02 16:10:22 +00:00
end
2015-12-09 13:09:37 +00:00
if data['event']
log 'debug', "execute event '#{data['event']}'", client_id
message = Sessions::Event.run(
event: data['event'],
payload: data,
session: @clients[client_id][:session],
2016-01-05 12:46:43 +00:00
remote_ip: @clients[client_id][:remote_ip],
2015-12-09 13:09:37 +00:00
client_id: client_id,
clients: @clients,
options: @options,
)
2015-11-10 14:01:04 +00:00
if message
websocket_send(client_id, message)
end
2015-12-09 13:09:37 +00:00
else
log 'error', "unknown message '#{data.inspect}'", client_id
2012-08-04 13:35:55 +00:00
end
end
2012-07-23 22:22:23 +00:00
end
# check unused connections
EventMachine.add_timer(0.5) do
check_unused_connections
end
# check open unused connections, kick all connection without activitie in the last 2 minutes
EventMachine.add_periodic_timer(120) do
2012-12-24 13:53:50 +00:00
check_unused_connections
end
EventMachine.add_periodic_timer(20) do
2012-11-26 05:04:44 +00:00
# websocket
log 'notice', "Status: websocket clients: #{@clients.size}"
2017-11-23 08:09:44 +00:00
@clients.each_key do |client_id|
log 'notice', 'working...', client_id
end
2012-11-26 05:04:44 +00:00
# ajax
client_list = Sessions.list
2012-11-26 05:04:44 +00:00
clients = 0
2017-11-23 08:09:44 +00:00
client_list.each_value do |client|
2012-11-26 05:04:44 +00:00
next if client[:meta][:type] == 'websocket'
clients = clients + 1
end
log 'notice', "Status: ajax clients: #{clients}"
client_list.each do |client_id, client|
2012-11-26 05:04:44 +00:00
next if client[:meta][:type] == 'websocket'
log 'notice', 'working...', client_id
end
2012-11-26 05:04:44 +00:00
end
EventMachine.add_periodic_timer(0.4) do
next if @clients.size.zero?
2015-05-12 08:46:07 +00:00
#log 'debug', 'checking for data to send...'
@clients.each do |client_id, client|
2012-08-07 05:33:47 +00:00
next if client[:disconnect]
log 'debug', 'checking for data...', client_id
2012-07-23 22:22:23 +00:00
begin
queue = Sessions.queue(client_id)
next if queue.blank?
log 'notice', 'send data to client', client_id
websocket_send(client_id, queue)
2012-08-03 22:46:05 +00:00
rescue => e
log 'error', 'problem:' + e.inspect, client_id
# disconnect client
2012-08-07 05:33:47 +00:00
client[:error_count] += 1
if client[:error_count] > 20
2012-08-07 05:33:47 +00:00
if @clients.include? client_id
@clients.delete client_id
end
end
2012-07-23 22:22:23 +00:00
end
end
end
2012-11-02 16:10:22 +00:00
2016-01-05 08:29:15 +00:00
def get_remote_ip(headers)
return headers['X-Forwarded-For'] if headers && headers['X-Forwarded-For']
nil
end
2015-05-12 11:31:32 +00:00
def websocket_send(client_id, data)
msg = if data.class != Array
"[#{data.to_json}]"
else
data.to_json
end
2015-05-12 08:46:07 +00:00
log 'debug', "send #{msg}", client_id
if !@clients[client_id]
log 'error', "no such @clients for #{client_id}", client_id
return
end
2015-05-12 11:31:32 +00:00
@clients[client_id][:websocket].send(msg)
2015-05-12 08:46:07 +00:00
end
2012-12-24 13:53:50 +00:00
def check_unused_connections
log 'notice', 'check unused idle connections...'
2012-12-24 13:53:50 +00:00
idle_time_in_sec = 4 * 60
2012-12-24 13:53:50 +00:00
2015-01-13 16:03:58 +00:00
# close unused web socket sessions
@clients.each do |client_id, client|
2012-12-24 13:53:50 +00:00
2015-05-10 20:53:15 +00:00
next if ( client[:last_ping].to_i + idle_time_in_sec ) >= Time.now.utc.to_i
2012-12-24 13:53:50 +00:00
log 'notice', 'closing idle websocket connection', client_id
2012-12-24 13:53:50 +00:00
# remember to not use this connection anymore
client[:disconnect] = true
# try to close regular
client[:websocket].close_websocket
# delete session from client list
sleep 0.3
@clients.delete(client_id)
end
2012-12-24 13:53:50 +00:00
2015-01-13 16:03:58 +00:00
# close unused ajax long polling sessions
clients = Sessions.destroy_idle_sessions(idle_time_in_sec)
clients.each do |client_id|
log 'notice', 'closing idle long polling connection', client_id
end
2012-12-24 13:53:50 +00:00
end
2015-12-09 13:09:37 +00:00
def log(level, data, client_id = '-')
2013-03-10 23:14:31 +00:00
if !@options[:v]
return if level == 'debug'
end
puts "#{Time.now.utc.iso8601}:client(#{client_id}) #{data}"
2015-05-12 08:46:07 +00:00
#puts "#{Time.now.utc.iso8601}:#{ level }:client(#{ client_id }) #{ data }"
2012-08-03 22:46:05 +00:00
end
2012-07-23 22:22:23 +00:00
end