#!/usr/bin/env ruby require '../lib/pxnx_jruby/spoon/pxnx_runner' require 'timeout' def setup() @pid_dir = File.join(File.dirname(__FILE__), '.') @name = "pxnx_daemon_process" @pid_path = File.join(@pid_dir, "#{@name}.pid") @pid = get_pid_from_file() @timeout = 120 end def create_pid_file(pid) begin open(@pid_path, 'w') do |f| f.puts pid end rescue => e STDERR.puts "Error: Unable to open #{@pid_path} for writing:\n\t <#{e.message}>" exit end end def get_pid_from_file @pid = nil open(@pid_path, 'r') do |f| @pid = f.readline.to_s.gsub(/[^0-9]/,'') end rescue Errno::ENOENT => e #File does not exist. Leave PID at nil. @pid.to_i unless @pid.nil? end def remove_pid_file File.unlink(@pid_path) rescue => e STDERR.puts "ERROR: Unable to unlink #{@pid_path}:\n\t <#{e.message}>" exit end def running? setup() return false if @pid.nil? begin Process.kill(0, @pid.to_i) return true rescue Errno::ESRCH, TypeError => e #STDERR.puts "Error querying PID <#{@pid}>! Error was <#{e.message}>"; return false rescue Errno::EPERM STDERR.puts "No permission to query #{@pid}!"; return false rescue => e STDERR.puts "ERROR: Unable to check PXNX status:\n\t <#{e.message}>" return false end end def stop setup() abort "PXNX is not running!" unless running? begin STDOUT.puts "Stopping process #{@pid}..." Timeout.timeout(@timeout) do Process.kill("TERM", @pid.to_i) sleep 5 while running? end rescue Timeout::Error STDERR.puts "Shutdown timeout... forcing shutdown!" Process.kill("KILL", @pid.to_i) sleep 5 while process_exists? end remove_pid_file STDOUT.puts "Process stopped." end def start() abort "Process already running!" if running? if pid = Spoon.spawnp('jruby', *ARGV) create_pid_file(pid) STDOUT.puts "Process started with pid #{pid}" else Process.setsid end end case ARGV.shift when 'start' start() when 'stop' stop() when 'restart' stop() start() when 'status' if running? STDOUT.puts "PXNX is running with pid #{@pid}" else STDOUT.puts "PXNX is not running." end else STDERR.puts "Usage: jruby pxnx_daemon.rb " exit! end