Skip to content

Instantly share code, notes, and snippets.

@cluesque
Created August 3, 2023 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cluesque/0564c52b29693f59393b924a8167a992 to your computer and use it in GitHub Desktop.
Save cluesque/0564c52b29693f59393b924a8167a992 to your computer and use it in GitHub Desktop.
Liveness monitor for ruby programs
# Have your health checker execute this
require './liveness_monitor'
puts LivenessMonitor.new.status
require 'socket'
class LivenessMonitor
attr_accessor :port
def initialize(port = 5678)
@port = port
end
def start(callback)
Thread.new do
server = TCPServer.new 5678
while session = server.accept
session.puts callback.call
session.close
end
end
end
def status
server = TCPSocket.new 'localhost', 5678
out = ''
while line = server.gets
out += line
end
server.close
out
end
end
require './liveness_monitor'
# Probably you put this in an initializer, where the checker
# is actually inspecting some kind of heatbeat, or at the very least
# an indication that the program has fully started
# Maybe return '' for healthy, and an error message otherwise?
checker = ->{ "Hello world! The time is #{Time.now}" }
LivenessMonitor.new.start(checker)
# This stuff just keeps the program running, pretend its your real workload
puts 'server started'
while input = gets
puts "Did you just say '#{input.strip}'?"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment