require 'rubygems' require 'thread' require 'uri' require 'net/http' require 'logger' require 'json' require 'digest/md5' require 'shellwords' require 'trollop' require 'socket' module KL module Agent PIDFile = "#{KL.home}/kldockeragent.pid" @@notifier_engine = KL::Notifier.new @@web_server = KL::Server.new @@global_app_uuid = KL.getApplicationId # Start the agent. # # options: # :daemon => true if running as a daemon, false if as a console application # :port => port of web server will listen to # :ssl => set true to enable HTTPS # :certfile => certificate file path for HTTPS # :keyfile => key file path for HTTPS # def self.start(opts={}) KL.logger.info "[main] Starting agent: #{KL::Agent.getUUID}" puts "Starting agent..." @@config = opts Process.daemon if opts[:daemon] and not opts[:mock] begin if not is_windows # trap signal ['INT', 'HUP'].each do |signal| trap(signal) { KL.logger.info "[main] Shutting down services..." web_server.stop notifier_engine.stop loop do break if notifier_engine.status == :stopped sleep 1 end self.close } end end File.open(PIDFile, 'w', 0644) { |f| f.write($$.to_s) } notifier_engine.start web_server.start @@main_enabled = true while @@main_enabled; end rescue Exception => e KL.logger.error "Starting the agent [Failed] #{e}\n#{e.backtrace.join("\n")}" raise e end end # Stop the agent's daemon. # def self.stop(opts={}) begin pid = File.read(PIDFile).to_i puts "Stopping agent with PID #{pid}..." Process.kill 'HUP', pid if not opts[:mock] begin sleep (KL::Notifier::SleepTime + 0.5) Process.kill 0, pid KL.logger.info "[main] Agent is still running." puts "Agent is still running." KL.logger.info "[main] Killing agent." puts "Killing agent." Process.kill 9, pid rescue KL.logger.info "[main] Agent has stopped." puts "Agent has stopped." File.delete(PIDFile) if File.exist?(PIDFile) end end rescue puts "Agent is not running." File.delete(PIDFile) if File.exist?(PIDFile) end end def self.pid begin pid = File.read(PIDFile).to_i return pid if Process.kill 0, pid rescue end nil end # Return agent's PID if it is running, otherwise nil. # def self.status if pid.nil? puts "Agent is not running." else puts "Agent is running with PID #{pid}" end end def self.is_windows (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/) end def self.is_linux (RbConfig::CONFIG['host_os'] =~ /linux/) end def self.notifier_engine @@notifier_engine end def self.web_server @@web_server end def self.close KL.logger.info "[main] Stopping agent..." @@main_enabled = false end def self.getUUID @@global_app_uuid end def self.getVersion File.read(File.dirname(__FILE__) + '/../../VERSION').strip end end end