class NTP::Server::Base

Attributes

gap_reader[RW]
gap_writer[RW]
host[RW]
pid[RW]
pipe_in[RW]
pipe_out[RW]
port[RW]

Public Class Methods

new(port = 123) click to toggle source
# File lib/ntp/server/base.rb, line 7
def initialize(port = 123)
   self.pipe_in = Fifo.new('ntp-mock-server-in', :r, :nowait)
   self.pipe_out = Fifo.new('ntp-mock-server-out', :w, :nowait)
   self.host = 'localhost'
   self.port = port
   (self.gap_reader, self.gap_writer) = IO.pipe
   handler.origin_time = Time.now
   handler.gap = 0
end

Public Instance Methods

handler() click to toggle source

returns handler constant

# File lib/ntp/server/base.rb, line 32
def handler
    NTP::Server::Handler
end
start() click to toggle source

runs the server

# File lib/ntp/server/base.rb, line 18
def start
   self.pid = fork do
     self.gap_writer.close
     self.handler.reader = self.gap_reader
     EventMachine::run do
       EventMachine::open_datagram_socket self.host, self.port, self.handler
     end
   end
   self.gap_reader.close
   self.pipe_out.puts "started NTP mock server on #{host}:#{port}."
   process_queue
end

Private Instance Methods

change_time(new_time) click to toggle source

sets a new time for the NTP server to base future responses

# File lib/ntp/server/base.rb, line 70
def change_time(new_time)
   send_gap(new_time.utc - Time.now.utc)
end
process_queue() click to toggle source

enters to the processing queue loop

# File lib/ntp/server/base.rb, line 39
def process_queue
   while true
      self.pipe_in.to_io.sync
      message = self.pipe_in.gets
      # puts message
      case message
      when /stop/
         stop
      when /status/
         self.pipe_out.puts(status)
      when /time/
         /time (?<time>.*)/ =~ message
         begin
            change_time(Time.parse(time))
         rescue ArgumentError
            puts "can't set invalid time"
         end
      when /reset/
         reset
      end
   end
end
puts(*args) click to toggle source
# File lib/ntp/server/base.rb, line 83
def puts *args
   Kernel.puts *args
end
reset() click to toggle source

sets the time to current time to base future responses

# File lib/ntp/server/base.rb, line 75
def reset
   send_gap(0)
end
send_gap(gap) click to toggle source
# File lib/ntp/server/base.rb, line 87
def send_gap gap
   begin
      self.gap_writer.puts(gap)
   rescue Errno::EPIPE
      # TODO check and restore child server part
   end
   self.gap_writer.sync
   Process.kill("USR1", self.pid)
   Process.setpriority(Process::PRIO_PROCESS, self.pid, 19)
end
status() click to toggle source
# File lib/ntp/server/base.rb, line 79
def status
   'listening...'
end
stop() click to toggle source

stops the server

# File lib/ntp/server/base.rb, line 63
def stop
   Process.kill("HUP", self.pid)
   Process.wait2
   Process.exit(true)
end