| 1 | # A tiny HTTP server: every response reports the container's hostname, the |
| 2 | # request path, and the MESSAGE environment variable the object passed in. |
| 3 | import json |
| 4 | import os |
| 5 | import signal |
| 6 | import socket |
| 7 | import sys |
| 8 | from http.server import BaseHTTPRequestHandler, HTTPServer |
| 9 | |
| 10 | # The process is PID 1 in the container, and PID 1 ignores a signal it has |
| 11 | # no handler for. The object's stop() sends SIGTERM, so exit on it. |
| 12 | signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) |
| 13 | |
| 14 | |
| 15 | class Handler(BaseHTTPRequestHandler): |
| 16 | def do_GET(self): |
| 17 | body = json.dumps({ |
| 18 | "hostname": socket.gethostname(), |
| 19 | "path": self.path, |
| 20 | "message": os.environ.get("MESSAGE", ""), |
| 21 | }).encode() |
| 22 | self.send_response(200) |
| 23 | self.send_header("content-type", "application/json") |
| 24 | self.send_header("content-length", str(len(body))) |
| 25 | self.end_headers() |
| 26 | self.wfile.write(body) |
| 27 | |
| 28 | def log_message(self, *args): |
| 29 | pass |
| 30 | |
| 31 | |
| 32 | HTTPServer(("0.0.0.0", int(os.environ["PORT"])), Handler).serve_forever() |