Class: Talkshow::Daemon

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDaemon

Create a new Talkshow object to get going



18
19
20
21
22
23
# File 'lib/talkshow/daemon.rb', line 18

def initialize
  Dir.mkdir './logs' if !Dir.exists?('./logs')
  Dir.mkdir './pids' if !Dir.exists?('./pids')
  @processes = {}
  @port_requests = ::Queue.new
end

Instance Attribute Details

#port_requestsObject

Returns the value of attribute port_requests.



14
15
16
# File 'lib/talkshow/daemon.rb', line 14

def port_requests
  @port_requests
end

#processesObject

Returns the value of attribute processes.



15
16
17
# File 'lib/talkshow/daemon.rb', line 15

def processes
  @processes
end

#threadObject

Returns the value of attribute thread.



13
14
15
# File 'lib/talkshow/daemon.rb', line 13

def thread
  @thread
end

Instance Method Details

#check_processesObject



92
93
94
95
96
# File 'lib/talkshow/daemon.rb', line 92

def check_processes()
  @processes.each do |port, status|
    @processes[port] = check_status(port)
  end
end

#check_status(port) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/talkshow/daemon.rb', line 74

def check_status(port)
  uri = URI.parse("http://localhost:#{port}/status")
  begin
    response = Net::HTTP.get_response(uri)
  rescue
    status = 'dead'
  end
  
  if !status
    if response.code.to_i == 200
      status = 'ok'
    else
      status = "dead #{response.code}"
    end
  end
  status
end

#deal_with_port_requestsObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/talkshow/daemon.rb', line 49

def deal_with_port_requests
  begin
    port = @port_requests.pop(true)
  rescue
    port = nil
  end
  if port
    if @processes[port]
      puts "Port request -- checking aliveness"
      if check_status(port) == 'dead'
        @processes[port] = spawn_process(port)
      end
    else
      puts "New port request"
      @processes[port] = spawn_process(port)
    end
  end
end

#runObject



40
41
42
43
44
45
46
47
# File 'lib/talkshow/daemon.rb', line 40

def run
  self.start_server
  loop do
    deal_with_port_requests
    sleep 5
    check_processes
  end
end

#spawn_process(port) ⇒ Object



68
69
70
71
72
# File 'lib/talkshow/daemon.rb', line 68

def spawn_process(port)
  `TALKSHOW_PORT=#{port} bundle exec ./bin/talkshow_server.rb > logs/talkshow.#{port}.log 2>&1 &`
  sleep 5
  'starting'
end

#start_serverObject



25
26
27
28
29
30
31
32
33
# File 'lib/talkshow/daemon.rb', line 25

def start_server
  @thread = Thread.new do
    Talkshow::WebControl.port_requests(@port_requests)
    Talkshow::WebControl.processes(@processes)
    Talkshow::WebControl.run!
  end
  p @thread
  sleep 10
end

#stop_serverObject

Stop the webserver



36
37
38
# File 'lib/talkshow/daemon.rb', line 36

def stop_server
  @thread.exit
end