lib/oria/server.rb in oria-0.0.3 vs lib/oria/server.rb in oria-0.1.0

- old
+ new

@@ -1,53 +1,73 @@ require 'yaml' require 'tmpdir' + module Oria class Server < EventMachine::Connection class << self @@timer = nil def debug? @@debug end def log(value, app_key = nil) - logger.debug("#{"#{app_key}: " if app_key}#{value}") if debug? + if debug? || @@options[:puts] + value = "#{Time.now.strftime('%d %b %H:%M:%S')} - #{"#{app_key}: " if app_key}#{value}" + logger.debug(value) if debug? + puts value if @@options[:puts] + end end def logger require 'logger' @@logger ||= Logger.new(log_file, 0, 100 * 1024 * 1024) end - def start(server, port, app_key = nil, debug = false) - at_exit do - Oria::Server.stop - end - pid = Process.pid - File.open(pid_file, 'w') do |file| - file.puts pid - end - app_key ||= 'default' + def running? + pid && !!Process.getpgid(pid) + rescue Errno::ESRCH + false + end + + def start(server, port, debug = false, options = {}) + @@debug = !!debug + @@options = options + log "Server started" @@servers ||= if File.exists?(yaml_store) + log "DB loaded from disk" YAML.load_file(yaml_store) else {} end - @@debug = !!debug - @@servers[app_key] ||= {} + pid = Process.pid EventMachine.run do EventMachine.start_server server, port, Oria::Server + File.open(pid_file, 'w') do |file| + file.puts pid + end + log "The server is now ready to accept connections on port #{port}" end end def stop + response = false if File.exists?(pid_file) - if pid - Process.kill(9, pid) + begin + if pid + Process.kill(9, pid) + response = true + end + rescue Errno::ESRCH + # TODO: We perform error reporting elsewhere. Still, + # an actionless rescue doesn't seem like a great idea. + ensure + File.unlink(pid_file) + @@pid = nil end - File.unlink(pid_file) end + response end def store_hash(app_key) @@timer.cancel if @@timer @@timer = EventMachine::Timer.new(10) do @@ -118,10 +138,10 @@ def unbind end private def hash - @hash ||= @@servers[@app_key || 'default'] ||= {} + @hash ||= @@servers[@app_key && !@app_key.empty? ? @app_key : 'default'] ||= {} end def random_key chars = ['a'..'z', 'A'..'Z', 0..9].map(&:to_a).flatten max = [hash.length, 2].max \ No newline at end of file