Class: Jobby::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/server.rb

Overview

This is a generic server class which accepts connections on a UNIX socket. On receiving a connection, the server process forks and runs the specified block.

By default, this class will enable the copy-on-write code if the interpretter supports it.

Example

Jobby::Server.new("/tmp/jobby.socket", 3, "/var/log/jobby.log").run do
  # This code will be run in the forked children
  puts "#{Process.pid}: I'm toilet trained!"
end

Stopping the server

There are two built-in ways of stopping the server:

SIGUSR1    will stop the server accepting any more connections, but it 
           will continue to fork if there are any requests in the queue. 
           It will then wait for the children to exit before terminating.

SIGTERM    will stop the server forking any more children, kill 15 any 
           existing children and terminate it.

Log rotation

The server can receive SIGHUP as notification that the logfile has been rotated. This will close and re-open the handle to the log file. Since the server process forks to produce children, they too can handle SIGHUP on log rotation.

To tell all Jobby processes that the log file has been rotated, use something like:

% pkill -HUP -f jobby

Instance Method Summary collapse

Constructor Details

#initialize(socket_path, max_forked_processes, log, prerun = nil) ⇒ Server

The log parameter can be either a filepath or an IO object.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/server.rb', line 61

def initialize(socket_path, max_forked_processes, log, prerun = nil)
  $0 = "jobbyd: #{socket_path}" # set the process name
  @log = log.path rescue log
  reopen_standard_streams
  close_fds
  start_logging
  if GC.respond_to?(:copy_on_write_friendly=)
    GC.copy_on_write_friendly = true
  end
  @socket_path = socket_path
  @max_forked_processes = max_forked_processes.to_i
  @queue = Queue.new
  setup_signal_handling
  prerun.call(@logger) unless prerun.nil?
end

Instance Method Details

#run(&block) ⇒ Object

Starts the server and listens for connections. The specified block is run in the child processes. When a connection is received, the input parameter is immediately added to the queue.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/server.rb', line 80

def run(&block)
  try_to_connect_to_socket
  unless block_given?
    @logger.error "No block given, exiting"
    terminate
  end
  start_forking_thread(block)
  loop do
    client = @socket.accept
    input = ""
    while bytes = client.read(1)
      input += bytes
    end
    client.close
    @queue << input
  end
end