Class: Zashoku::Daemon

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

Instance Method Summary collapse

Constructor Details

#initialize(port:) ⇒ Daemon

Returns a new instance of Daemon.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/daemon.rb', line 45

def initialize(port:)
  @port = port
  @semaphore = Mutex.new

  Zashoku.logger = Logger.new(STDOUT)
  Zashoku.logger.level = Zashoku::CConf[:app][:log_level][:daemon]
  Zashoku.logger.info("server using zashoku v#{Version.join('.')}")
  # Load conf
  Zashoku.conf = DaemonConfig.new
  # Load modules
  Zashoku.modules = Zashoku::Module.load(Zashoku::CConf[:app][:modules][:daemon])
  # Update conf with module defaults
  Zashoku.conf.reload

  Zashoku.controllers =
    Zashoku.modules.keys.zip(Zashoku.modules.values.map(&:controller)).to_h

  Zashoku.controllers.each_value { |c| c.add_observer(self) }
end

Instance Method Details

#cleanupObject



113
114
115
116
# File 'lib/daemon.rb', line 113

def cleanup
  @server.exit
  exit
end

#lay_traps!Object



105
106
107
108
109
110
111
# File 'lib/daemon.rb', line 105

def lay_traps!
  Signal.trap('INT') do
    Thread.new do
      @semaphore.synchronize { cleanup }
    end
  end
end

#listenObject



65
66
67
68
69
70
71
# File 'lib/daemon.rb', line 65

def listen
  lay_traps!
  @server = Net::Server.new(@port)
  @server.handler = method(:respond)
  Zashoku.logger.info('server listening')
  sleep
end

#respond(message) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/daemon.rb', line 78

def respond(message)
  Zashoku.logger.debug("daemon.respond #{message}")
  case message['msg']
  when 'modules'
    Zashoku.modules.map { |m, _| m }
  when 'items'
    Zashoku.command(mod: message[:mod], meth: :items)
  when 'fwd'
    Zashoku.command(message)
  when 'helo'
    Zashoku.logger.info("Client saying helo #{message}")
    if message['zv'] == Zashoku::Version && message['app'] == Zashoku::CConf[:app][:name]
      'ok'
    else
      'rejected'
    end
  when 'disconnect'
    nil
  when 'stop'
    cleanup
  when 'up?'
    true
  else
    'what?'
  end
end

#update(e) ⇒ Object



73
74
75
76
# File 'lib/daemon.rb', line 73

def update(e)
  Zashoku.logger.debug("controller #{e['sender']} sent update #{e['event']}")
  @server.event(e)
end