Module: Videoreg

Defined in:
lib/videoreg.rb,
lib/videoreg/base.rb,
lib/videoreg/util.rb,
lib/videoreg/config.rb,
lib/videoreg/lockfile.rb,
lib/videoreg/registrar.rb

Overview

Main videoreg module

Defined Under Namespace

Classes: Base, Config, Lockfile, Registrar, Util

Constant Summary collapse

VERSION =

configurable constants

"0.1"
DAEMON_NAME =
"videoreg"
MAX_THREAD_WAIT_LIMIT_SEC =

time while daemon waits until capture thread exists

600
UDEV_RULES_FILE =
'/etc/udev/rules.d/50-udev-videoreg.rules'
"webcam"
ALLOWED_CONFIG_OPTIONS =

internal constants

%w[mq_host mq_queue pid_path log_path device]
MSG_HALT =
'HALT'
MSG_RECOVER =
'RECOVER'
MSG_PAUSE =
'PAUSE'
MSG_RESUME =
'RESUME'
MSG2ACTION =
{MSG_HALT => :halt!, MSG_PAUSE => :pause!, MSG_RESUME => :resume!, MSG_RECOVER => :recover!}

Class Method Summary collapse

Class Method Details

.calc_reg_list(device = :all) ⇒ Object

Calculate current registrars list



123
124
125
# File 'lib/videoreg.rb', line 123

def calc_reg_list(device = :all)
  registrars.find_all { |dev, reg| device.to_sym == :all || device.to_s == dev }.map { |vp| vp[1] }
end

.init_dante_runnerObject

Initiate new dante runner



128
129
130
131
132
133
# File 'lib/videoreg.rb', line 128

def init_dante_runner
  dante_opts = {:pid_path => '/tmp/videoreg.pid', :log_path => opt.log_path}
  dante_opts.merge!(:kill => true) if opt.action == :kill
  dante_opts.merge!(:pid_path => opt.pid_path) if opt.pid_path
  Dante::Runner.new(DAEMON_NAME, dante_opts)
end

.loggerObject



90
91
92
# File 'lib/videoreg.rb', line 90

def logger
  Videoreg::Base.logger
end

.mq_disconnect(connection) ⇒ Object

Disconnect from RabbitMQ



46
47
48
49
# File 'lib/videoreg.rb', line 46

def mq_disconnect(connection)
  logger.info "Disconnecting from RabbitMQ..."
  connection.close { EM.stop { exit } }
end

.mq_listen(&block) ⇒ Object

Listen the incoming messages from RabbitMQ



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/videoreg.rb', line 52

def mq_listen(&block)
  Thread.new {
    begin
      logger.info "New messaging thread created for RabbitMQ #{opt.mq_host} / #{opt.mq_queue}"
      AMQP.start(:host => opt.mq_host) do |connection|
        q = AMQP::Channel.new(connection).queue(opt.mq_queue)
        q.subscribe do |msg|
          Videoreg::Base.logger.info "Received message from RabbitMQ #{msg}..."
          block.call(connection, msg) if block_given?
        end
        Signal.add_trap("TERM") { q.delete; mq_disconnect(connection) }
        Signal.add_trap(0) { q.delete; mq_disconnect(connection) }
      end
    rescue => e
      logger.error "Error during establishing the connection to RabbitMQ: #{e.message}"
      @dante_runner.stop if @dante_runner
    end
  }
end

.mq_send(message, arg = nil) ⇒ Object

Send a message to the RabbitMQ



73
74
75
76
77
78
79
80
# File 'lib/videoreg.rb', line 73

def mq_send(message, arg = nil)
  AMQP.start(:host => opt.mq_host) do |connection|
    channel = AMQP::Channel.new(connection)
    logger.info "Publish message to RabbitMQ '#{message}' with arg '#{arg}' to '#{opt.mq_queue}'..."
    channel.default_exchange.publish({:msg => message, :arg => arg}.to_json, :routing_key => opt.mq_queue)
    EM.add_timer(0.5) { mq_disconnect(connection) }
  end
end

.opt(*args) ⇒ Object

Options



97
98
99
100
101
102
103
104
# File 'lib/videoreg.rb', line 97

