#!/usr/bin/env ruby Dir.chdir(File.join(File.dirname(__FILE__), '..')) faf_lib_path = File.expand_path(File.dirname(__FILE__) + "/../lib") $:.unshift(faf_lib_path) unless $:.include?(faf_lib_path) # include dependencies without using rubygems (to save memory) $:.unshift('vendor/json-1.5.0/lib') $:.unshift('vendor/daemons-1.1.0/lib') require 'vendor/json-1.5.0/lib/json/pure' require 'vendor/daemons-1.1.0/lib/daemons' require 'ostruct' require 'optparse' require 'socket' require 'etc' require 'fire_and_forget' options = OpenStruct.new options.socket = FireAndForget::DEFAULT_SOCKET options.gid = Process.egid OptionParser.new do |opts| opts.on("-s", "--socket SOCKET", "Socket") { |v| options.socket = v } opts.on("-g", "--socket-group GROUPNAME", "Socket owning group") { |v| options.gid = nil; options.group_name = v } end.parse! raise ArgumentError, "You must specify a socket file using -s" unless options.socket unless options.gid if options.group_name options.gid = Etc.getgrnam(options.group_name).gid end end server = nil begin raise Errno::EADDRINUSE if File.exists?(options.socket) and File.socket?(options.socket) server = UNIXServer.new(options.socket) File.chown(nil, options.gid, options.socket) # make the socket group writable File.chmod(0770, options.socket) rescue Errno::EADDRINUSE puts "FAF unable to create socket #{options.socket}: file exists" exit(1) end run = true server_thread = Thread.new do begin while run and (session = server.accept) request = response = "" while l = session.gets request << l end session.close_read begin response = FAF::Server.parse(request) rescue => e response = "ERROR #{e}" end session.write(response) session.close end ensure server.close File.unlink(options.socket) if File.exists?(options.socket) end end ['INT', 'TERM'].each do |signal| trap(signal) do run = false; server_thread.exit end end puts "Fire&Forget process #{$$} listening on #{options.socket} ..." server_thread.join