> For the complete documentation index, see [llms.txt](https://docs.cennso.com/cennso/monitoring/latest/llms.txt) (all documentation: [llms.txt](https://docs.cennso.com/llms.txt)). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cennso.com/cennso/monitoring/latest/architecture.md).

# Architecture

This document describes the architecture of the Monitoring Extension.

The Monitoring Extension is built on three layers: an `Exporter` Custom Resource that declares the pipeline, a Crossplane composition that materializes stock Kubernetes resources from the CR, and a stock Telegraf pod that runs the data path.

```likec4 dynamicViewVariant=diagram viewId=index
// Monitoring Extension — architecture diagram
//
// Adapted from docs-from-design-draft/architecture.c4.
// Uses LikeC4 specification blocks with Cennso brand vocabulary.

specification {
  color cnc-blue       #1E75BC
  color cnf-cyan       #00C1D4
  color external-blue  #2E398A
  color infra-grey     #848687

  element platform {
    style { color cnc-blue }
  }
  element cluster {
    style {
      color cnc-blue
      multiple true
    }
  }
  element coreComponent {
    notation 'Cennso component'
    style { color cnc-blue }
  }
  element infrastructure {
    notation 'Infrastructure'
    style { color infra-grey }
  }
  element external {
    notation 'External System'
    style { color external-blue }
  }
  element actor {
    style {
      shape person
      color cnc-blue
    }
  }

  relationship manages
  relationship pulls
  relationship pushes
  relationship authenticates
  relationship mounts
  relationship renders
}

model {

  operator = actor 'Platform operator' {
    description 'Authors Exporter resources to declare what metrics ship where.'
  }

  cennso = platform 'Cennso Platform' {
    description 'Crossplane-driven Kubernetes platform. Monitoring Extension reconciles each namespace-scoped Exporter resource into a running Telegraf pod.'

    mgmt = cluster 'Management Cluster' {
      description 'Hosts the Crossplane control plane and the Telegraf pods. All composed resources run in the same namespace as the Exporter CR.'

      crossplane = coreComponent 'Crossplane' {
        description 'Reconciles XRDs into composed resources.'
        technology 'Crossplane'

        cr = coreComponent 'Exporter (XR)' {
          description 'One namespace-scoped Composite Resource per pipeline. Reconciled into a ConfigMap, a Helm Release, and a reference to the OAuth2 Secret.'
        }

        composition = coreComponent 'Composition' {
          description 'Pipeline: function-go-templating renders provider configs, the Telegraf ConfigMap, and the Helm Release; function-extra-resources fetches the registry pull secret into context.'
        }

        fnExtras = coreComponent 'function-extra-resources' {
          description 'Step 4. Fetches the observed cennso-pull-secret Object into context so render-helm-release can conditionally switch to the private OCI registry.'
        }

        fn = coreComponent 'function-go-templating' {
          description 'Steps 1, 2, 3, 5. Renders provider configs, the Telegraf ConfigMap, and the Helm Release from the inline Go template and XR spec fields.'
        }

        template = infrastructure 'telegraf.toml.gotmpl' {
          description 'Inline Go template that renders the complete telegraf.conf from the XR spec fields.'
        }
      }

      configMap = infrastructure 'telegraf.conf ConfigMap' {
        description 'Rendered TOML: agent, inputs.promql, processors.rename, outputs.http (elasticcommonschema serializer), secretstores.oauth2 (when auth is configured), outputs.prometheus_client, outputs.health.'
      }

      secret = infrastructure 'OAuth2 credentials Secret' {
        description 'Pre-existing core/v1 Secret referenced by spec.sink.elastic.auth.oauth2.secretRef. Holds client_id, client_secret, token_endpoint, api_endpoint (the ingest gateway URL, used verbatim). The composition projects each key as an environment variable on the Telegraf container.'
      }

      release = infrastructure 'Telegraf Helm Release' {
        description 'Installs the official Telegraf chart with the Telegraf image.'
      }

      telegraf = coreComponent 'Telegraf pod' {
        description 'Stock Telegraf process configured by the rendered TOML. One pod per Exporter CR.'
        technology 'Telegraf'

        secretstoreOauth = coreComponent 'secretstores.oauth2' {
          description 'Fetches and refreshes OAuth 2.0 client-credentials tokens. Exposes them as @{cennso_oauth:access_token}. Reads client_id, client_secret, token_endpoint from environment variables.'
        }

        inputPromql = coreComponent 'inputs.promql' {
          description 'Polls a PromQL-compatible HTTP API with range queries at the configured interval.'
        }

        inputInternal = coreComponent 'inputs.internal' {
          description "Emits Telegraf's own runtime metrics for self-observability."
        }

        outputHttp = coreComponent 'outputs.http' {
          description 'POSTs an NDJSON stream of ECS-compliant documents (built by the elasticcommonschema serializer, no _bulk action lines) to an ingest gateway. Sets the Authorization bearer token via the secret reference from secretstores.oauth2.'
        }

        outputProm = coreComponent 'outputs.prometheus_client' {
          description 'Exposes Telegraf-internal series on :9273/metrics, filtered to internal_* names only.'
        }
      }
    }
  }

  metricsSource = external 'PromQL-compatible source' {
    description 'Prometheus or Grafana Mimir.'
  }

  idp = external 'Identity Provider' {
    description 'OAuth 2.0 token endpoint. Issues access tokens via client-credentials flow.'
  }

  observabilityBackend = external 'Elasticsearch cluster' {
    description 'Receives an NDJSON stream of ECS-compliant JSON metric documents. Typical target: an ingest gateway in front of an Elastic deployment or Elastic Cloud.'
  }

  // Operator workflow
  operator -> cennso.mgmt.crossplane.cr 'applies'

  // Crossplane reconciliation
  cennso.mgmt.crossplane.cr -> cennso.mgmt.crossplane.composition 'matches'
  cennso.mgmt.crossplane.composition -[renders]-> cennso.mgmt.crossplane.fn 'steps 1, 2, 3, 5'
  cennso.mgmt.crossplane.composition -> cennso.mgmt.crossplane.fnExtras 'step 4'
  cennso.mgmt.crossplane.template -> cennso.mgmt.crossplane.fn 'supplies Go template'
  cennso.mgmt.crossplane.fn -[renders]-> cennso.mgmt.configMap 'produces TOML'
  cennso.mgmt.crossplane.composition -[manages]-> cennso.mgmt.secret 'step 5 (reference only)'
  cennso.mgmt.crossplane.composition -[manages]-> cennso.mgmt.release 'step 5'

  // Release brings up the pod
  cennso.mgmt.release -> cennso.mgmt.telegraf 'installs'

  // Pod mounts
  cennso.mgmt.configMap -[mounts]-> cennso.mgmt.telegraf '/etc/telegraf-cennso/telegraf.conf'
  cennso.mgmt.secret -[mounts]-> cennso.mgmt.telegraf 'projected as env vars'

  // Internal token flow
  cennso.mgmt.telegraf.secretstoreOauth -[authenticates]-> idp 'client-credentials grant'
  cennso.mgmt.telegraf.secretstoreOauth -> cennso.mgmt.telegraf.outputHttp 'access token'

  // Data path
  cennso.mgmt.telegraf.inputPromql -[pulls]-> metricsSource 'range queries / HTTP'
  cennso.mgmt.telegraf.inputPromql -> cennso.mgmt.telegraf.outputHttp 'Telegraf metrics'
  cennso.mgmt.telegraf.inputInternal -> cennso.mgmt.telegraf.outputProm 'internal series'
  cennso.mgmt.telegraf.outputHttp -[pushes]-> observabilityBackend 'ECS JSON / NDJSON stream'
}

views {

  // ── 1. Context ──────────────────────────────────────────────────────────
  view index {
    title 'Monitoring Extension — Context'
    description 'Who interacts with the platform, and which external services Telegraf talks to at runtime.'

    include operator
    include cennso
    include metricsSource
    include idp
    include observabilityBackend

    autoLayout TopBottom
  }

  // ── 2. Crossplane reconciliation ────────────────────────────────────────
  view platform of cennso {
    title 'Monitoring Extension — Crossplane reconciliation'
    description 'How an Exporter resource becomes a running Telegraf pod via the Crossplane composition.'

    include *

    group 'Composition pipeline output' {
      include cennso.mgmt.configMap
      include cennso.mgmt.secret
      include cennso.mgmt.release
      include cennso.mgmt.telegraf
    }

    autoLayout TopBottom
  }

  // ── 3. Telegraf internals ────────────────────────────────────────────────
  view telegrafInternals of cennso.mgmt.telegraf {
    title 'Telegraf — plugin wiring'
    description 'Plugin set used inside the Telegraf process and how they hand metrics off to each other.'

    include *
    include metricsSource
    include idp
    include observabilityBackend
    include cennso.mgmt.configMap
    include cennso.mgmt.secret

    autoLayout LeftRight
  }

  // ── 4. Dataflow on one polling tick (dynamic) ───────────────────────────
  dynamic view dataflow {
    title 'Dataflow — one polling tick'
    description 'Token refresh (if needed), PromQL range query pull, NDJSON document stream push.'

    cennso.mgmt.telegraf.secretstoreOauth -> idp 'POST /oauth2/token (if expired)'
    idp -> cennso.mgmt.telegraf.secretstoreOauth 'access_token'

    cennso.mgmt.telegraf.inputPromql -> metricsSource 'GET /api/v1/query_range'
    metricsSource -> cennso.mgmt.telegraf.inputPromql 'samples'

    cennso.mgmt.telegraf.inputPromql -> cennso.mgmt.telegraf.outputHttp 'Telegraf metrics'
    cennso.mgmt.telegraf.secretstoreOauth -> cennso.mgmt.telegraf.outputHttp 'Bearer token'

    cennso.mgmt.telegraf.outputHttp -> observabilityBackend 'POST api_endpoint (ECS NDJSON documents)'
    observabilityBackend -> cennso.mgmt.telegraf.outputHttp '2xx'
  }
}
```

## Exporter

`Exporter` is a namespace-scoped Crossplane Composite Resource (XR) that serves as the operator-facing API. Each CR represents one independent export pipeline. All composed resources — the ConfigMap, the Helm Release, and the Telegraf pod — are created in the same namespace as the `Exporter` CR.

The CR schema has three top-level sections:

- **spec.deployment** — optional image and resource overrides for the Telegraf pod. When omitted, the composition uses its built-in defaults.
- **spec.source** — PromQL endpoint, authentication, polling parameters, and the list of metrics to export.
- **spec.sink** — discriminated union selecting the output type. Exactly one sink type must be specified. Currently only `elastic` is supported.

## Crossplane Composition

The composition processes each `Exporter` CR through a pipeline:

1. **render-providerconfigs** (`function-go-templating`) — Creates namespace-scoped ProviderConfigs for the Kubernetes and Helm providers, scoped to the same namespace as the `Exporter` CR.

2. **render-telegraf-toml** (`function-go-templating`) — Renders the full Telegraf TOML configuration from the XR fields using an inline Go template. The output is a `kubernetes.m.crossplane.io/v1alpha1` Object that materializes as a ConfigMap named `<name>-telegraf-conf` in the same namespace.

3. **observe-registry-secret** + **pull-registry-secret** (`function-go-templating` + `function-extra-resources`) — Mirrors the `cennso-pull-secret` as a read-only Object and fetches it into context. The next step uses it to conditionally switch the Telegraf image pull to the private OCI registry.

4. **render-helm-release** (`function-go-templating`) — Creates a `helm.m.crossplane.io/v1beta1` Release that installs the official Telegraf chart. The composition wires the XR namespace, the step-2 ConfigMap as a mounted volume, the image override, and the OAuth2 Secret name as an `envFromSecret` reference.

5. **sequence-creation** (`function-sequencer`) — Enforces creation order: ProviderConfigs → ConfigMap Object → Helm Release. The Helm Release is withheld from the desired state until the ConfigMap Object is Ready, preventing the Telegraf pod from starting before its configuration volume exists. On deletion, resources are removed in reverse order.

6. **auto-ready** (`function-auto-ready`) — Propagates the readiness of all composed resources to the `Exporter` XR. The XR reports `Ready=True` only when every composed resource (ProviderConfigs, ConfigMap Object, Helm Release) is Ready.

## Telegraf Pod

The Telegraf pod is configured entirely by the rendered ConfigMap. It uses the following plugins:

| Plugin | Role |
|---|---|
| `inputs.promql` | Polls the PromQL endpoint with range queries at the configured interval. |
| `processors.rename` | Rewrites Prometheus underscore labels to ECS dotted field names (`k8s_cluster_name` → `orchestrator.cluster.name`, `namespace` → `orchestrator.namespace`, `pod` → `orchestrator.resource.name`, `container` → `container.name`, `node` → `host.name`, `service` → `service.name`). |
| `outputs.http` (+ `elasticcommonschema` serializer) | POSTs an NDJSON stream of ECS-compliant documents (one per line, no Elasticsearch `_bulk` action lines) to an ingest gateway. The serializer expands dotted tag keys into nested objects, so each document includes `@timestamp`, `ecs.version`, `event.dataset`, the metric value nested under the measurement name, and the ECS fieldsets as nested objects at the document root. |
| `secretstores.oauth2` | Fetches and automatically refreshes OAuth 2.0 client-credentials tokens; exposes the token as `@{cennso_oauth:access_token}`. |
| `inputs.internal` | Emits Telegraf's own runtime metrics for self-observability. |
| `outputs.prometheus_client` | Exposes Telegraf-internal series on `:9273/metrics`, filtered to `internal_*` names only. |
| `outputs.health` | Serves a health endpoint on `:8080` used by liveness and readiness probes. |

The OAuth2 credentials Secret is projected as environment variables (`client_id`, `client_secret`, `token_endpoint`, `api_endpoint`) onto the Telegraf container. The rendered TOML reads them using Telegraf's built-in variable substitution (`${client_id}`, and so on). The `api_endpoint` variable holds the Elasticsearch HTTP URL.
