Files
maptool/lib/maptool/can_recorder.rb
T

92 lines
2.8 KiB
Ruby

require "fileutils"
module Maptool
module Can
# Recording the bus on the server: can-recorder (can-recorder/, Rust)
# writes every interface's frames into ASAM MDF4 files, one per segment
# (`<dir>/<UTC start>.mf4`, asammdf with a DBC, CSS Electronics' tools);
# this starts it, stops it (SIGTERM: the segment being recorded is
# written) and lists what it wrote. Segments older than `keep` seconds
# go (it's diagnostics, ~85 MB an hour at 1000 frames/s): when listed and
# every segment while recording; `keep` nil keeps them all.
class Recorder
NAME = /\A\d{8}-\d{6}\.mf4\z/
STOP_WAIT = 10 # s for the last segment to be written
attr_reader :dir, :error, :started_at
def initialize(dir, interfaces, binary: ENV.fetch("CAN_RECORDER", "can-recorder"), segment: 300,
keep: (ENV.fetch("CAN_REC_KEEP_HOURS", "24").to_f * 3600).then { |s| s.positive? ? s : nil })
@dir = dir
@keep = keep
@interfaces = interfaces
@binary = binary
@segment = segment
@mutex = Mutex.new
end
def running?
@waiter&.alive? || false
end
def start
@mutex.synchronize do
return if running?
FileUtils.mkdir_p(@dir)
pid = Process.spawn(@binary, "--segment", @segment.to_s, @dir, *@interfaces)
@waiter = Process.detach(pid)
@pid = pid
@started_at = Time.now.to_f
@error = nil
waiter = @waiter
Thread.new { loop { prune; break if waiter.join(@segment) } }
rescue SystemCallError => e
@error = "#{@binary}: #{e.message}"
raise
end
end
def stop
@mutex.synchronize do
return unless running?
Process.kill("TERM", @pid)
@waiter.join(STOP_WAIT) or Process.kill("KILL", @pid)
status = @waiter.value
@error = "#{@binary} exited with #{status.exitstatus}" unless status.success?
@started_at = nil
end
end
# The newest first.
def files
return [] unless Dir.exist?(@dir)
prune
Dir.children(@dir).grep(NAME).sort.reverse.map do |name|
stat = File.stat(File.join(@dir, name))
{ name: name, size: stat.size, at: stat.mtime.to_f }
end
end
def prune
return unless @keep && Dir.exist?(@dir)
old = Time.now - @keep
Dir.children(@dir).grep(NAME).each do |name|
path = File.join(@dir, name)
File.delete(path) if File.mtime(path) < old
rescue SystemCallError
nil # gone meanwhile
end
end
def path(name)
path = File.join(@dir, name)
path if NAME.match?(name) && File.file?(path)
end
end
end
end