Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

executable file 64 lines (54 sloc) 1.417 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#!/usr/bin/env ruby
#
# A simple example showing how to use Einhorn's shared-socket
# features. Einhorn translates the (addr:port[,flags...]) bind spec in
# into a file descriptor number in the EINHORN_FD_# environment
# variables.
#
# Invoke through Einhorn as
#
# einhorn -b 127.0.0.1:2345,r ./time_server
#
# or, if you want to try out preloading:
#
# einhorn -b 127.0.0.1:2345,r -p ./time_server ./time_server
require 'rubygems'
require 'einhorn/worker'

def log(msg)
  puts "=== [#{$$}] #{msg}"
end

def einhorn_main
  log "Called with ENV['EINHORN_FD_0']: #{ENV['EINHORN_FD_0']}"

  fd_num = Einhorn::Worker.socket!
  socket = Socket.for_fd(fd_num)

  sleep_before_shutdown = 0
  sleep_before_ack = 0

  # Came up successfully, so let's set up graceful handler and ACK the
  # master.
  Einhorn::Worker.graceful_shutdown do
    if sleep_before_shutdown > 0
      log "sleeping #{sleep_before_shutdown}s before shutdown"
      sleep sleep_before_shutdown
    end
    log "Goodbye!"
    exit(0)
  end

  if sleep_before_ack > 0
    log "sleeping #{sleep_before_ack}s before ack"
    sleep sleep_before_ack
  end
  log "worker ack"

  Einhorn::Worker.ack!

  # Real work happens here.
  begin
    while true
      accepted, _ = socket.accept
      accepted.write("[#{$$}] The current time is: #{Time.now}!\n")
      accepted.close
    end
  rescue Exception
  end
end

if $0 == __FILE__
  einhorn_main
end
Something went wrong with that request. Please try again.