Skip to content

Instantly share code, notes, and snippets.

@kirs
Created January 10, 2017 19:12
Show Gist options
  • Save kirs/123ca0e3cdb39c3581b04e3d9fb005ec to your computer and use it in GitHub Desktop.
Save kirs/123ca0e3cdb39c3581b04e3d9fb005ec to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Usage:
# bin/with-magellan bundle exec unicorn
# The binary will execute `bundle exec unicorn` and watch for endpoint status changes in Magellan
require 'net/http'
require 'json'
require "English"
parent = $PID
hostname = "demo"
borg_service = "development_kirs_sb"
def get_magellan_service(service_name)
request = Net::HTTP::Get.new("/services/#{service_name}")
url = URI.parse("http://192.168.64.103:8438")
Net::HTTP.start(url.host, url.port) do |http|
response = http.request(request)
return unless response.code == "200"
JSON.parse(response.body)
end
end
def get_magellan_status(service_name, hostname)
service = get_magellan_service(service_name)
return unless service
instance = service.fetch("instances").find { |i| i.fetch("endpoint") == hostname }
unless instance
raise "Could not find an instance for #{hostname}"
end
status = instance.fetch("body").fetch("status")
puts "<<< watching magellan status: #{status}"
status
end
def subscribe_to_magellan_status
loop do
sleep 5
status = get_magellan_status(borg_service, hostname)
yield(status)
end
end
# Before running the actual process, check if it's supposed to be active
# If it's not active, sleep and check it again
# Eventually it will be marked as active, we will exit from the script and runit
# will start the service again
status = get_magellan_status(borg_service, hostname)
if status != "active"
puts "The process should not be up..."
subscribe_to_magellan_status do |status|
if status == "active"
puts "The process became active. Restarting..."
exit
end
end
end
# Watch status updates in the work while running the process
# If we OOR the process, kill the parent
# On the next run, runit won't start it and will wait until the process becomes active
fork do
subscribe_to_magellan_status do |status|
if status != "active"
puts "The process is not supposed to be running anymore. Killing it..."
Process.kill("SIGTERM", parent)
exit
end
end
end
exec(*ARGV)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment