Created
July 19, 2017 09:23
-
-
Save kml/81c96356563c6360dd28fc701c6ec4db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# bind "tcp://127.0.0.1:5000" | |
# activate_control_app "tcp://127.0.0.1:9293", auth_token: "foo" | |
# | |
# curl -v http://127.0.0.1:5000/ping | |
# curl -v http://127.0.0.1:9293/ping/disable?token=foo | |
# curl -v http://127.0.0.1:9293/ping/enable?token=foo | |
# https://github.com/puma/puma/blob/master/lib/puma/app/status.rb | |
require "puma/app/status" | |
::Puma::App::Status.prepend(Module.new do | |
def call(env) | |
unless authenticate(env) | |
return rack_response(403, 'Invalid auth token', 'text/plain') | |
end | |
case env['PATH_INFO'] | |
when /\A\/ping\/disable\z/ | |
Thread.main[:ping].disable | |
return rack_response(200, ::Puma::App::Status::OK_STATUS) | |
when /\A\/ping\/enable\z/ | |
Thread.main[:ping].enable | |
return rack_response(200, ::Puma::App::Status::OK_STATUS) | |
end | |
super | |
end | |
end) | |
require "io/wait" | |
class PingMaster | |
LOCK_MESSAGE = "!".freeze | |
private_constant :LOCK_MESSAGE | |
attr_reader :pipe | |
def initialize(pipe) | |
@pipe = pipe | |
@read_ping, @write_ping = pipe | |
end | |
def enable | |
unless enabled? | |
@read_ping.gets | |
end | |
end | |
def disable | |
if enabled? | |
@write_ping.puts(LOCK_MESSAGE) | |
end | |
end | |
def enabled? | |
!@read_ping.ready? | |
end | |
def close | |
@write_ping.close | |
@read_ping.close | |
end | |
end | |
class PingWorker | |
def initialize(pipe) | |
@read, @write = pipe | |
@write.close | |
end | |
def enabled? | |
!@read.ready? | |
end | |
def close | |
@write.close | |
@read.close | |
end | |
end | |
before_fork do | |
Thread.main[:ping] = PingMaster.new(IO.pipe) | |
at_exit do | |
Thread.main[:ping].close | |
end | |
end | |
on_worker_boot do | |
Thread.main[:ping] = PingWorker.new(Thread.main[:ping].pipe) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment