|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Fetch Cozystack telemetry and produce a JSON payload for the OSS Health shell. |
| 4 | +
|
| 5 | +What it does: |
| 6 | +1. Query https://telemetry.cozystack.io/api/overview?year=YYYY&month=MM |
| 7 | +2. Filter apps to entries visible on the Cozystack dashboard. |
| 8 | +3. Merge case-insensitive / Pax* / legacy-name aliases into one canonical entry |
| 9 | + per application, keeping the maximum instance count (zero-count entries |
| 10 | + left after the merge are dropped from the table). |
| 11 | +4. Pull `Tenant` out of the apps map and surface it as the top-level Tenants |
| 12 | + summary card (the raw `total_tenants` field from the API is always zero). |
| 13 | +5. Emit the payload in the shape consumed by `oss-health-app.html` + |
| 14 | + `renderTelemetry`, including `summary_cards`, `apps`, `range`. |
| 15 | +
|
| 16 | +Used by both `.github/workflows/fetch-telemetry.yml` (daily cron) and the |
| 17 | +developer who needs to refresh the seed file locally. |
| 18 | +""" |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import datetime as dt |
| 22 | +import json |
| 23 | +import os |
| 24 | +import sys |
| 25 | +import urllib.error |
| 26 | +import urllib.request |
| 27 | + |
| 28 | +API_URL = "https://telemetry.cozystack.io/api/overview" |
| 29 | +OUTPUT_PATH = os.environ.get( |
| 30 | + "TELEMETRY_OUTPUT_PATH", |
| 31 | + "static/oss-health-data/telemetry.json", |
| 32 | +) |
| 33 | + |
| 34 | +# Canonical display name per normalized key. Anything not in this table is |
| 35 | +# dropped (internal entities like `Info`, `Pax*` experimental variants that |
| 36 | +# don't map to a dashboard app, duplicate lowercase CR kind names, etc.). |
| 37 | +# Keys are lower-cased and stripped of hyphens so we can match PascalCase, |
| 38 | +# lowercase, kebab-case and Pax-prefixed variants against the same canonical. |
| 39 | +ALIASES: dict[str, str] = { |
| 40 | + # Managed applications (docs/v1.2/applications/_include/*) |
| 41 | + "clickhouse": "ClickHouse", |
| 42 | + "paxclickhouse": "ClickHouse", |
| 43 | + "foundationdb": "FoundationDB", |
| 44 | + "harbor": "Harbor", |
| 45 | + "kafka": "Kafka", |
| 46 | + "mariadb": "MariaDB", |
| 47 | + "mongodb": "MongoDB", |
| 48 | + "nats": "NATS", |
| 49 | + "openbao": "OpenBAO", |
| 50 | + "opensearch": "OpenSearch", |
| 51 | + "postgres": "Postgres", |
| 52 | + "postgresql": "Postgres", |
| 53 | + "paxpostgres": "Postgres", |
| 54 | + "qdrant": "Qdrant", |
| 55 | + "rabbitmq": "RabbitMQ", |
| 56 | + "redis": "Redis", |
| 57 | + "paxredis": "Redis", |
| 58 | + "clearml": "ClearML", |
| 59 | + # Services (docs/v1.2/operations/services/*) |
| 60 | + "etcd": "Etcd", |
| 61 | + "ingress": "Ingress", |
| 62 | + "monitoring": "Monitoring", |
| 63 | + "bucket": "Bucket", |
| 64 | + "seaweedfs": "SeaweedFS", |
| 65 | + "nfs": "NFS", |
| 66 | + # Networking (docs/v1.2/networking/_include/*) |
| 67 | + "httpcache": "HTTPCache", |
| 68 | + "tcpbalancer": "TCPBalancer", |
| 69 | + "virtualprivatecloud": "VirtualPrivateCloud", |
| 70 | + "vpc": "VirtualPrivateCloud", |
| 71 | + "vpn": "VPN", |
| 72 | + # Virtualization (docs/v1.2/virtualization/_include/*) |
| 73 | + "vminstance": "VMInstance", |
| 74 | + "paxvminstance": "VMInstance", |
| 75 | + "vmdisk": "VMDisk", |
| 76 | + # Managed Kubernetes |
| 77 | + "kubernetes": "Kubernetes", |
| 78 | +} |
| 79 | + |
| 80 | + |
| 81 | +def normalize_key(raw: str) -> str: |
| 82 | + return raw.lower().replace("-", "").replace("_", "") |
| 83 | + |
| 84 | + |
| 85 | +def clean_apps(apps: dict[str, int]) -> list[dict[str, object]]: |
| 86 | + """Filter, dedupe (max), drop zeros, sort desc by count.""" |
| 87 | + merged: dict[str, int] = {} |
| 88 | + for raw_name, count in apps.items(): |
| 89 | + canonical = ALIASES.get(normalize_key(raw_name)) |
| 90 | + if not canonical: |
| 91 | + continue |
| 92 | + if count > merged.get(canonical, 0): |
| 93 | + merged[canonical] = count |
| 94 | + non_zero = [(name, n) for name, n in merged.items() if n > 0] |
| 95 | + non_zero.sort(key=lambda item: (-item[1], item[0].lower())) |
| 96 | + return [{"name": name, "value": str(count)} for name, count in non_zero] |
| 97 | + |
| 98 | + |
| 99 | +def transform_period(raw_period: dict, label_fallback: str) -> dict | None: |
| 100 | + if not raw_period: |
| 101 | + return None |
| 102 | + apps_raw = raw_period.get("apps", {}) or {} |
| 103 | + tenants = int(apps_raw.get("Tenant", 0)) |
| 104 | + clusters = int(raw_period.get("clusters", 0)) |
| 105 | + total_nodes = int(raw_period.get("total_nodes", 0)) |
| 106 | + avg_nodes = raw_period.get("avg_nodes_per_cluster") |
| 107 | + summary = [ |
| 108 | + {"label": "Clusters", "value": str(clusters)}, |
| 109 | + { |
| 110 | + "label": "Total Nodes", |
| 111 | + "value": str(total_nodes), |
| 112 | + "hint": ( |
| 113 | + f"avg {avg_nodes:.1f} per cluster" |
| 114 | + if clusters and isinstance(avg_nodes, (int, float)) |
| 115 | + else "" |
| 116 | + ), |
| 117 | + }, |
| 118 | + { |
| 119 | + "label": "Tenants", |
| 120 | + "value": str(tenants), |
| 121 | + "hint": ( |
| 122 | + f"avg {tenants / clusters:.1f} per cluster" |
| 123 | + if clusters |
| 124 | + else "" |
| 125 | + ), |
| 126 | + }, |
| 127 | + ] |
| 128 | + period = { |
| 129 | + "label": raw_period.get("label") or label_fallback, |
| 130 | + "summary_cards": summary, |
| 131 | + "apps": clean_apps(apps_raw), |
| 132 | + } |
| 133 | + start = raw_period.get("start") |
| 134 | + end = raw_period.get("end") |
| 135 | + if start and end: |
| 136 | + period["range"] = {"from": start, "to": end} |
| 137 | + return period |
| 138 | + |
| 139 | + |
| 140 | +def fetch(year: int, month: int) -> dict: |
| 141 | + url = f"{API_URL}?year={year}&month={month:02d}" |
| 142 | + req = urllib.request.Request(url, headers={"User-Agent": "cozystack-website/telemetry-fetch"}) |
| 143 | + with urllib.request.urlopen(req, timeout=30) as resp: |
| 144 | + if resp.status != 200: |
| 145 | + raise RuntimeError(f"telemetry API returned HTTP {resp.status}") |
| 146 | + return json.loads(resp.read().decode("utf-8")) |
| 147 | + |
| 148 | + |
| 149 | +def build_payload(raw: dict) -> dict: |
| 150 | + periods_raw = raw.get("periods", {}) or {} |
| 151 | + periods_out: dict[str, dict] = {} |
| 152 | + for key in ("month", "quarter", "year"): |
| 153 | + transformed = transform_period(periods_raw.get(key, {}) or {}, label_fallback=key.title()) |
| 154 | + if transformed: |
| 155 | + periods_out[key] = transformed |
| 156 | + return { |
| 157 | + "updated_at": raw.get("generated_at"), |
| 158 | + "title": "Telemetry", |
| 159 | + "source": {"label": "Cozystack Telemetry Server"}, |
| 160 | + "periods": periods_out, |
| 161 | + } |
| 162 | + |
| 163 | + |
| 164 | +def main() -> int: |
| 165 | + today = dt.datetime.now(dt.timezone.utc) |
| 166 | + year = int(os.environ.get("TELEMETRY_YEAR", today.year)) |
| 167 | + month = int(os.environ.get("TELEMETRY_MONTH", today.month)) |
| 168 | + try: |
| 169 | + raw = fetch(year, month) |
| 170 | + except (urllib.error.URLError, urllib.error.HTTPError, RuntimeError, ValueError) as err: |
| 171 | + print(f"fetch failed: {err}", file=sys.stderr) |
| 172 | + return 1 |
| 173 | + payload = build_payload(raw) |
| 174 | + if not payload["periods"]: |
| 175 | + print("fetched payload has no usable periods; refusing to write empty file", file=sys.stderr) |
| 176 | + return 1 |
| 177 | + os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True) |
| 178 | + with open(OUTPUT_PATH, "w", encoding="utf-8") as fh: |
| 179 | + json.dump(payload, fh, indent=2, ensure_ascii=False) |
| 180 | + fh.write("\n") |
| 181 | + print(f"wrote {OUTPUT_PATH} ({len(payload['periods'])} periods, {sum(len(p['apps']) for p in payload['periods'].values())} app rows total)") |
| 182 | + return 0 |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + sys.exit(main()) |
0 commit comments