def opt(*args)
  if !args.empty? && args[0].is_a?(Hash)
    op = args[0].flatten
    run_options.send("#{op[0]}=", op[1])
  else
    run_options
  end
end

.reg(&block) ⇒ Object

Shortcut to create new registrar’s configuration



114
115
116
117
118
119
120
# File 'lib/videoreg.rb', line 114

def reg(&block)
  r = Registrar.new
  Signal.add_trap(0) { r.safe_release! }
  r.logger = opt.logger if opt.logger
  r.config.instance_eval(&block)
  registrars[r.config.device] = r
end

.registrarsObject



86
87
88
# File 'lib/videoreg.rb', line 86

def registrars
  @registered_regs
end

.run(device = :all, action = opt.action) ⇒ Object

Shortcut to run action on registrar(s)



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/videoreg.rb', line 169

def run(device = :all, action = opt.action)

  # Input
  @registrars = calc_reg_list(device)
  @dante_runner = init_dante_runner
  opt.action, action = :run, :run if @dante_runner.daemon_stopped? && opt.action == :recover

  # Main actions switch
  puts "Running command '#{opt.action}' for device(s): '#{device}'..."
  case action
    when :kill then
      @dante_runner.stop
    when :pause then
      mq_send(MSG_PAUSE, device) if @dante_runner.daemon_running?
    when :resume then
      mq_send(MSG_RESUME, device) if @dante_runner.daemon_running?
    when :recover then
      mq_send(MSG_RECOVER, device) if @dante_runner.daemon_running?
    when :ensure then
      uptime = (@dante_runner.daemon_running?) ? Time.now - File.stat(opt.pid_path).ctime : 0
      [{:daemon_running? => @dante_runner.daemon_running?, :uptime => uptime}] + @registrars.map { |reg|
        {
            :device => reg.device,
            :device_exists? => reg.device_exists?,
            :process_alive? => reg.process_alive?,
            :paused? => reg.paused?
        }
      }
    when :halt then
      mq_send(MSG_HALT, device) if @dante_runner.daemon_running?
    when :run then
      @dante_runner.execute(:daemonize => true) {
        logger.info "Starting daemon with options: #{opt.marshal_dump}"
        run_daemon(@registrars)
      }
    when :reset then
      @registrars.each { |reg|
        reg.force_release_lock!
      }
      logger.info "Forced to release pidfile #{opt.pid_path}"
      File.unlink(opt.pid_path) if File.exists?(opt.pid_path)
    else
      raise "Unsupported action #{action} provided to runner!"
  end
end

.run_daemon(regs) ⇒ Object

Run daemon



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/videoreg.rb', line 136

def run_daemon(regs)
  Signal.add_trap("TERM") { File.unlink(opt.pid_path) if File.exists?(opt.pid_path) }
  @time_started = Time.now
  # Run message thread
  mq_listen do |connection, message|
    begin
      raise "Unexpected message struct received: #{message}!" unless (message = JSON.parse(message)).is_a?(Hash)
      opt.device = message["arg"] if message["arg"]
      if (action = MSG2ACTION[message["msg"]])
        logger.info "#{message["msg"]} MESSAGE RECEIVED!"
        calc_reg_list(opt.device).each { |reg| reg.send(action) }
      else
        logger.error "UNKNOWN MESSAGE RECEIVED!"
      end
    rescue => e
      logger.error "Exception during incoming message processing: #{e.message}: \n#{e.backtrace.join("\n")}"
    end
  end
  # Run main thread
  regs.map { |reg|
    logger.info "Starting continuous registration from device #{reg.device}..."
    {:reg => reg, :thread => reg.continuous}
  }.each { |reg_hash|
    while true do # avoid deadlock exception
      reg_hash[:thread].join(MAX_THREAD_WAIT_LIMIT_SEC)
      break if reg_hash[:reg].terminated? # break if thread was terminated
    end if reg_hash[:reg] && reg_hash[:thread]
  }
  @time_ended = Time.now
  logger.info "Daemon finished execution. Uptime #{@time_ended - @time_started} sec"
end

.run_optionsObject



82
83
84
# File 'lib/videoreg.rb', line 82

def run_options
  @run_options
end

.version_infoObject

Version info



41
42
43
# File 'lib/videoreg.rb', line 41

def version_info
  "#{DAEMON_NAME} v.#{VERSION}"
end