Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): add four per-application Argo CD tables (#99206)

Tom Owersdb36c9802c92
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 0c57755797e4..c052ffde04a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -484,14 +484,14 @@ Note: Genuinely a one-endpoint API, not a thin implementation. The docs sitemap
## Argocd — gaps
-Today (5): `applications`, `clusters`, `deployment_history`, `projects`, `repositories`
+Today (9): `application_events`, `applications`, `clusters`, `deployment_history`, `managed_resources`, `projects`, `repositories`, `resource_tree`, `revision_metadata`
Diffed against: <https://raw.githubusercontent.com/argoproj/argo-cd/master/assets/swagger.json>
-- [ ] `/api/v1/applications/{name}/events` — per-application Kubernetes event stream — the sync and health state-transition history behind each deployment (high)
-- [ ] `/api/v1/applications/{name}/revisions/{revision}/metadata` — lookup resolving the revision SHAs in deployment_history to commit author, message and date (high)
-- [ ] `/api/v1/applications/{applicationName}/managed-resources` — the resource inventory each app owns, with live vs target diff — the drift signal (high)
-- [ ] `/api/v1/applications/{applicationName}/resource-tree` — live resource hierarchy and per-resource health, one level below application health (medium)
+- [x] `/api/v1/applications/{name}/events` — per-application Kubernetes event stream — the sync and health state-transition history behind each deployment (high)
+- [x] `/api/v1/applications/{name}/revisions/{revision}/metadata` — lookup resolving the revision SHAs in deployment_history to commit author, message and date (high)
+- [x] `/api/v1/applications/{applicationName}/managed-resources` — the resource inventory each app owns, with live vs target diff — the drift signal (high)
+- [x] `/api/v1/applications/{applicationName}/resource-tree` — live resource hierarchy and per-resource health, one level below application health (medium)
- [ ] `/api/v1/applicationsets` — lookup for the generator that produced each application in a templated setup (medium)
- [ ] `/api/v1/projects/{name}/events` — project-level change history, useful for attributing policy changes to sync behavior (medium)
- [ ] `/api/v1/applications/{name}/revisions/{revision}/chartdetails` — Helm chart version and metadata per deployed revision (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py
index 24da519abdf3..00bc60b91f93 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/argocd.py
@@ -3,11 +3,11 @@ import json
import time
from collections.abc import Iterator
from typing import Any, Optional
-from urllib.parse import urlencode, urlparse
+from urllib.parse import quote, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from tenacity import Retrying, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from urllib3.util.retry import Retry
from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.settings import ARGOCD_ENDPOINTS
@@ -17,6 +17,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
REQUEST_TIMEOUT_SECONDS = 120
MAX_RETRIES = 5
+# A per-application request usually fails for a reason specific to that one application, such
+# as a spec the server can't compare or a revision its repository no longer resolves, and the
+# application is then skipped. A short budget keeps a large install from waiting out the full
+# one once per application.
+MAX_CHILD_RETRIES = 2
HOST_NOT_ALLOWED_ERROR = "Argo CD host is not allowed"
HTTPS_REQUIRED_ERROR = "Argo CD host must use HTTPS"
@@ -41,6 +46,21 @@ _ERROR_SNIPPET_BYTES = 2048
# The applications list is fetched in one response, so batch the yielded rows to keep
# downstream Arrow conversion working on bounded slices.
_ROWS_PER_BATCH = 1000
+# Each managed-resource row carries the resource's live and target manifests, so these rows
+# are batched smaller to keep a batch's memory footprint comparable to the other endpoints'.
+_MANAGED_RESOURCE_ROWS_PER_BATCH = 100
+
+# Per-application endpoints cost one request per application, so bound the walk rather than
+# letting a pathological install run unchecked.
+MAX_FAN_OUT_APPLICATIONS = 5000
+# Argo CD keeps 10 history entries per application by default; this leaves headroom for
+# installs that raise revisionHistoryLimit.
+MAX_REVISIONS_PER_APPLICATION = 25
+# Every per-request limit resets on the next request, so a walk of one request per application
+# needs a budget of its own. Without it a host that answers slowly for tens of thousands of
+# applications holds an import worker until the activity's 24h timeout. The walk stops at the
+# budget and logs what it skipped, the same way it does at the application cap.
+MAX_FAN_OUT_SECONDS = 4 * 60 * 60
# Repository objects' credential fields are write-only in the Argo CD API, but drop them
# defensively in case a server version ever echoes one back.
@@ -236,13 +256,284 @@ def _normalize_cluster(item: dict[str, Any]) -> dict[str, Any]:
return {k: v for k, v in item.items() if k != "config"}
-@retry(
- retry=retry_if_exception_type((ArgocdRetryableError, requests.ReadTimeout, requests.ConnectionError)),
- stop=stop_after_attempt(MAX_RETRIES),
- wait=wait_exponential_jitter(initial=1, max=30),
- reraise=True,
-)
-def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+def _application_identity(app: dict[str, Any]) -> dict[str, Any]:
+ metadata = app.get("metadata") or {}
+ spec = app.get("spec") or {}
+ return {
+ "application_name": metadata.get("name"),
+ "application_namespace": metadata.get("namespace"),
+ "application_uid": metadata.get("uid"),
+ "project": spec.get("project"),
+ }
+
+
+def _normalize_event(event: dict[str, Any]) -> dict[str, Any]:
+ metadata = event.get("metadata") or {}
+ involved = event.get("involvedObject") or {}
+ return {
+ "uid": metadata.get("uid"),
+ "created_at": metadata.get("creationTimestamp"),
+ "reason": event.get("reason"),
+ "message": event.get("message"),
+ "type": event.get("type"),
+ "action": event.get("action"),
+ "count": event.get("count"),
+ "first_timestamp": event.get("firstTimestamp"),
+ "last_timestamp": event.get("lastTimestamp"),
+ "event_time": event.get("eventTime"),
+ "involved_object_kind": involved.get("kind"),
+ "involved_object_name": involved.get("name"),
+ "involved_object_namespace": involved.get("namespace"),
+ "involved_object_uid": involved.get("uid"),
+ "reporting_component": event.get("reportingComponent"),
+ "reporting_instance": event.get("reportingInstance"),
+ "source": event.get("source"),
+ "series": event.get("series"),
+ "metadata": metadata,
+ }
+
+
+def _normalize_managed_resource(item: dict[str, Any]) -> dict[str, Any]:
+ return {
+ # Key columns must never be null: a core-API resource has no group and a
+ # cluster-scoped one has no namespace.
+ "group": item.get("group") or "",
+ "kind": item.get("kind") or "",
+ "namespace": item.get("namespace") or "",
+ "name": item.get("name") or "",
+ "modified": item.get("modified"),
+ "hook": item.get("hook"),
+ "resource_version": item.get("resourceVersion"),
+ "diff": item.get("diff"),
+ "live_state": item.get("liveState"),
+ "target_state": item.get("targetState"),
+ "normalized_live_state": item.get("normalizedLiveState"),
+ "predicted_live_state": item.get("predictedLiveState"),
+ }
+
+
+def _normalize_resource_node(node: dict[str, Any], *, orphaned: bool) -> dict[str, Any]:
+ health = node.get("health") or {}
+ return {
+ "group": node.get("group") or "",
+ "kind": node.get("kind") or "",
+ "namespace": node.get("namespace") or "",
+ "name": node.get("name") or "",
+ "uid": node.get("uid"),
+ "version": node.get("version"),
+ # Orphaned resources live in the application's namespace but are not managed by it.
+ "orphaned": orphaned,
+ "created_at": node.get("createdAt"),
+ "health_status": health.get("status"),
+ "health_message": health.get("message"),
+ "resource_version": node.get("resourceVersion"),
+ "images": node.get("images"),
+ "info": node.get("info"),
+ "parent_refs": node.get("parentRefs"),
+ "networking_info": node.get("networkingInfo"),
+ }
+
+
+def _normalize_revision_metadata(data: dict[str, Any], revision: str, source_index: int) -> dict[str, Any]:
+ return {
+ "revision": revision,
+ "source_index": source_index,
+ "author": data.get("author"),
+ "date": data.get("date"),
+ "message": data.get("message"),
+ "tags": data.get("tags"),
+ "references": data.get("references"),
+ "signature_info": data.get("signatureInfo"),
+ "source_integrity_result": data.get("sourceIntegrityResult"),
+ }
+
+
+def _child_params(app: dict[str, Any], extra: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ """Scope a per-application request to the application it was walked from.
+
+ With apps-in-any-namespace the name alone is ambiguous, and the project is what the
+ server checks the token's RBAC against.
+ """
+ metadata = app.get("metadata") or {}
+ spec = app.get("spec") or {}
+ params: dict[str, Any] = {}
+ if metadata.get("namespace"):
+ params["appNamespace"] = metadata["namespace"]
+ if spec.get("project"):
+ params["project"] = spec["project"]
+ if extra:
+ params.update(extra)
+ return params
+
+
+def _child_url(host: str, path: str, app: dict[str, Any], revision: Optional[str] = None, **params: Any) -> str:
+ name = (app.get("metadata") or {}).get("name") or ""
+ path = path.replace("{name}", quote(name, safe=""))
+ if revision is not None:
+ path = path.replace("{revision}", quote(revision, safe=""))
+ return _build_url(host, path, _child_params(app, params))
+
+
+def _revision_requests(app: dict[str, Any]) -> list[tuple[str, int]]:
+ """Distinct (revision, source index) pairs to resolve for one application.
+
+ Multi-source applications record one revision per source and the API resolves each by its
+ index. Chart revisions are left out: this endpoint resolves git commits through the repo
+ server, and a Helm chart version has its own endpoint. History runs oldest first, so it is
+ walked backwards to keep the most recent revisions when the cap bites.
+ """
+ history = (app.get("status") or {}).get("history") or []
+ pairs: list[tuple[str, int]] = []
+ seen: set[tuple[str, int]] = set()
+ for entry in reversed(history):
+ if not isinstance(entry, dict):
+ continue
+ sources = entry.get("sources") or []
+ revisions = entry.get("revisions") or []
+ if revisions:
+ candidates = [
+ (rev, index, sources[index] if index < len(sources) else {}) for index, rev in enumerate(revisions)
+ ]
+ else:
+ candidates = [(entry.get("revision"), 0, entry.get("source") or {})]
+ for revision, source_index, source in candidates:
+ if not revision or (isinstance(source, dict) and source.get("chart")):
+ continue
+ if (revision, source_index) in seen:
+ continue
+ seen.add((revision, source_index))
+ pairs.append((revision, source_index))
+ if len(pairs) >= MAX_REVISIONS_PER_APPLICATION:
+ return pairs
+ return pairs
+
+
+def _fetch_child(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ app_label: str,
+) -> Any:
+ """Fetch a per-application endpoint, returning ``None`` when the application is skipped.
+
+ These endpoints fail for one application at a time in ways a retry cannot fix: the
+ application was deleted during the walk, its spec does not compare so the server holds no
+ cached state, or its revision is not a commit the repo server can resolve. Argo CD reports
+ those as a 404 or a 500, so one broken application must not fail the whole table. A rejected
+ token or a blocked host still fails the sync.
+ """
+ try:
+ return _fetch(session, url, headers, logger, attempts=MAX_CHILD_RETRIES)
+ except requests.HTTPError as e:
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code in (401, 403):
+ raise
+ logger.warning(f"Argo CD: skipping application {app_label} for this endpoint: {e}")
+ return None
+ except (ArgocdRetryableError, requests.ReadTimeout, requests.ConnectionError) as e:
+ logger.warning(f"Argo CD: skipping application {app_label} for this endpoint: {e}")
+ return None
+
+
+def _child_rows(
+ session: requests.Session,
+ host: str,
+ headers: dict[str, str],
+ endpoint: str,
+ app: dict[str, Any],
+ logger: FilteringBoundLogger,
+ deadline: float,
+) -> Iterator[dict[str, Any]]:
+ identity = _application_identity(app)
+ app_label = f"{identity['application_namespace']}/{identity['application_name']}"
+ path = ARGOCD_ENDPOINTS[endpoint].path
+
+ if endpoint == "revision_metadata":
+ for revision, source_index in _revision_requests(app):
+ if time.monotonic() > deadline:
+ return
+ url = _child_url(host, path, app, revision=revision, sourceIndex=source_index)
+ data = _fetch_child(session, url, headers, logger, app_label)
+ if isinstance(data, dict):
+ yield {**identity, **_normalize_revision_metadata(data, revision, source_index)}
+ return
+
+ data = _fetch_child(session, _child_url(host, path, app), headers, logger, app_label)
+ if data is None:
+ return
+
+ if endpoint == "application_events":
+ for item in _items(data):
+ yield {**identity, **_normalize_event(item)}
+ elif endpoint == "managed_resources":
+ for item in _items(data):
+ yield {**identity, **_normalize_managed_resource(item)}
+ else:
+ # The resource tree is not a Kubernetes List: managed and orphaned resources arrive in
+ # separate arrays.
+ nodes = data.get("nodes") if isinstance(data, dict) else None
+ orphaned_nodes = data.get("orphanedNodes") if isinstance(data, dict) else None
+ for node in nodes or []:
+ yield {**identity, **_normalize_resource_node(node, orphaned=False)}
+ for node in orphaned_nodes or []:
+ yield {**identity, **_normalize_resource_node(node, orphaned=True)}
+
+
+def _fan_out_rows(
+ session: requests.Session,
+ host: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ project: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ headers = _get_headers(api_token)
+ apps_url = _build_url(host, ARGOCD_ENDPOINTS["applications"].path, _list_params("applications", project))
+ apps = _items(_fetch(session, apps_url, headers, logger))
+ if len(apps) > MAX_FAN_OUT_APPLICATIONS:
+ logger.warning(
+ f"Argo CD: {endpoint} walks at most {MAX_FAN_OUT_APPLICATIONS} applications, "
+ f"skipping {len(apps) - MAX_FAN_OUT_APPLICATIONS} of {len(apps)}"
+ )
+ apps = apps[:MAX_FAN_OUT_APPLICATIONS]
+
+ rows_per_batch = _MANAGED_RESOURCE_ROWS_PER_BATCH if endpoint == "managed_resources" else _ROWS_PER_BATCH
+ deadline = time.monotonic() + MAX_FAN_OUT_SECONDS
+ batch: list[dict[str, Any]] = []
+ for index, app in enumerate(apps):
+ if time.monotonic() > deadline:
+ logger.warning(
+ f"Argo CD: {endpoint} reached its {MAX_FAN_OUT_SECONDS}s budget after {index} applications, "
+ f"skipping the remaining {len(apps) - index}"
+ )
+ break
+ for row in _child_rows(session, host, headers, endpoint, app, logger, deadline):
+ batch.append(row)
+ if len(batch) >= rows_per_batch:
+ yield batch
+ batch = []
+ if batch:
+ yield batch
+
+
+def _fetch(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ attempts: int = MAX_RETRIES,
+) -> Any:
+ retrying = Retrying(
+ retry=retry_if_exception_type((ArgocdRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(attempts),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ return retrying(_fetch_once, session, url, headers, logger)
+
+
+def _fetch_once(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
# Don't follow redirects: the customer-controlled host could 3xx to an internal address,
# bypassing the host validation done before the request (SSRF). `stream=True` so bodies
# are only read through `_read_bounded` / `_error_snippet` under a byte cap.
@@ -295,6 +586,11 @@ def get_rows(
# default retries on would nest under it, so a host that stalls each read could occupy a
# worker for adapter_attempts × tenacity_attempts × timeout.
session = make_tracked_session(redact_values=(api_token,), capture=False, retry=Retry(total=0))
+
+ if config.fan_out:
+ yield from _fan_out_rows(session, host, api_token, endpoint, logger, project)
+ return
+
url = _build_url(host, config.path, _list_params(endpoint, project))
data = _fetch(session, url, _get_headers(api_token), logger)
items = _items(data)
@@ -347,6 +643,11 @@ def validate_credentials(
return False, host_err or HOST_NOT_ALLOWED_ERROR
endpoint = schema_name if schema_name in ARGOCD_ENDPOINTS else "applications"
+ if ARGOCD_ENDPOINTS[endpoint].fan_out:
+ # A per-application endpoint needs an application name in its path. It is only reached
+ # by walking the applications list and needs the same `applications, get` permission,
+ # so probing that list is the scoped check.
+ endpoint = "applications"
params = _list_params(endpoint, project)
if endpoint in ("applications", "deployment_history"):
# Filtering by a name that can't exist keeps the probe response tiny; servers that
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py
index 90125b0d8524..234ce9f014f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/canonical_descriptions.py
@@ -73,4 +73,99 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"info": "Cluster statistics such as application count and cache state.",
},
},
+ "application_events": {
+ "description": "Kubernetes events recorded against each Application resource, one row per event. This is the sync and health transition history behind each deployment. Argo CD stores these in Kubernetes, which expires them after about an hour, so the table only holds events seen by a sync.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app/",
+ "columns": {
+ "application_name": "Name of the application the event was recorded against.",
+ "application_namespace": "Namespace of the Application resource.",
+ "application_uid": "Kubernetes UID of the Application resource.",
+ "project": "Argo CD project the application belongs to.",
+ "uid": "Kubernetes UID of the event.",
+ "created_at": "Timestamp the event was recorded.",
+ "reason": "Short machine-readable reason, for example ResourceUpdated or OperationCompleted.",
+ "message": "Human-readable description of what happened.",
+ "type": "Event level (Normal or Warning).",
+ "action": "Action taken on the application, when the reporting component sets one.",
+ "count": "Number of times this event has repeated.",
+ "first_timestamp": "Timestamp the event first occurred.",
+ "last_timestamp": "Timestamp the event last occurred.",
+ "event_time": "Timestamp the event occurred, for components using the newer events API.",
+ "involved_object_kind": "Kind of the object the event is about (Application).",
+ "involved_object_name": "Name of the object the event is about.",
+ "involved_object_namespace": "Namespace of the object the event is about.",
+ "involved_object_uid": "Kubernetes UID of the object the event is about.",
+ "reporting_component": "Component that reported the event.",
+ "reporting_instance": "Instance of the component that reported the event.",
+ "source": "Component and host that generated the event.",
+ "series": "Count and last-observed time when the event repeats as a series.",
+ "metadata": "Full Kubernetes object metadata of the event.",
+ },
+ },
+ "revision_metadata": {
+ "description": "Git commit metadata for each revision an application deployed, resolved from the repository. Join it to deployment_history on revision to get the author, message, and commit date behind a deployment. Helm chart revisions are not included.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app_get/",
+ "columns": {
+ "application_name": "Name of the application that deployed the revision.",
+ "application_namespace": "Namespace of the Application resource.",
+ "application_uid": "Kubernetes UID of the Application resource.",
+ "project": "Argo CD project the application belongs to.",
+ "revision": "Git revision (commit SHA) the metadata describes.",
+ "source_index": "Index of the application source the revision belongs to; 0 for single-source applications.",
+ "author": "Who authored the commit, typically a name and email address.",
+ "date": "Timestamp of the commit.",
+ "message": "Commit message.",
+ "tags": "Git tags currently pointing at the revision.",
+ "references": "Related references for the commit, such as the pull request it came from.",
+ "signature_info": "Hint about the GPG signer, when signature verification is enabled.",
+ "source_integrity_result": "Result of Argo CD's source integrity check for the revision.",
+ },
+ },
+ "managed_resources": {
+ "description": "Every Kubernetes resource an application owns, with its live and target state, so you can measure configuration drift. Argo CD masks the values inside Secret resources, but any other manifest is synced as the API returns it.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/user-guide/diffing/",
+ "columns": {
+ "application_name": "Name of the application that manages the resource.",
+ "application_namespace": "Namespace of the Application resource.",
+ "application_uid": "Kubernetes UID of the Application resource.",
+ "project": "Argo CD project the application belongs to.",
+ "group": "Kubernetes API group of the resource; empty for core resources.",
+ "kind": "Kubernetes kind of the resource, for example Deployment or Service.",
+ "namespace": "Namespace the resource lives in; empty for cluster-scoped resources.",
+ "name": "Name of the resource.",
+ "modified": "Whether the live resource differs from the target state in Git.",
+ "hook": "Whether the resource is a sync hook.",
+ "resource_version": "Kubernetes resource version of the live resource.",
+ "diff": "JSON patch between the live and target state. Argo CD deprecated this in favor of normalized_live_state and predicted_live_state.",
+ "live_state": "JSON manifest of the resource as it currently runs in the cluster.",
+ "target_state": "JSON manifest of the resource as defined in Git or Helm.",
+ "normalized_live_state": "Live manifest after Argo CD's normalizations, such as ignoring defaulted fields.",
+ "predicted_live_state": "Manifest Argo CD predicts the cluster would hold after applying the target state.",
+ },
+ },
+ "resource_tree": {
+ "description": "Live Kubernetes resources in each application's tree, one row per resource, with its own health status. Use it to find which resource makes an application unhealthy.",
+ "docs_url": "https://argo-cd.readthedocs.io/en/stable/operator-manual/health/",
+ "columns": {
+ "application_name": "Name of the application the resource belongs to.",
+ "application_namespace": "Namespace of the Application resource.",
+ "application_uid": "Kubernetes UID of the Application resource.",
+ "project": "Argo CD project the application belongs to.",
+ "group": "Kubernetes API group of the resource; empty for core resources.",
+ "kind": "Kubernetes kind of the resource, for example Pod or ReplicaSet.",
+ "namespace": "Namespace the resource lives in; empty for cluster-scoped resources.",
+ "name": "Name of the resource.",
+ "uid": "Kubernetes UID of the live resource.",
+ "version": "Kubernetes API version of the resource.",
+ "orphaned": "Whether the resource sits in the application's namespace without being managed by it.",
+ "created_at": "Timestamp the live resource was created.",
+ "health_status": "Health of this resource (Healthy, Progressing, Degraded, Suspended, Missing, or Unknown).",
+ "health_message": "Explanation of the resource's health, when Argo CD reports one.",
+ "resource_version": "Kubernetes resource version of the live resource.",
+ "images": "Container images the resource runs, for workload resources.",
+ "info": "Extra details Argo CD surfaces about the resource, such as revision or route.",
+ "parent_refs": "Resources that own this one, giving the tree its hierarchy.",
+ "networking_info": "Networking details for the resource, such as ingress hosts and labels.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py
index e9048ac03606..24747a805e03 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/settings.py
@@ -1,15 +1,18 @@
-from dataclasses import dataclass
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+@frozen
class ArgocdEndpointConfig:
name: str
path: str
primary_keys: list[str]
# Stable, immutable field to partition by (creation/deployment timestamps only).
partition_key: str | None = None
+ # Per-application endpoint: `path` carries a `{name}` (and possibly `{revision}`)
+ # placeholder and is fetched once per application from the applications list.
+ fan_out: bool = False
# Argo CD's list APIs return the whole collection in one Kubernetes-style List response
@@ -49,6 +52,37 @@ ARGOCD_ENDPOINTS: dict[str, ArgocdEndpointConfig] = {
path="/api/v1/clusters",
primary_keys=["server"],
),
+ "application_events": ArgocdEndpointConfig(
+ name="application_events",
+ path="/api/v1/applications/{name}/events",
+ # Event UIDs are unique within the Argo CD control-plane cluster; the parent identity
+ # keeps the key unambiguous and makes the table joinable without a lookup.
+ primary_keys=["application_namespace", "application_name", "uid"],
+ partition_key="created_at",
+ fan_out=True,
+ ),
+ "revision_metadata": ArgocdEndpointConfig(
+ name="revision_metadata",
+ path="/api/v1/applications/{name}/revisions/{revision}/metadata",
+ # One row per revision each application deployed, resolved per source for
+ # multi-source applications.
+ primary_keys=["application_namespace", "application_name", "revision", "source_index"],
+ fan_out=True,
+ ),
+ "managed_resources": ArgocdEndpointConfig(
+ name="managed_resources",
+ path="/api/v1/applications/{name}/managed-resources",
+ # Managed resources have no id of their own, so the key is the Kubernetes resource
+ # identity within the application.
+ primary_keys=["application_namespace", "application_name", "group", "kind", "namespace", "name"],
+ fan_out=True,
+ ),
+ "resource_tree": ArgocdEndpointConfig(
+ name="resource_tree",
+ path="/api/v1/applications/{name}/resource-tree",
+ primary_keys=["application_namespace", "application_name", "group", "kind", "namespace", "name"],
+ fan_out=True,
+ ),
}
ENDPOINTS = tuple(ARGOCD_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
index eda861a9c206..5bae72fbb81b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/source.py
@@ -48,7 +48,7 @@ class ArgocdSource(SimpleSource[ArgocdSourceConfig]):
label="Argo CD",
keywords=["argo", "gitops", "kubernetes", "deployments"],
releaseStatus=ReleaseStatus.ALPHA,
- caption="""Sync applications, deployment history, projects, repositories, and clusters from your Argo CD server, e.g. to track deployment frequency and rollback rates.
+ caption="""Sync applications, deployment history, events, managed resources, commit metadata, projects, repositories, and clusters from your Argo CD server, e.g. to track deployment frequency and configuration drift.
Generate an API token with `argocd account generate-token`. The account needs the `apiKey` capability enabled and read access to the resources you want to sync, for example:
- `applications, get`
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
index 8d9e57e54740..02348a167ff4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
@@ -4,6 +4,8 @@ from typing import Any, Optional
import pytest
from unittest import mock
+import requests
+
from products.warehouse_sources.backend.temporal.data_imports.sources.argocd import argocd as argocd_module
from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.argocd import (
HOST_NOT_ALLOWED_ERROR,
@@ -17,12 +19,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.arg
_list_params,
_normalize_application,
_normalize_cluster,
+ _normalize_event,
+ _normalize_managed_resource,
_normalize_repository,
+ _normalize_resource_node,
+ _revision_requests,
argocd_source,
get_rows,
normalize_host,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.argocd.settings import ARGOCD_ENDPOINTS
APPLICATION = {
"metadata": {
@@ -55,9 +62,27 @@ def _response(*, status_code: int = 200, json_data: Any = None, text: str = "")
response.iter_content = mock.Mock(side_effect=lambda chunk_size: iter([body] if body else []))
response.__enter__ = mock.Mock(return_value=response)
response.__exit__ = mock.Mock(return_value=False)
+ if not response.ok:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status_code} Client Error: for url: https://argocd.example.com", response=response
+ )
return response
+def _patch_session_by_url(responses: dict[str, mock.MagicMock]):
+ """Patch the session so each request is answered by the first matching URL fragment."""
+ session = mock.MagicMock()
+
+ def _get(url: str, **_kwargs: Any) -> mock.MagicMock:
+ for fragment, response in responses.items():
+ if fragment in url:
+ return response
+ raise AssertionError(f"unexpected request: {url}")
+
+ session.get.side_effect = _get
+ return mock.patch.object(argocd_module, "make_tracked_session", return_value=session)
+
+
def _patch_session(response: Optional[mock.MagicMock] = None, raises: Optional[Exception] = None):
session = mock.MagicMock()
if raises is not None:
@@ -187,6 +212,69 @@ class TestNormalization:
)
assert row == {"repo": "https://github.com/org/repo"}
+ def test_event_lifts_identity_and_involved_object(self):
+ row = _normalize_event(
+ {
+ "metadata": {"uid": "ev-1", "creationTimestamp": "2025-02-01T00:00:00Z"},
+ "reason": "OperationCompleted",
+ "message": "Sync operation to abc succeeded",
+ "type": "Normal",
+ "involvedObject": {"kind": "Application", "name": "guestbook", "namespace": "argocd"},
+ }
+ )
+ assert row["uid"] == "ev-1"
+ assert row["created_at"] == "2025-02-01T00:00:00Z"
+ assert row["reason"] == "OperationCompleted"
+ assert row["involved_object_name"] == "guestbook"
+
+ @pytest.mark.parametrize(
+ "normalize, item",
+ [
+ (_normalize_managed_resource, {"kind": "Namespace", "name": "web"}),
+ (lambda item: _normalize_resource_node(item, orphaned=False), {"kind": "Namespace", "name": "web"}),
+ ],
+ )
+ def test_key_columns_are_never_null(self, normalize, item):
+ # group and namespace are absent for core-API and cluster-scoped resources, and both
+ # are primary key columns.
+ row = normalize(item)
+ assert row["group"] == ""
+ assert row["namespace"] == ""
+ assert row["name"] == "web"
+
+ def test_managed_resource_carries_live_and_target_state(self):
+ row = _normalize_managed_resource(
+ {
+ "group": "apps",
+ "kind": "Deployment",
+ "namespace": "web",
+ "name": "frontend",
+ "modified": True,
+ "liveState": '{"spec":{"replicas":3}}',
+ "targetState": '{"spec":{"replicas":2}}',
+ "normalizedLiveState": '{"spec":{"replicas":3}}',
+ "predictedLiveState": '{"spec":{"replicas":2}}',
+ }
+ )
+ assert row["modified"] is True
+ assert row["live_state"] == '{"spec":{"replicas":3}}'
+ assert row["target_state"] == '{"spec":{"replicas":2}}'
+
+ def test_resource_node_lifts_health(self):
+ row = _normalize_resource_node(
+ {
+ "kind": "Pod",
+ "name": "frontend-abc",
+ "namespace": "web",
+ "uid": "pod-1",
+ "health": {"status": "Degraded", "message": "back-off restarting"},
+ },
+ orphaned=False,
+ )
+ assert row["health_status"] == "Degraded"
+ assert row["health_message"] == "back-off restarting"
+ assert row["orphaned"] is False
+
class TestGetRows:
def _run(self, endpoint: str, response: mock.MagicMock, host: str = "https://argocd.example.com", **kwargs: Any):
@@ -351,6 +439,315 @@ class TestGetRows:
argocd_module._read_bounded(slow, max_bytes=1_000, max_seconds=600)
+MULTI_SOURCE_APPLICATION = {
+ "metadata": {"name": "multi", "namespace": "team-ns", "uid": "uid-2"},
+ "spec": {"project": "team-a"},
+ "status": {
+ "history": [
+ {
+ "id": 1,
+ "revisions": ["sha-old", "1.2.3"],
+ "sources": [{"repoURL": "https://github.com/org/repo"}, {"chart": "nginx"}],
+ },
+ {
+ "id": 2,
+ "revisions": ["sha-new", "1.2.4"],
+ "sources": [{"repoURL": "https://github.com/org/repo"}, {"chart": "nginx"}],
+ },
+ ]
+ },
+}
+
+
+class TestRevisionRequests:
+ @pytest.mark.parametrize(
+ "app, expected",
+ [
+ # The metadata endpoint resolves git commits through the repo server. A Helm chart
+ # version is not one, so source index 1 of the multi-source app is never requested.
+ (MULTI_SOURCE_APPLICATION, [("sha-new", 0), ("sha-old", 0)]),
+ # Newest first, so the cap keeps the recent revisions.
+ (APPLICATION, [("def", 0), ("abc", 0)]),
+ # A revision deployed twice is resolved once.
+ ({"status": {"history": [{"revision": "abc"}, {"revision": "abc"}]}}, [("abc", 0)]),
+ ({"metadata": {"name": "new-app"}, "status": {}}, []),
+ ],
+ )
+ def test_revisions_to_resolve(self, app, expected):
+ assert _revision_requests(app) == expected
+
+ def test_cap_keeps_the_most_recent_revisions(self):
+ app = {"status": {"history": [{"revision": f"sha-{i}"} for i in range(10)]}}
+ with mock.patch.object(argocd_module, "MAX_REVISIONS_PER_APPLICATION", 3):
+ assert _revision_requests(app) == [("sha-9", 0), ("sha-8", 0), ("sha-7", 0)]
+
+
+class TestFanOut:
+ def _run(self, endpoint: str, responses: dict[str, mock.MagicMock], **kwargs: Any):
+ with _patch_session_by_url(responses) as patched:
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, patched.return_value
+
+ def _child_urls(self, session: mock.MagicMock, fragment: str) -> list[str]:
+ return [call.args[0] for call in session.get.call_args_list if fragment in call.args[0]]
+
+ def test_events_are_fetched_per_application_with_parent_scope(self):
+ events = {"items": [{"metadata": {"uid": "ev-1"}, "reason": "ResourceUpdated"}]}
+ rows, session = self._run(
+ "application_events",
+ {
+ "/events": _response(json_data=events),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ },
+ )
+
+ assert [row["uid"] for row in rows] == ["ev-1"]
+ assert rows[0]["application_name"] == "guestbook"
+ assert rows[0]["application_namespace"] == "argocd"
+ # The namespace and project come from the application that was walked, not from the
+ # source's optional project filter, because the name alone is ambiguous across
+ # namespaces.
+ url = self._child_urls(session, "/events")[0]
+ assert url.startswith("https://argocd.example.com/api/v1/applications/guestbook/events?")
+ assert "appNamespace=argocd" in url
+ assert "project=default" in url
+
+ def test_application_name_is_url_quoted_in_the_path(self):
+ app = {"metadata": {"name": "team/app one", "namespace": "argocd"}, "spec": {}, "status": {}}
+ _rows, session = self._run(
+ "resource_tree",
+ {
+ "/resource-tree": _response(json_data={"nodes": []}),
+ "/api/v1/applications": _response(json_data={"items": [app]}),
+ },
+ )
+ assert self._child_urls(session, "/resource-tree")[0].startswith(
+ "https://argocd.example.com/api/v1/applications/team%2Fapp%20one/resource-tree"
+ )
+
+ def test_revision_metadata_requests_each_revision_with_its_source_index(self):
+ rows, session = self._run(
+ "revision_metadata",
+ {
+ "/revisions/": _response(json_data={"author": "Jane <[email protected]>", "message": "ship it"}),
+ "/api/v1/applications": _response(json_data={"items": [MULTI_SOURCE_APPLICATION]}),
+ },
+ )
+
+ assert [row["revision"] for row in rows] == ["sha-new", "sha-old"]
+ assert rows[0]["author"] == "Jane <[email protected]>"
+ assert rows[0]["source_index"] == 0
+ assert rows[0]["application_name"] == "multi"
+ urls = self._child_urls(session, "/revisions/")
+ assert urls[0].startswith("https://argocd.example.com/api/v1/applications/multi/revisions/sha-new/metadata?")
+ assert "sourceIndex=0" in urls[0]
+
+ def test_resource_tree_flattens_managed_and_orphaned_nodes(self):
+ tree = {
+ "nodes": [{"kind": "Pod", "name": "frontend-abc", "namespace": "web", "uid": "pod-1"}],
+ "orphanedNodes": [{"kind": "ConfigMap", "name": "left-over", "namespace": "web", "uid": "cm-1"}],
+ }
+ rows, _session = self._run(
+ "resource_tree",
+ {
+ "/resource-tree": _response(json_data=tree),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ },
+ )
+
+ assert [(row["name"], row["orphaned"]) for row in rows] == [("frontend-abc", False), ("left-over", True)]
+
+ def test_empty_resource_tree_yields_nothing(self):
+ # An application with no cached tree marshals both node arrays as null.
+ rows, _session = self._run(
+ "resource_tree",
+ {
+ "/resource-tree": _response(json_data={"nodes": None, "orphanedNodes": None}),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ },
+ )
+ assert rows == []
+
+ def test_managed_resources_are_batched_smaller_than_other_endpoints(self):
+ # Each row carries the resource's full manifests, so the batch size must be the
+ # managed-resource one rather than the shared default.
+ items = [{"kind": "Pod", "name": f"pod-{i}", "namespace": "web"} for i in range(5)]
+ with (
+ mock.patch.object(argocd_module, "_MANAGED_RESOURCE_ROWS_PER_BATCH", 2),
+ mock.patch.object(argocd_module, "_ROWS_PER_BATCH", 1000),
+ _patch_session_by_url(
+ {
+ "/managed-resources": _response(json_data={"items": items}),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ }
+ ),
+ ):
+ batches = list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="managed_resources",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+ assert [len(batch) for batch in batches] == [2, 2, 1]
+
+ def test_parent_walk_honours_the_project_filter(self):
+ _rows, session = self._run(
+ "application_events",
+ {
+ "/events": _response(json_data={"items": None}),
+ "/api/v1/applications": _response(json_data={"items": []}),
+ },
+ project="team-a",
+ )
+ assert "projects=team-a" in session.get.call_args_list[0].args[0]
+
+ def test_application_walk_is_capped(self):
+ apps = [{"metadata": {"name": f"app-{i}", "namespace": "argocd"}, "spec": {}, "status": {}} for i in range(4)]
+ logger = mock.MagicMock()
+ with (
+ mock.patch.object(argocd_module, "MAX_FAN_OUT_APPLICATIONS", 2),
+ _patch_session_by_url(
+ {
+ "/resource-tree": _response(json_data={"nodes": []}),
+ "/api/v1/applications": _response(json_data={"items": apps}),
+ }
+ ) as patched,
+ ):
+ list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="resource_tree",
+ team_id=1,
+ logger=logger,
+ )
+ )
+ assert len(self._child_urls(patched.return_value, "/resource-tree")) == 2
+ logger.warning.assert_called_once()
+
+ def test_walk_stops_at_its_time_budget(self):
+ # Per-request limits reset on the next request, so without a budget for the walk a slow
+ # host holds an import worker for one request per application. A budget already spent
+ # stops the walk, so no application is requested.
+ apps = [{"metadata": {"name": f"app-{i}", "namespace": "argocd"}, "spec": {}, "status": {}} for i in range(4)]
+ logger = mock.MagicMock()
+ with (
+ mock.patch.object(argocd_module, "MAX_FAN_OUT_SECONDS", -1),
+ _patch_session_by_url(
+ {
+ "/resource-tree": _response(json_data={"nodes": []}),
+ "/api/v1/applications": _response(json_data={"items": apps}),
+ }
+ ) as patched,
+ ):
+ list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="resource_tree",
+ team_id=1,
+ logger=logger,
+ )
+ )
+ assert self._child_urls(patched.return_value, "/resource-tree") == []
+ logger.warning.assert_called_once()
+
+ @pytest.mark.parametrize(
+ "endpoint, fragment, json_data",
+ [
+ ("application_events", "/events", {"items": [{"metadata": {"uid": "ev-1"}}]}),
+ ("revision_metadata", "/revisions/", {"author": "Jane"}),
+ ("managed_resources", "/managed-resources", {"items": [{"kind": "Pod", "name": "frontend"}]}),
+ ("resource_tree", "/resource-tree", {"nodes": [{"kind": "Pod", "name": "frontend"}]}),
+ ],
+ )
+ def test_every_row_carries_its_primary_key_columns(self, endpoint, fragment, json_data):
+ # A key column missing from a normalized row makes the Delta merge match on null, so
+ # the rows duplicate on every sync.
+ rows, _session = self._run(
+ endpoint,
+ {
+ fragment: _response(json_data=json_data),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ },
+ )
+ assert rows
+ for row in rows:
+ for key in ARGOCD_ENDPOINTS[endpoint].primary_keys:
+ assert row.get(key) is not None
+
+ @pytest.mark.parametrize("status_code", [400, 404, 500])
+ def test_one_broken_application_is_skipped_not_fatal(self, status_code):
+ # Argo CD reports a deleted application, an uncomparable spec and an unresolvable
+ # revision as 404/500 for that one application. The rest of the table must still sync.
+ apps = [
+ {"metadata": {"name": "broken", "namespace": "argocd"}, "spec": {}, "status": {}},
+ {"metadata": {"name": "healthy", "namespace": "argocd"}, "spec": {}, "status": {}},
+ ]
+ logger = mock.MagicMock()
+ with (
+ mock.patch.object(argocd_module, "MAX_CHILD_RETRIES", 1),
+ _patch_session_by_url(
+ {
+ "/broken/resource-tree": _response(status_code=status_code),
+ "/healthy/resource-tree": _response(
+ json_data={"nodes": [{"kind": "Pod", "name": "p", "namespace": "web"}]}
+ ),
+ "/api/v1/applications": _response(json_data={"items": apps}),
+ }
+ ),
+ ):
+ rows = [
+ row
+ for batch in get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="resource_tree",
+ team_id=1,
+ logger=logger,
+ )
+ for row in batch
+ ]
+
+ assert [row["application_name"] for row in rows] == ["healthy"]
+ logger.warning.assert_called_once()
+
+ @pytest.mark.parametrize("status_code", [401, 403])
+ def test_rejected_token_fails_the_sync(self, status_code):
+ # A skipped application must not hide a token that the server no longer accepts.
+ with (
+ mock.patch.object(argocd_module, "MAX_CHILD_RETRIES", 1),
+ _patch_session_by_url(
+ {
+ "/resource-tree": _response(status_code=status_code),
+ "/api/v1/applications": _response(json_data={"items": [APPLICATION]}),
+ }
+ ),
+ pytest.raises(requests.HTTPError),
+ ):
+ list(
+ get_rows(
+ host="https://argocd.example.com",
+ api_token="tok",
+ endpoint="resource_tree",
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+ )
+
+
class TestValidateCredentials:
def test_success_without_reading_the_body(self):
# The probe runs inline on the API thread; on success it must decide from the status
@@ -373,6 +770,16 @@ class TestValidateCredentials:
url = patched.return_value.get.call_args.args[0]
assert url == "https://argocd.example.com/api/v1/projects"
+ @pytest.mark.parametrize(
+ "schema_name", ["application_events", "revision_metadata", "managed_resources", "resource_tree"]
+ )
+ def test_per_application_schema_probes_the_applications_list(self, schema_name):
+ # These paths need an application name, so the probe cannot request them directly.
+ # They are reached by walking the applications list and need the same permission.
+ with _patch_session(_response(json_data={"items": None})) as patched:
+ assert validate_credentials("https://argocd.example.com", "tok", schema_name=schema_name) == (True, None)
+ assert patched.return_value.get.call_args.args[0].startswith("https://argocd.example.com/api/v1/applications?")
+
def test_authority_parser_mismatch_is_rejected_without_probing(self):
# The probe must not be sent to a host the SSRF check never validated.
with _patch_session(_response(json_data={"items": None})) as patched:
@@ -436,16 +843,12 @@ class TestValidateCredentials:
assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
def test_ssl_error_gets_actionable_message(self):
- import requests
-
with _patch_session(raises=requests.exceptions.SSLError("self signed certificate")):
valid, msg = validate_credentials("https://argocd.example.com", "tok")
assert valid is False
assert "certificate" in (msg or "")
def test_connection_error_returns_failure(self):
- import requests
-
with _patch_session(raises=requests.exceptions.ConnectionError("boom")):
valid, msg = validate_credentials("https://argocd.example.com", "tok")
assert valid is False