#!/usr/bin/env python3 """Read Docker Engine event JSON on stdin and export scoped OTLP logs.""" import argparse import json import os import re import sys import urllib.error import urllib.parse import urllib.request ACTIONS = {"create", "start", "stop", "restart", "die", "oom", "destroy"} MAX_LINE_BYTES = 256 * 1024 class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, fp, code, msg, headers, newurl): return None def otlp_attributes(values): return [ {"key": name, "value": {"stringValue": value}} for name, value in values.items() if isinstance(value, str) and value and len(value) <= 256 ] def event_payload(event, scope): if not isinstance(event, dict) or event.get("Type") != "container": return None actor = event.get("Actor") action = event.get("Action") timestamp = event.get("timeNano") if not isinstance(actor, dict) or not isinstance(action, str) or action not in ACTIONS: return None container_id = actor.get("ID") if not isinstance(container_id, str) or not re.fullmatch(r"[a-f0-9]{64}", container_id): return None if type(timestamp) is not int or not 0 < timestamp <= 2**63 - 1: return None labels = actor.get("Attributes") if not isinstance(labels, dict): labels = {} resource = { **scope, "service.name": "docker-engine", "container.id": container_id, "container.name": labels.get("name"), "docker.compose.project": labels.get("com.docker.compose.project"), "docker.compose.service": labels.get("com.docker.compose.service"), } details = {"docker.event.action": action} exit_code = labels.get("exitCode") if action == "die" and isinstance(exit_code, str) and re.fullmatch(r"[0-9]{1,3}", exit_code): details["docker.event.exit_code"] = exit_code return {"resourceLogs": [{ "resource": {"attributes": otlp_attributes(resource)}, "scopeLogs": [{"logRecords": [{ "timeUnixNano": str(timestamp), "eventName": "docker.container.lifecycle", "severityNumber": 17 if action == "oom" else 9, "body": {"stringValue": f"Docker container {action}"}, "attributes": otlp_attributes(details), }]}], }]} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dry-run", action="store_true", help="Print normalized OTLP JSON without sending") args = parser.parse_args() fields = { "host.id": "CORRIDORA_HOST_ID", "host.name": "CORRIDORA_HOST_NAME", "service.namespace": "CORRIDORA_SERVICE_NAMESPACE", "deployment.environment.name": "CORRIDORA_DEPLOYMENT_ENVIRONMENT", } scope = {key: os.environ.get(variable, "") for key, variable in fields.items()} if any(not value or len(value) > 256 for value in scope.values()): parser.error("set the host ID, host name, service namespace, and deployment environment") if not args.dry_run: endpoint = urllib.parse.urlsplit(os.environ.get("CORRIDORA_OTLP_ENDPOINT", "")) key = os.environ.get("CORRIDORA_INGEST_KEY", "") if endpoint.scheme != "https" or not endpoint.hostname or endpoint.username or endpoint.password or endpoint.query or endpoint.fragment or not key: parser.error("set a trusted HTTPS OTLP base endpoint and an ingest key") url = endpoint.geturl().rstrip("/") + "/v1/logs" opener = urllib.request.build_opener(NoRedirect()) while line := sys.stdin.buffer.readline(MAX_LINE_BYTES + 1): if len(line) > MAX_LINE_BYTES: print("Docker event exceeds the input limit", file=sys.stderr) return 1 try: payload = event_payload(json.loads(line), scope) except (ValueError, UnicodeError): print("Skipped malformed Docker event", file=sys.stderr) continue if payload is None: continue body = json.dumps(payload) if args.dry_run: print(body) continue request = urllib.request.Request(url, method="POST", data=body.encode(), headers={ "Content-Type": "application/json", "Accept": "application/json", "X-CORRIDORA-KEY": key, }) try: with opener.open(request, timeout=15) as response: reply = response.read(4096) if reply and json.loads(reply).get("partialSuccess", {}).get("rejectedLogRecords") not in (None, 0, "0"): print("Docker lifecycle record rejected by ingest", file=sys.stderr) return 1 except (OSError, ValueError, AttributeError) as error: status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" print(f"Docker lifecycle export failed{status}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": sys.exit(main())