sessions.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. module Sessions
  2. # get application root directory
  3. @root = Dir.pwd.to_s
  4. if @root.blank? || @root == '/'
  5. @root = Rails.root
  6. end
  7. # get working directories
  8. @path = "#{@root}/tmp/websocket_#{Rails.env}"
  9. # create global vars for threads
  10. @@client_threads = {} # rubocop:disable Style/ClassVars
  11. =begin
  12. start new session
  13. Sessions.create(client_id, session_data, { type: 'websocket' })
  14. returns
  15. true|false
  16. =end
  17. def self.create(client_id, session, meta)
  18. path = "#{@path}/#{client_id}"
  19. path_tmp = "#{@path}/tmp/#{client_id}"
  20. session_file = "#{path_tmp}/session"
  21. # collect session data
  22. meta[:last_ping] = Time.now.utc.to_i
  23. data = {
  24. user: session,
  25. meta: meta,
  26. }
  27. content = data.to_json
  28. # store session data in session file
  29. FileUtils.mkpath path_tmp
  30. File.open(session_file, 'wb') do |file|
  31. file.write content
  32. end
  33. # destroy old session if needed
  34. if File.exist?(path)
  35. Sessions.destroy(client_id)
  36. end
  37. # move to destination directory
  38. FileUtils.mv(path_tmp, path)
  39. # send update to browser
  40. return if !session || session['id'].blank?
  41. send(
  42. client_id,
  43. {
  44. event: 'ws:login',
  45. data: { success: true },
  46. }
  47. )
  48. end
  49. =begin
  50. list of all session
  51. client_ids = Sessions.sessions
  52. returns
  53. ['4711', '4712']
  54. =end
  55. def self.sessions
  56. path = "#{@path}/"
  57. # just make sure that spool path exists
  58. if !File.exist?(path)
  59. FileUtils.mkpath path
  60. end
  61. data = []
  62. Dir.foreach(path) do |entry|
  63. next if entry == '.'
  64. next if entry == '..'
  65. next if entry == 'tmp'
  66. next if entry == 'spool'
  67. data.push entry.to_s
  68. end
  69. data
  70. end
  71. =begin
  72. list of all session
  73. Sessions.session_exists?(client_id)
  74. returns
  75. true|false
  76. =end
  77. def self.session_exists?(client_id)
  78. session_dir = "#{@path}/#{client_id}"
  79. return false if !File.exist?(session_dir)
  80. session_file = "#{session_dir}/session"
  81. return false if !File.exist?(session_file)
  82. true
  83. end
  84. =begin
  85. list of all session with data
  86. client_ids_with_data = Sessions.list
  87. returns
  88. {
  89. '4711' => {
  90. user: {
  91. 'id' => 123,
  92. },
  93. meta: {
  94. type: 'websocket',
  95. last_ping: time_of_last_ping,
  96. }
  97. },
  98. '4712' => {
  99. user: {
  100. 'id' => 124,
  101. },
  102. meta: {
  103. type: 'ajax',
  104. last_ping: time_of_last_ping,
  105. }
  106. },
  107. }
  108. =end
  109. def self.list
  110. client_ids = sessions
  111. session_list = {}
  112. client_ids.each do |client_id|
  113. data = get(client_id)
  114. next if !data
  115. session_list[client_id] = data
  116. end
  117. session_list
  118. end
  119. =begin
  120. destroy session
  121. Sessions.destroy(client_id)
  122. returns
  123. true|false
  124. =end
  125. def self.destroy(client_id)
  126. path = "#{@path}/#{client_id}"
  127. FileUtils.rm_rf path
  128. end
  129. =begin
  130. destroy idle session
  131. list_of_client_ids = Sessions.destroy_idle_sessions
  132. returns
  133. ['4711', '4712']
  134. =end
  135. def self.destroy_idle_sessions(idle_time_in_sec = 240)
  136. list_of_closed_sessions = []
  137. clients = Sessions.list
  138. clients.each do |client_id, client|
  139. if !client[:meta] || !client[:meta][:last_ping] || ( client[:meta][:last_ping].to_i + idle_time_in_sec ) < Time.now.utc.to_i
  140. list_of_closed_sessions.push client_id
  141. Sessions.destroy(client_id)
  142. end
  143. end
  144. list_of_closed_sessions
  145. end
  146. =begin
  147. touch session
  148. Sessions.touch(client_id)
  149. returns
  150. true|false
  151. =end
  152. def self.touch(client_id)
  153. data = get(client_id)
  154. return false if !data
  155. path = "#{@path}/#{client_id}"
  156. data[:meta][:last_ping] = Time.now.utc.to_i
  157. File.open("#{path}/session", 'wb' ) do |file|
  158. file.flock(File::LOCK_EX)
  159. file.write data.to_json
  160. file.flock(File::LOCK_UN)
  161. end
  162. true
  163. end
  164. =begin
  165. get session data
  166. data = Sessions.get(client_id)
  167. returns
  168. {
  169. user: {
  170. 'id' => 123,
  171. },
  172. meta: {
  173. type: 'websocket',
  174. last_ping: time_of_last_ping,
  175. }
  176. }
  177. =end
  178. def self.get(client_id)
  179. session_dir = "#{@path}/#{client_id}"
  180. session_file = "#{session_dir}/session"
  181. data = nil
  182. # if no session dir exists, session got destoried
  183. if !File.exist?(session_dir)
  184. destroy(client_id)
  185. log('debug', "missing session directory #{session_dir} for '#{client_id}', remove session.")
  186. return
  187. end
  188. # if only session file is missing, then it's an error behavior
  189. if !File.exist?(session_file)
  190. destroy(client_id)
  191. log('error', "missing session file for '#{client_id}', remove session.")
  192. return
  193. end
  194. begin
  195. File.open(session_file, 'rb') do |file|
  196. file.flock(File::LOCK_SH)
  197. all = file.read
  198. file.flock(File::LOCK_UN)
  199. data_json = JSON.parse(all)
  200. if data_json
  201. data = symbolize_keys(data_json)
  202. data[:user] = data_json['user'] # for compat. reasons
  203. end
  204. end
  205. rescue => e
  206. log('error', e.inspect)
  207. destroy(client_id)
  208. log('error', "error in reading/parsing session file '#{session_file}', remove session.")
  209. return
  210. end
  211. data
  212. end
  213. =begin
  214. send message to client
  215. Sessions.send(client_id_of_recipient, data)
  216. returns
  217. true|false
  218. =end
  219. def self.send(client_id, data)
  220. path = "#{@path}/#{client_id}/"
  221. filename = "send-#{Time.now.utc.to_f}"
  222. location = "#{path}#{filename}"
  223. check = true
  224. count = 0
  225. while check
  226. if File.exist?(location)
  227. count += 1
  228. location = "#{path}#{filename}-#{count}"
  229. else
  230. check = false
  231. end
  232. end
  233. return false if !File.directory? path
  234. begin
  235. File.open(location, 'wb') do |file|
  236. file.flock(File::LOCK_EX)
  237. file.write data.to_json
  238. file.flock(File::LOCK_UN)
  239. file.close
  240. end
  241. rescue => e
  242. log('error', e.inspect)
  243. log('error', "error in writing message file '#{location}'")
  244. return false
  245. end
  246. true
  247. end
  248. =begin
  249. send message to recipient client
  250. Sessions.send_to(user_id, data)
  251. e. g.
  252. Sessions.send_to(user_id, {
  253. event: 'session:takeover',
  254. data: {
  255. taskbar_id: 12312
  256. },
  257. })
  258. returns
  259. true|false
  260. =end
  261. def self.send_to(user_id, data)
  262. # list all current clients
  263. client_list = sessions
  264. client_list.each do |client_id|
  265. session = Sessions.get(client_id)
  266. next if !session
  267. next if !session[:user]
  268. next if !session[:user]['id']
  269. next if session[:user]['id'].to_i != user_id.to_i
  270. Sessions.send(client_id, data)
  271. end
  272. true
  273. end
  274. =begin
  275. send message to all authenticated client
  276. Sessions.broadcast(data)
  277. returns
  278. [array_with_client_ids_of_recipients]
  279. broadcase also to not authenticated client
  280. Sessions.broadcast(data, 'public') # public|authenticated
  281. broadcase also not to sender
  282. Sessions.broadcast(data, 'public', sender_user_id)
  283. =end
  284. def self.broadcast(data, recipient = 'authenticated', sender_user_id = nil)
  285. # list all current clients
  286. recipients = []
  287. client_list = sessions
  288. client_list.each do |client_id|
  289. session = Sessions.get(client_id)
  290. next if !session
  291. if recipient != 'public'
  292. next if session[:user].blank?
  293. next if session[:user]['id'].blank?
  294. end
  295. if sender_user_id
  296. next if session[:user] && session[:user]['id'] && session[:user]['id'].to_i == sender_user_id.to_i
  297. end
  298. Sessions.send(client_id, data)
  299. recipients.push client_id
  300. end
  301. recipients
  302. end
  303. =begin
  304. get messages for client
  305. messages = Sessions.queue(client_id_of_recipient)
  306. returns
  307. [
  308. {
  309. key1 => 'some data of message 1',
  310. key2 => 'some data of message 1',
  311. },
  312. {
  313. key1 => 'some data of message 2',
  314. key2 => 'some data of message 2',
  315. },
  316. ]
  317. =end
  318. def self.queue(client_id)
  319. path = "#{@path}/#{client_id}/"
  320. data = []
  321. files = []
  322. Dir.foreach(path) do |entry|
  323. next if entry == '.'
  324. next if entry == '..'
  325. files.push entry
  326. end
  327. files.sort.each do |entry|
  328. next if !entry.start_with?('send')
  329. message = Sessions.queue_file_read(path, entry)
  330. next if !message
  331. data.push message
  332. end
  333. data
  334. end
  335. def self.queue_file_read(path, filename)
  336. location = "#{path}#{filename}"
  337. message = ''
  338. File.open(location, 'rb') do |file|
  339. file.flock(File::LOCK_EX)
  340. message = file.read
  341. file.flock(File::LOCK_UN)
  342. end
  343. File.delete(location)
  344. return if message.blank?
  345. begin
  346. JSON.parse(message)
  347. rescue => e
  348. log('error', "can't parse queue message: #{message}, #{e.inspect}")
  349. nil
  350. end
  351. end
  352. =begin
  353. remove all session and spool messages
  354. Sessions.cleanup
  355. =end
  356. def self.cleanup
  357. return true if !File.exist?(@path)
  358. FileUtils.rm_rf @path
  359. true
  360. end
  361. =begin
  362. create spool messages
  363. Sessions.spool_create(some: 'data')
  364. =end
  365. def self.spool_create(data)
  366. msg = JSON.generate(data)
  367. path = "#{@path}/spool/"
  368. FileUtils.mkpath path
  369. data = {
  370. msg: msg,
  371. timestamp: Time.now.utc.to_i,
  372. }
  373. file_path = "#{path}/#{Time.now.utc.to_f}-#{rand(99_999)}"
  374. File.open(file_path, 'wb') do |file|
  375. file.flock(File::LOCK_EX)
  376. file.write data.to_json
  377. file.flock(File::LOCK_UN)
  378. end
  379. end
  380. =begin
  381. get spool messages
  382. Sessions.spool_list(junger_then, for_user_id)
  383. =end
  384. def self.spool_list(timestamp, current_user_id)
  385. path = "#{@path}/spool/"
  386. FileUtils.mkpath path
  387. data = []
  388. to_delete = []
  389. files = []
  390. Dir.foreach(path) do |entry|
  391. next if entry == '.'
  392. next if entry == '..'
  393. files.push entry
  394. end
  395. files.sort.each do |entry|
  396. filename = "#{path}/#{entry}"
  397. next if !File.exist?(filename)
  398. File.open(filename, 'rb') do |file|
  399. file.flock(File::LOCK_SH)
  400. message = file.read
  401. file.flock(File::LOCK_UN)
  402. message_parsed = {}
  403. begin
  404. spool = JSON.parse(message)
  405. message_parsed = JSON.parse(spool['msg'])
  406. rescue => e
  407. log('error', "can't parse spool message: #{message}, #{e.inspect}")
  408. to_delete.push "#{path}/#{entry}"
  409. next
  410. end
  411. # ignore message older then 48h
  412. if spool['timestamp'] + (2 * 86_400) < Time.now.utc.to_i
  413. to_delete.push "#{path}/#{entry}"
  414. next
  415. end
  416. # add spool attribute to push spool info to clients
  417. message_parsed['spool'] = true
  418. # only send not already older messages
  419. if !timestamp || timestamp < spool['timestamp']
  420. # spool to recipient list
  421. if message_parsed['recipient'] && message_parsed['recipient']['user_id']
  422. message_parsed['recipient']['user_id'].each do |user_id|
  423. next if current_user_id != user_id
  424. message = message_parsed
  425. if message_parsed['event'] == 'broadcast'
  426. message = message_parsed['data']
  427. end
  428. item = {
  429. type: 'direct',
  430. message: message,
  431. }
  432. data.push item
  433. end
  434. # spool to every client
  435. else
  436. message = message_parsed
  437. if message_parsed['event'] == 'broadcast'
  438. message = message_parsed['data']
  439. end
  440. item = {
  441. type: 'broadcast',
  442. message: message,
  443. }
  444. data.push item
  445. end
  446. end
  447. end
  448. end
  449. to_delete.each do |file|
  450. File.delete(file)
  451. end
  452. data
  453. end
  454. =begin
  455. delete spool messages
  456. Sessions.spool_delete
  457. =end
  458. def self.spool_delete
  459. path = "#{@path}/spool/"
  460. FileUtils.rm_rf path
  461. end
  462. def self.jobs(node_id = nil)
  463. # just make sure that spool path exists
  464. if !File.exist?(@path)
  465. FileUtils.mkpath(@path)
  466. end
  467. # dispatch sessions
  468. if node_id.blank? && ENV['ZAMMAD_SESSION_JOBS_CONCURRENT'].to_i.positive?
  469. dispatcher_pid = Process.pid
  470. node_count = ENV['ZAMMAD_SESSION_JOBS_CONCURRENT'].to_i
  471. node_pids = []
  472. (1..node_count).each do |worker_node_id|
  473. node_pids << fork do
  474. title = "Zammad Session Jobs Node ##{worker_node_id}: dispatch_pid:#{dispatcher_pid} -> worker_pid:#{Process.pid}"
  475. $PROGRAM_NAME = title
  476. log('info', "#{title} started.")
  477. ::Sessions.jobs(worker_node_id)
  478. sleep node_count
  479. rescue Interrupt # rubocop:disable Layout/RescueEnsureAlignment
  480. nil
  481. end
  482. end
  483. Signal.trap 'SIGTERM' do
  484. node_pids.each do |node_pid|
  485. Process.kill 'TERM', node_pid
  486. end
  487. Process.waitall
  488. raise SignalException, 'SIGTERM'
  489. end
  490. # displatch client_ids to nodes
  491. loop do
  492. # nodes
  493. nodes_stats = Sessions::Node.stats
  494. client_ids = sessions
  495. client_ids.each do |client_id|
  496. # ask nodes for nodes
  497. next if nodes_stats[client_id]
  498. # assigne to node
  499. Sessions::Node.session_assigne(client_id)
  500. sleep 1
  501. end
  502. sleep 1
  503. end
  504. end
  505. Thread.abort_on_exception = true
  506. loop do
  507. if node_id
  508. # register node
  509. Sessions::Node.register(node_id)
  510. # watch for assigned sessions
  511. client_ids = Sessions::Node.sessions_by(node_id)
  512. else
  513. client_ids = sessions
  514. end
  515. client_ids.each do |client_id|
  516. # connection already open, ignore
  517. next if @@client_threads[client_id]
  518. # get current user
  519. session_data = Sessions.get(client_id)
  520. next if session_data.blank?
  521. next if session_data[:user].blank?
  522. next if session_data[:user]['id'].blank?
  523. user = User.lookup(id: session_data[:user]['id'])
  524. next if user.blank?
  525. # start client thread
  526. next if @@client_threads[client_id].present?
  527. @@client_threads[client_id] = true
  528. @@client_threads[client_id] = Thread.new do
  529. thread_client(client_id, 0, Time.now.utc, node_id)
  530. @@client_threads[client_id] = nil
  531. log('debug', "close client (#{client_id}) thread")
  532. if ActiveRecord::Base.connection.owner == Thread.current
  533. ActiveRecord::Base.connection.close
  534. end
  535. end
  536. sleep 1
  537. end
  538. sleep 1
  539. end
  540. end
  541. =begin
  542. check if thread for client_id is running
  543. Sessions.thread_client_exists?(client_id)
  544. returns
  545. thread
  546. =end
  547. def self.thread_client_exists?(client_id)
  548. @@client_threads[client_id]
  549. end
  550. =begin
  551. start client for browser
  552. Sessions.thread_client(client_id)
  553. returns
  554. thread
  555. =end
  556. def self.thread_client(client_id, try_count = 0, try_run_time = Time.now.utc, node_id)
  557. log('debug', "LOOP #{node_id}.#{client_id} - #{try_count}")
  558. begin
  559. Sessions::Client.new(client_id, node_id)
  560. rescue => e
  561. log('error', "thread_client #{client_id} exited with error #{e.inspect}")
  562. log('error', e.backtrace.join("\n ") )
  563. sleep 10
  564. begin
  565. ActiveRecord::Base.connection_pool.release_connection
  566. rescue => e
  567. log('error', "Can't reconnect to database #{e.inspect}")
  568. end
  569. try_run_max = 10
  570. try_count += 1
  571. # reset error counter if to old
  572. if try_run_time + ( 60 * 5 ) < Time.now.utc
  573. try_count = 0
  574. end
  575. try_run_time = Time.now.utc
  576. # restart job again
  577. if try_run_max > try_count
  578. thread_client(client_id, try_count, try_run_time, node_id)
  579. end
  580. raise "STOP thread_client for client #{node_id}.#{client_id} after #{try_run_max} tries"
  581. end
  582. log('debug', "/LOOP #{node_id}.#{client_id} - #{try_count}")
  583. end
  584. def self.symbolize_keys(hash)
  585. hash.each_with_object({}) do |(key, value), result|
  586. new_key = case key
  587. when String then key.to_sym
  588. else key
  589. end
  590. new_value = case value
  591. when Hash then symbolize_keys(value)
  592. else value
  593. end
  594. result[new_key] = new_value
  595. end
  596. end
  597. # we use it in rails and non rails context
  598. def self.log(level, message)
  599. if defined?(Rails)
  600. if level == 'debug'
  601. Rails.logger.debug { message }
  602. elsif level == 'notice'
  603. Rails.logger.notice message
  604. else
  605. Rails.logger.error message
  606. end
  607. return
  608. end
  609. puts "#{Time.now.utc.iso8601}:#{level} #{message}" # rubocop:disable Rails/Output
  610. end
  611. end