Class: Adminix::Watcher
- Inherits:
-
Object
- Object
- Adminix::Watcher
- Defined in:
- lib/adminix/watcher.rb
Constant Summary collapse
- SYNC_PERIOD =
5.freeze
- WEBSOCKET_HOST =
'ws://api.adminix.io/websocket'.freeze
- SERVICE_CHANNEL =
'ServiceChannel'.freeze
Class Method Summary collapse
Instance Method Summary collapse
- #get_pid ⇒ Object
-
#initialize(opts) ⇒ Watcher
constructor
A new instance of Watcher.
- #publish_message(action, data) ⇒ Object
- #run! ⇒ Object
- #start ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(opts) ⇒ Watcher
Returns a new instance of Watcher.
24 25 26 27 28 29 30 |
# File 'lib/adminix/watcher.rb', line 24 def initialize(opts) @socket_url = opts[:websocket_host] || ENV['ADMINIX_WEBSOCKET_HOST'] || WEBSOCKET_HOST @socket_url = "#{@socket_url}?secret_key=#{config.secret_key}" @service = Service.instance @client = nil @pid_full = '/tmp/adminix.pid' end |
Class Method Details
.run!(options) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/adminix/watcher.rb', line 6 def self.run!() watcher = Watcher.new() if [:stop_daemon] watcher.stop else if [:daemonize] watcher.start else watcher.run! end end end |
Instance Method Details
#get_pid ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/adminix/watcher.rb', line 57 def get_pid if File.exists?(@pid_full) file = File.new(@pid_full, "r") pid = file.read file.close pid else 0 end end |
#publish_message(action, data) ⇒ Object
50 51 52 53 54 55 |
# File 'lib/adminix/watcher.rb', line 50 def (action, data) identifier = { channel: SERVICE_CHANNEL, service_id: @service.id } data = { action: action, data: data } @client.publish(identifier, data) end |
#run! ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/adminix/watcher.rb', line 32 def run! trap_signal EventMachine.run do @client = WebsocketClient.new(@socket_url) do on_disconnect(@client) end @client.connect do || (@client, ) end EventMachine.add_periodic_timer(SYNC_PERIOD) do (:sync, @service.to_cable) if @client.connected end end end |
#start ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/adminix/watcher.rb', line 69 def start pid = get_pid if pid != 0 warn "Daemon is already running" exit -1 end pid = fork { run! } begin file = File.new(@pid_full, "w") file.write(pid) file.close Process.detach(pid) rescue => exc Process.kill('TERM', pid) warn "Cannot start daemon: #{exc.message}" end end |
#stop ⇒ Object
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/adminix/watcher.rb', line 90 def stop pid = get_pid begin EM.stop rescue end if pid != 0 Process.kill('HUP', pid.to_i) File.delete(@pid_full) system.log "Stopped" else warn "Daemon is not running" exit -1 end end |