Class: Adminix::Watcher
- Inherits:
-
Object
- Object
- Adminix::Watcher
- Defined in:
- lib/adminix/watcher.rb
Constant Summary collapse
- SYNC_PERIOD =
5.freeze
- DEFAULT_WEBSOCKET_HOST =
'wss://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.
- #run! ⇒ Object
- #start ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(opts) ⇒ Watcher
Returns a new instance of Watcher.
20 21 22 23 24 25 26 27 28 |
# File 'lib/adminix/watcher.rb', line 20 def initialize(opts) @pid_full = '/tmp/adminix.pid' @service = Service.instance @ws_client = nil ws_path = opts[:websocket_host] || ENV['ADMINIX_WEBSOCKET_HOST'] || DEFAULT_WEBSOCKET_HOST @ws_uri = "#{ws_path}?secret_key=#{config.secret_key}" @ws_channel = { channel: 'ServiceChannel', service_id: @service.id } end |
Class Method Details
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 |
#run! ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/adminix/watcher.rb', line 30 def run! trap_signal EventMachine.run do @ws_client = ActionCableClient.new(@ws_uri, @ws_channel) @ws_client.connected do |msg| puts 'Connection established' end @ws_client.disconnected do system.log 'Disconnected. Reconnecting...' sleep(2) @ws_client.connect! end @ws_client.received do |msg| = msg['message'] || {} case ['type'] when 'restart' then @service.restart! when 'sync' then @service.sync(@ws_client, ['data']) end end EventMachine.add_periodic_timer(SYNC_PERIOD) do @ws_client.perform(:sync, @service.to_cable) if @ws_client.subscribed? 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.}" 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 |