#!/usr/bin/env python3 """orders: the small service every capstone builds on. Standard library only, so it runs anywhere Python 3.10+ runs. GET /healthz liveness: the process is up GET /readyz readiness: ready to take traffic (503 while starting or draining) GET /orders list orders POST /orders create an order: {"item": "book", "qty": 2} GET /metrics Prometheus text format: requests by route and status, latency histogram GET /version the version this process runs Every request is logged as one JSON line on standard output, with a W3C trace ID taken from the traceparent header or created. Environment variables: PORT (8080) VERSION (1.0.0) FAIL_RATE (0.0: share of /orders requests that return 500) SLOW_MS (0: extra latency per /orders request) STARTUP_S (0: seconds before /readyz is ready) OTLP_URL (unset: if set, each request is also sent as an OTLP/HTTP JSON span to this URL) DRAIN_S (0: on SIGTERM, seconds to keep serving while readiness reports 503, before stopping) """ import json import os import random import secrets import signal import sys import threading import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = int(os.environ.get("PORT", "8080")) VERSION = os.environ.get("VERSION", "1.0.0") FAIL_RATE = float(os.environ.get("FAIL_RATE", "0")) SLOW_MS = int(os.environ.get("SLOW_MS", "0")) STARTUP_S = float(os.environ.get("STARTUP_S", "0")) OTLP_URL = os.environ.get("OTLP_URL", "") if OTLP_URL and not OTLP_URL.startswith(("http://", "https://")): sys.exit("OTLP_URL must start with http:// or https://") # so urlopen below can never read file:// URLs DRAIN_S = float(os.environ.get("DRAIN_S", "0")) BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5] STARTED = time.time() state = {"draining": False} orders, lock = [], threading.Lock() requests_total = {} # (route, method, status) -> count latency = {} # route -> [bucket counts..., +Inf count, sum] def log(**fields): fields = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "service": "orders", "version": VERSION, **fields} sys.stdout.write(json.dumps(fields) + "\n") sys.stdout.flush() def observe(route, method, status, seconds): with lock: key = (route, method, status) requests_total[key] = requests_total.get(key, 0) + 1 h = latency.setdefault(route, [0] * (len(BUCKETS) + 1) + [0.0]) for i, b in enumerate(BUCKETS): if seconds <= b: h[i] += 1 h[len(BUCKETS)] += 1 h[-1] += seconds def metrics_text(): out = ["# HELP http_requests_total Requests by route, method, and status.", "# TYPE http_requests_total counter"] with lock: for (route, method, status), n in sorted(requests_total.items()): out.append(f'http_requests_total{{route="{route}",method="{method}",status="{status}"}} {n}') out += ["# HELP http_request_duration_seconds Request latency.", "# TYPE http_request_duration_seconds histogram"] for route, h in sorted(latency.items()): for i, b in enumerate(BUCKETS): out.append(f'http_request_duration_seconds_bucket{{route="{route}",le="{b}"}} {h[i]}') out.append(f'http_request_duration_seconds_bucket{{route="{route}",le="+Inf"}} {h[len(BUCKETS)]}') out.append(f'http_request_duration_seconds_sum{{route="{route}"}} {h[-1]:.6f}') out.append(f'http_request_duration_seconds_count{{route="{route}"}} {h[len(BUCKETS)]}') out += ["# HELP orders_in_memory Orders currently held.", "# TYPE orders_in_memory gauge", f"orders_in_memory {len(orders)}"] out += ["# HELP app_info Version of the running process.", "# TYPE app_info gauge", f'app_info{{version="{VERSION}"}} 1'] return "\n".join(out) + "\n" def export_span(trace_id, span_id, route, method, status, start, end): """Send one span as OTLP/HTTP JSON (the OpenTelemetry protocol), without an SDK.""" body = {"resourceSpans": [{"resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "orders"}}, {"key": "service.version", "value": {"stringValue": VERSION}}]}, "scopeSpans": [{"scope": {"name": "orders"}, "spans": [{ "traceId": trace_id, "spanId": span_id, "name": f"{method} {route}", "kind": 2, "startTimeUnixNano": str(int(start * 1e9)), "endTimeUnixNano": str(int(end * 1e9)), "attributes": [{"key": "http.request.method", "value": {"stringValue": method}}, {"key": "http.route", "value": {"stringValue": route}}, {"key": "http.response.status_code", "value": {"intValue": str(status)}}], "status": {"code": 2 if status >= 500 else 1}}]}]}]} try: req = urllib.request.Request(OTLP_URL, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) urllib.request.urlopen(req, timeout=2).read() # nosec B310 - scheme checked at startup (OTLP_URL) except Exception as e: # telemetry must never break the request log(level="warn", msg="span export failed", error=str(e)) class Handler(BaseHTTPRequestHandler): server_version = "orders/" + VERSION def log_message(self, *args): # replaced by our own JSON log line pass def send(self, status, body, ctype="application/json"): data = body.encode() if isinstance(body, str) else json.dumps(body).encode() self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.send_header("traceparent", f"00-{self.trace_id}-{self.span_id}-01") self.end_headers() self.wfile.write(data) return status def handle_one(self, method): start = time.time() tp = self.headers.get("traceparent", "") parts = tp.split("-") self.trace_id = parts[1] if len(parts) == 4 and len(parts[1]) == 32 else secrets.token_hex(16) self.span_id = secrets.token_hex(8) route = self.path.split("?")[0] try: status = self.route(method, route) except Exception as e: log(level="error", msg="unhandled error", error=repr(e), trace_id=self.trace_id) status = self.send(500, {"error": "internal"}) end = time.time() known = route if route in ("/healthz", "/readyz", "/orders", "/metrics", "/version") else "other" observe(known, method, status, end - start) if route not in ("/metrics", "/healthz", "/readyz"): log(level="error" if status >= 500 else "info", msg="request", method=method, route=known, status=status, duration_ms=round((end - start) * 1000, 1), trace_id=self.trace_id) if OTLP_URL and known == "/orders": export_span(self.trace_id, self.span_id, known, method, status, start, end) def route(self, method, route): if route == "/healthz": return self.send(200, {"status": "ok"}) if route == "/readyz": ready = time.time() - STARTED >= STARTUP_S and not state["draining"] return self.send(200 if ready else 503, {"ready": ready}) if route == "/version": return self.send(200, {"version": VERSION}) if route == "/metrics": return self.send(200, metrics_text(), "text/plain; version=0.0.4") if route == "/orders": if SLOW_MS: time.sleep(SLOW_MS / 1000) if FAIL_RATE and random.random() < FAIL_RATE: return self.send(500, {"error": "injected failure"}) if method == "GET": with lock: return self.send(200, {"orders": list(orders)}) n = int(self.headers.get("Content-Length", "0") or 0) try: o = json.loads(self.rfile.read(n) or b"{}") except json.JSONDecodeError: return self.send(400, {"error": "body must be JSON"}) if not isinstance(o.get("item"), str) or not isinstance(o.get("qty"), int) or o["qty"] < 1: return self.send(400, {"error": "need item (string) and qty (integer >= 1)"}) with lock: o = {"id": len(orders) + 1, "item": o["item"], "qty": o["qty"]} orders.append(o) return self.send(201, o) return self.send(404, {"error": "not found"}) def do_GET(self): self.handle_one("GET") def do_POST(self): self.handle_one("POST") def main(): # a container must listen on all interfaces; the network boundary is the published container port srv = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) # nosec B104 - see the line above def stop(signum, frame): # drain: fail readiness, keep serving DRAIN_S seconds, then stop state["draining"] = True log(level="info", msg="draining", signal=signum, drain_s=DRAIN_S) def later(): time.sleep(DRAIN_S) # load balancers stop sending new requests in this time srv.shutdown() threading.Thread(target=later, daemon=True).start() signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) log(level="info", msg="listening", port=PORT, fail_rate=FAIL_RATE, slow_ms=SLOW_MS) srv.serve_forever() log(level="info", msg="stopped") if __name__ == "__main__": main()