Add some output

This commit is contained in:
Scott Wallace 2020-10-15 10:55:12 +01:00
parent a1ffd94d8f
commit cbf4bd2c7b
Signed by: scott
GPG key ID: AA742FDC5AFE2A72

View file

@ -42,29 +42,27 @@ class HTTPHandler(MetricsHandler):
self._metrics() self._metrics()
if self.path == '/healthcheck': if self.path == '/healthcheck':
self._healthcheck()
def _healthcheck(self, message=True):
"""
Method to return 200 or 500 response and an optional message
"""
if not healthy(): if not healthy():
self.send_response(500) print('ERROR: Check requirements')
self.end_headers() self._respond(500, 'ERR')
if message:
self.wfile.write(b'ERR')
return
self.send_response(200) self._respond(200, 'OK')
def _respond(self, status, message):
"""
Method to output a simple HTTP status and string to the client
"""
self.send_response(int(status) or 500)
self.end_headers() self.end_headers()
if message: self.wfile.write(bytes(str(message).encode()))
self.wfile.write(b'OK')
def _metrics(self): def _metrics(self):
""" """
Method to handle the request for metrics Method to handle the request for metrics
""" """
if not self._healthcheck(message=False): if not healthy:
print('ERROR: Check requirements')
self._respond(500, 'Server not configured correctly')
return return
registry = CollectorRegistry() registry = CollectorRegistry()
@ -91,7 +89,7 @@ class HTTPHandler(MetricsHandler):
else: else:
gauge.labels(*label_values).set(int(health_str == HEALTHY_STR)) gauge.labels(*label_values).set(int(health_str == HEALTHY_STR))
self.wfile.write(generate_latest(registry)) self._respond(200, generate_latest(registry).decode())
def healthy(): def healthy():
@ -128,7 +126,11 @@ if __name__ == '__main__':
# Invert the sense of 'healthy' for Unix CLI usage # Invert the sense of 'healthy' for Unix CLI usage
return not healthy() return not healthy()
print(f'Starting web server on port {LISTEN_PORT}')
try:
HTTPServer(('', LISTEN_PORT), HTTPHandler).serve_forever() HTTPServer(('', LISTEN_PORT), HTTPHandler).serve_forever()
except KeyboardInterrupt:
print('Exiting')
return 0 return 0