Class: Enviroblyd::Daemon

Inherits:
Object
  • Object
show all
Defined in:
lib/enviroblyd/daemon.rb

Constant Summary collapse

MAX_MESSAGE_SIZE =

bytes

6000
PORT =
ENV.fetch("ENVIROBLYD_PORT", 63106).to_i

Instance Method Summary collapse

Constructor Details

#initializeDaemon

Returns a new instance of Daemon.



9
10
11
12
13
14
# File 'lib/enviroblyd/daemon.rb', line 9

def initialize
  imds = Enviroblyd::IMDS.new
  @host = imds.private_ipv4
  @threads = []
  @shutdown = false
end

Instance Method Details

#listenObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/enviroblyd/daemon.rb', line 16

def listen
  @server = TCPServer.new @host, PORT
  puts "Listening on #{@host}:#{PORT}"
  Enviroblyd::Web.register

  until @shutdown do
    @threads << Thread.start(@server.accept) do |client|
      message = client.recv(MAX_MESSAGE_SIZE)
      command = Enviroblyd::Command.new message

      unless command.valid?
        puts "Invalid message received: #{message}"
        client.puts "Invalid message"
        next
      end

      client.puts "OK"
      client.close
      command.run
    ensure
      client.close
    end

    delete_dead_threads
    GC.start
    GC.compact
  end
end

#shutdownObject



45
46
47
# File 'lib/enviroblyd/daemon.rb', line 45

def shutdown
  @threads.each(&:join)
end