Arie/serveme

View on GitHub
script/logdaemon

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
# frozen_string_literal: true

require File.expand_path('../config/boot', __dir__)
require 'dante'
require 'eventmachine'
require 'socket'
require 'sidekiq'
require 'active_support'
require 'active_support/core_ext'
require 'tf2_line_parser'
require File.expand_path('../app/workers/log_worker', __dir__)
require File.expand_path('../app/helpers/log_line_helper', __dir__)

STREAMING_LOG_DIR = File.expand_path('../log/streaming', __dir__)

class Handler < EM::Connection
  include LogLineHelper

  def receive_data(data)
    log_line = ActiveSupport::Multibyte::Chars.new(data).tidy_bytes[5..]
    LogWorker.perform_async(log_line.to_s) if interesting_line?(log_line)
    matches = log_line.match(LogWorker::LOG_LINE_REGEX)
    write_log(matches[:secret], matches[:line]) if matches && matches[:line] && matches[:secret].present?
  end

  def write_log(secret, line)
    return unless secret =~ /^\d+$/

    File.open(File.join(STREAMING_LOG_DIR, "#{secret}.log"), 'a') do |f|
      f.puts line
    end
  end
end

runner = Dante::Runner.new('logdaemon')
runner.with_options do |opts|
  opts.on('-i', '--ip IP', String, 'IP to bind to') do |ip|
    options[:ip] = ip
  end
end
runner.description = 'TF2 server logdaemon'

runner.execute do |opts|
  ip    = opts[:ip]
  port  = opts[:port]
  puts "Listening on #{ip}:#{port}..."
  FileUtils.mkdir_p(STREAMING_LOG_DIR)
  EM.run do
    EM.open_datagram_socket(ip, port, Handler)
  end
end