@intentius/chant-lexicon-k8s 0.102.0 → 0.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/codegen/generate.d.ts +26 -0
  2. package/dist/codegen/generate.d.ts.map +1 -1
  3. package/dist/components/kubectl-apply.d.ts +4 -1
  4. package/dist/components/kubectl-apply.d.ts.map +1 -1
  5. package/dist/composites/otel-collector-node.d.ts.map +1 -1
  6. package/dist/composites/otel-collector-rbac.d.ts.map +1 -1
  7. package/dist/composites/otel-collector-shape.d.ts +3 -1
  8. package/dist/composites/otel-collector-shape.d.ts.map +1 -1
  9. package/dist/crd/crd-sources.d.ts.map +1 -1
  10. package/dist/generated/index.d.ts +12 -0
  11. package/dist/generated/index.d.ts.map +1 -1
  12. package/dist/integrity.json +6 -6
  13. package/dist/lint/post-synth/wk8604.d.ts +3 -2
  14. package/dist/lint/post-synth/wk8604.d.ts.map +1 -1
  15. package/dist/manifest.json +1 -1
  16. package/dist/meta.json +63 -25
  17. package/dist/okf/index.md +1 -0
  18. package/dist/okf/types/GrafanaLibraryPanel.md +14 -0
  19. package/dist/rules/wk8602.ts +2 -2
  20. package/dist/rules/wk8604.ts +3 -2
  21. package/dist/serializer.d.ts +0 -3
  22. package/dist/serializer.d.ts.map +1 -1
  23. package/dist/telemetry-release.d.ts +15 -0
  24. package/dist/telemetry-release.d.ts.map +1 -0
  25. package/dist/types/index.d.ts +13 -0
  26. package/package.json +3 -3
  27. package/src/codegen/generate-crd-sources.test.ts +49 -0
  28. package/src/codegen/generate.ts +53 -14
  29. package/src/components/kubectl-apply.test.ts +87 -0
  30. package/src/components/kubectl-apply.ts +17 -1
  31. package/src/composites/otel-collector-gateway.test.ts +24 -1
  32. package/src/composites/otel-collector-gateway.ts +1 -1
  33. package/src/composites/otel-collector-node.test.ts +19 -0
  34. package/src/composites/otel-collector-node.ts +5 -7
  35. package/src/composites/otel-collector-rbac.test.ts +11 -0
  36. package/src/composites/otel-collector-rbac.ts +6 -4
  37. package/src/composites/otel-collector-shape.ts +9 -8
  38. package/src/composites/otel-collector.ts +1 -1
  39. package/src/crd/crd-sources.ts +4 -2
  40. package/src/generated/index.d.ts +13 -0
  41. package/src/generated/index.ts +12 -0
  42. package/src/generated/lexicon-k8s.json +63 -25
  43. package/src/generated/operations.json +16 -0
  44. package/src/lint/post-synth/otel-placement.test.ts +14 -0
  45. package/src/lint/post-synth/wk8602.ts +2 -2
  46. package/src/lint/post-synth/wk8604.ts +3 -2
  47. package/src/lint/post-synth/wk8605.test.ts +12 -0
  48. package/src/serializer-telemetry.test.ts +146 -0
  49. package/src/serializer.ts +75 -0
  50. package/src/telemetry-build.test.ts +79 -0
  51. package/src/telemetry-release.ts +93 -0
@@ -1142,11 +1142,6 @@
1142
1142
  "apiVersion": "v1",
1143
1143
  "gvkKind": "ConfigMapList"
1144
1144
  },
1145
- "ConfigMapRef": {
1146
- "resourceType": "K8s::Grafana::GrafanaDashboard.configMapRef",
1147
- "kind": "property",
1148
- "lexicon": "k8s"
1149
- },
1150
1145
  "Configuration": {
1151
1146
  "resourceType": "K8s::Cnpg::ObjectStore.configuration",
1152
1147
  "kind": "property",
@@ -1966,11 +1961,6 @@
1966
1961
  "kind": "property",
1967
1962
  "lexicon": "k8s"
1968
1963
  },
1969
- "GrafanaCom": {
1970
- "resourceType": "K8s::Grafana::GrafanaDashboard.grafanaCom",
1971
- "kind": "property",
1972
- "lexicon": "k8s"
1973
- },
1974
1964
  "GrafanaDashboard": {
1975
1965
  "resourceType": "K8s::Grafana::GrafanaDashboard",
1976
1966
  "kind": "resource",
@@ -2095,6 +2085,69 @@
2095
2085
  "kind": "property",
2096
2086
  "lexicon": "k8s"
2097
2087
  },
2088
+ "GrafanaLibraryPanel": {
2089
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel",
2090
+ "kind": "resource",
2091
+ "lexicon": "k8s",
2092
+ "apiVersion": "grafana.integreatly.org/v1beta1",
2093
+ "gvkKind": "GrafanaLibraryPanel",
2094
+ "specSchema": {"type":"object","fields":{"allowCrossNamespaceImport":{"type":"boolean"},"configMapRef":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]},"contentCacheDuration":{"type":"string"},"datasources":{"type":"array","items":{"type":"object","fields":{"datasourceName":{"type":"string"},"inputName":{"type":"string"}},"required":["datasourceName","inputName"]}},"envFrom":{"type":"array","items":{"type":"object","fields":{"configMapKeyRef":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]},"secretKeyRef":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]}}}},"envs":{"type":"array","items":{"type":"object","fields":{"name":{"type":"string"},"value":{"type":"string"},"valueFrom":{"type":"object","fields":{"configMapKeyRef":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]},"secretKeyRef":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]}}}},"required":["name"]}},"folderRef":{"type":"string"},"folderUID":{"type":"string"},"grafanaCom":{"type":"object","fields":{"id":{"type":"integer"},"revision":{"type":"integer"}},"required":["id"]},"gzipJson":{"type":"string"},"instanceSelector":{"type":"object","fields":{"matchExpressions":{"type":"array","items":{"type":"object","fields":{"key":{"type":"string"},"operator":{"type":"string"},"values":{"type":"array","items":{"type":"string"}}},"required":["key","operator"]}},"matchLabels":{"type":"object","open":true}}},"json":{"type":"string"},"jsonnet":{"type":"string"},"jsonnetLib":{"type":"object","fields":{"fileName":{"type":"string"},"gzipJsonnetProject":{"type":"string"},"jPath":{"type":"array","items":{"type":"string"}}},"required":["fileName","gzipJsonnetProject"]},"oci":{"type":"object","fields":{"insecurePlainHTTP":{"type":"boolean"},"path":{"type":"string"},"pullSecretRef":{"type":"object","fields":{"name":{"type":"string"}}},"reference":{"type":"string"}},"required":["path","reference"]},"plugins":{"type":"array","items":{"type":"object","fields":{"name":{"type":"string"},"version":{"type":"string"}},"required":["name","version"]}},"resyncPeriod":{"type":"string"},"suspend":{"type":"boolean"},"uid":{"type":"string"},"url":{"type":"string"},"urlAuthorization":{"type":"object","fields":{"basicAuth":{"type":"object","fields":{"password":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]},"username":{"type":"object","fields":{"key":{"type":"string"},"name":{"type":"string"},"optional":{"type":"boolean"}},"required":["key"]}}}}}},"required":["instanceSelector"]}
2095
+ },
2096
+ "GrafanaLibraryPanel_ConfigMapRef": {
2097
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.configMapRef",
2098
+ "kind": "property",
2099
+ "lexicon": "k8s"
2100
+ },
2101
+ "GrafanaLibraryPanel_Datasource": {
2102
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.datasources",
2103
+ "kind": "property",
2104
+ "lexicon": "k8s"
2105
+ },
2106
+ "GrafanaLibraryPanel_Env": {
2107
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.envs",
2108
+ "kind": "property",
2109
+ "lexicon": "k8s"
2110
+ },
2111
+ "GrafanaLibraryPanel_EnvFrom": {
2112
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.envFrom",
2113
+ "kind": "property",
2114
+ "lexicon": "k8s"
2115
+ },
2116
+ "GrafanaLibraryPanel_GrafanaCom": {
2117
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.grafanaCom",
2118
+ "kind": "property",
2119
+ "lexicon": "k8s"
2120
+ },
2121
+ "GrafanaLibraryPanel_InstanceSelector": {
2122
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.instanceSelector",
2123
+ "kind": "property",
2124
+ "lexicon": "k8s"
2125
+ },
2126
+ "GrafanaLibraryPanel_JsonnetLib": {
2127
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.jsonnetLib",
2128
+ "kind": "property",
2129
+ "lexicon": "k8s"
2130
+ },
2131
+ "GrafanaLibraryPanel_Oci": {
2132
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.oci",
2133
+ "kind": "property",
2134
+ "lexicon": "k8s"
2135
+ },
2136
+ "GrafanaLibraryPanel_Plugin": {
2137
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.plugins",
2138
+ "kind": "property",
2139
+ "lexicon": "k8s"
2140
+ },
2141
+ "GrafanaLibraryPanel_Status": {
2142
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.status",
2143
+ "kind": "property",
2144
+ "lexicon": "k8s"
2145
+ },
2146
+ "GrafanaLibraryPanel_UrlAuthorization": {
2147
+ "resourceType": "K8s::Grafana::GrafanaLibraryPanel.urlAuthorization",
2148
+ "kind": "property",
2149
+ "lexicon": "k8s"
2150
+ },
2098
2151
  "Group": {
2099
2152
  "resourceType": "K8s::Monitoring::PrometheusRule.groups",
2100
2153
  "kind": "property",
@@ -2885,11 +2938,6 @@
2885
2938
  "apiVersion": "batch/v1",
2886
2939
  "gvkKind": "JobList"
2887
2940
  },
2888
- "JsonnetLib": {
2889
- "resourceType": "K8s::Grafana::GrafanaDashboard.jsonnetLib",
2890
- "kind": "property",
2891
- "lexicon": "k8s"
2892
- },
2893
2941
  "K3sHelmChart": {
2894
2942
  "resourceType": "K8s::K3s::HelmChart",
2895
2943
  "kind": "resource",
@@ -3661,11 +3709,6 @@
3661
3709
  "kind": "property",
3662
3710
  "lexicon": "k8s"
3663
3711
  },
3664
- "Oci": {
3665
- "resourceType": "K8s::Grafana::GrafanaDashboard.oci",
3666
- "kind": "property",
3667
- "lexicon": "k8s"
3668
- },
3669
3712
  "OidcIdentityProviderConfig": {
3670
3713
  "resourceType": "K8s::Controlplane::AWSManagedControlPlane.oidcIdentityProviderConfig",
3671
3714
  "kind": "property",
@@ -5387,11 +5430,6 @@
5387
5430
  "kind": "property",
5388
5431
  "lexicon": "k8s"
5389
5432
  },
5390
- "UrlAuthorization": {
5391
- "resourceType": "K8s::Grafana::GrafanaDashboard.urlAuthorization",
5392
- "kind": "property",
5393
- "lexicon": "k8s"
5394
- },
5395
5433
  "User": {
5396
5434
  "resourceType": "K8s::Iam::User",
5397
5435
  "kind": "resource",
@@ -1761,6 +1761,22 @@
1761
1761
  "watch"
1762
1762
  ]
1763
1763
  },
1764
+ "K8s::Grafana::GrafanaLibraryPanel": {
1765
+ "entityType": "K8s::Grafana::GrafanaLibraryPanel",
1766
+ "apiVersion": "grafana.integreatly.org/v1beta1",
1767
+ "kind": "GrafanaLibraryPanel",
1768
+ "plural": "grafanalibrarypanels",
1769
+ "scope": "Namespaced",
1770
+ "verbs": [
1771
+ "delete",
1772
+ "get",
1773
+ "list",
1774
+ "patch",
1775
+ "post",
1776
+ "put",
1777
+ "watch"
1778
+ ]
1779
+ },
1764
1780
  "K8s::Iam::Policy": {
1765
1781
  "entityType": "K8s::Iam::Policy",
1766
1782
  "apiVersion": "iam.services.k8s.aws/v1alpha1",
@@ -306,6 +306,20 @@ describe("WK8602: multi-replica tail sampling gateway without trace-aware routin
306
306
  expect(wk8602.check(withAgent("otlphttp", "{ endpoint: 'http://gw:4318' }"))).toHaveLength(1);
307
307
  });
308
308
 
309
+ test.each([
310
+ ["otlp_grpc", "{ endpoint: gw.obs.svc.cluster.local:4317 }"],
311
+ ["otlp_http", "{ endpoint: 'http://gw:4318' }"],
312
+ ])("flags a hand-written exporter under the collector's newer name %s", (type, body) => {
313
+ expect(wk8602.check(withAgent(type, body))).toHaveLength(1);
314
+ });
315
+
316
+ test("reads load_balancing as loadbalancing", () => {
317
+ const diags = wk8602.check(withAgent("load_balancing", "{ protocol: { otlp: {} }, resolver: { dns: { hostname: gw.obs.svc } } }"));
318
+ expect(diags).toHaveLength(1);
319
+ expect(diags[0].message).toContain("one virtual IP");
320
+ expect(wk8602.check(withAgent("load_balancing", "{ routing_key: traceID, protocol: { otlp: {} }, resolver: { k8s: { service: gw-headless.obs } } }"))).toEqual([]);
321
+ });
322
+
309
323
  test("flags the dns resolver on the ClusterIP Service", () => {
310
324
  const diags = wk8602.check(withAgent("loadbalancing", "{ protocol: { otlp: {} }, resolver: { dns: { hostname: gw.obs.svc } } }"));
311
325
  expect(diags).toHaveLength(1);
@@ -20,10 +20,10 @@
20
20
  */
21
21
 
22
22
  import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
23
+ import { canonicalTypeOf } from "@intentius/chant-lexicon-otel/model";
23
24
  import { docsToManifests } from "./k8s-helpers";
24
25
  import {
25
26
  collectorPlacements,
26
- componentType,
27
27
  describePlacement,
28
28
  hostOfEndpoint,
29
29
  pipelinesOf,
@@ -47,7 +47,7 @@ function unroutedExporters(sender: CollectorPlacement, services: Map<string, boo
47
47
  for (const id of pipeline.exporters) {
48
48
  if (seen.has(id)) continue;
49
49
  seen.add(id);
50
- const type = componentType(id);
50
+ const type = canonicalTypeOf("exporter", id);
51
51
  const cfg = record(sender.config.exporters?.[id]);
52
52
 
53
53
  if (type === "loadbalancing") {
@@ -7,9 +7,10 @@
7
7
  * otel lexicon's config checks never see a config that lives in the k8s output
8
8
  * (chant #2930). This check runs them there: every ConfigMap data value that
9
9
  * parses as a collector config (a `service.pipelines` map) goes through the
10
- * otel lexicon's `validateCollectorConfig`.
10
+ * otel lexicon's `validateCollectorConfig`, and through `attributionIssues`
11
+ * (OTEL118) when the build stamps telemetry attribution.
11
12
  *
12
- * Findings keep the otel rule ids (OTEL101-OTEL106, OTEL112-OTEL117, and any config
13
+ * Findings keep the otel rule ids (OTEL101-OTEL106, OTEL112-OTEL127, and any config
13
14
  * check the otel lexicon adds later), so `lint.rules` and suppressions name
14
15
  * one id wherever the config lives. Each message names the ConfigMap's
15
16
  * namespace, name and key. Needs only the k8s lexicon in the project.
@@ -90,6 +90,18 @@ describe("WK8605: node-reading collector config without the node", () => {
90
90
  expect(d[0].message).toContain("filelog reads host /var/log/pods at /var/log/pods");
91
91
  });
92
92
 
93
+ test("the collector's newer names (host_metrics, file_log, k8s_attributes) are reported the same", () => {
94
+ const docs = daemonSet({}) as Array<Record<string, any>>;
95
+ docs[0].data["config.yaml"] = NODE_CONFIG.replace(/hostmetrics/g, "host_metrics")
96
+ .replace(/filelog/g, "file_log")
97
+ .replace(/k8sattributes/g, "k8s_attributes");
98
+ const d = wk8605.check(yaml(...docs));
99
+ expect(d).toHaveLength(1);
100
+ expect(d[0].message).toContain("no K8S_NODE_NAME variable (set it from spec.nodeName");
101
+ expect(d[0].message).toContain("host_metrics reads host / at /hostfs");
102
+ expect(d[0].message).toContain("file_log reads host /var/log/pods at /var/log/pods");
103
+ });
104
+
93
105
  test("the variable from any source and covering hostPath mounts pass, including partial host root mounts", () => {
94
106
  const d = wk8605.check(yaml(...daemonSet({
95
107
  env: [{ name: "K8S_NODE_NAME", value: "fixed" }],
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Telemetry attribution on k8s workloads (#3059, #2558 D22, ws-060): each
3
+ * container of a Deployment, StatefulSet, DaemonSet, ReplicaSet, Job, CronJob
4
+ * or Pod gets `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` when the
5
+ * build hands the serializer `context.telemetry`.
6
+ */
7
+ import { describe, expect, test } from "vitest";
8
+ import { loadAll } from "js-yaml";
9
+ import { DECLARABLE_MARKER } from "@intentius/chant/declarable";
10
+ import { k8sSerializer } from "./serializer";
11
+
12
+ function mockResource(entityType: string, props: Record<string, unknown>): any {
13
+ return { [DECLARABLE_MARKER]: true, lexicon: "k8s", entityType, kind: "resource", props };
14
+ }
15
+
16
+ type Doc = Record<string, any>;
17
+
18
+ function serialize(entities: Map<string, unknown>, telemetry?: { workspace?: string; member?: string; environment?: string }): string {
19
+ const result = k8sSerializer.serialize(entities as Map<string, any>, [], telemetry ? { telemetry } : undefined);
20
+ return typeof result === "string" ? result : result.primary;
21
+ }
22
+
23
+ function docs(out: string): Doc[] {
24
+ return loadAll(out) as Doc[];
25
+ }
26
+
27
+ const podSpec = (containers: unknown[]) => ({ containers });
28
+ const RELEASE_ENV = {
29
+ name: "CHANT_RELEASE_ATTRIBUTES",
30
+ valueFrom: { fieldRef: { fieldPath: "metadata.annotations['chant.intentius.io/release-attributes']" } },
31
+ };
32
+ const valueOf = (env: Doc[], name: string) => env.find((e) => e.name === name)?.value;
33
+ const attrs = { workspace: "acme", member: "delivery", environment: "prod" };
34
+
35
+ const workloads: Array<[string, string, (spec: unknown) => Record<string, unknown>, (doc: Doc) => Doc]> = [
36
+ ["Deployment", "K8s::Apps::Deployment", (s) => ({ spec: { template: { spec: s } } }), (d) => d.spec.template.spec],
37
+ ["StatefulSet", "K8s::Apps::StatefulSet", (s) => ({ spec: { template: { spec: s } } }), (d) => d.spec.template.spec],
38
+ ["DaemonSet", "K8s::Apps::DaemonSet", (s) => ({ spec: { template: { spec: s } } }), (d) => d.spec.template.spec],
39
+ ["Job", "K8s::Batch::Job", (s) => ({ spec: { template: { spec: s } } }), (d) => d.spec.template.spec],
40
+ ["CronJob", "K8s::Batch::CronJob", (s) => ({ spec: { schedule: "* * * * *", jobTemplate: { spec: { template: { spec: s } } } } }), (d) => d.spec.jobTemplate.spec.template.spec],
41
+ ["Pod", "K8s::Core::Pod", (s) => ({ spec: s }), (d) => d.spec],
42
+ ];
43
+
44
+ describe("telemetry attribution on workloads", () => {
45
+ test.each(workloads)("a %s's containers get OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES", (_kind, type, wrap, pod) => {
46
+ const entities = new Map([["apiWorkload", mockResource(type, { metadata: { name: "api" }, ...wrap(podSpec([{ name: "api", image: "nginx:1" }])) })]]);
47
+ const [doc] = docs(serialize(entities, attrs));
48
+ expect(pod(doc).containers[0].env).toEqual([
49
+ { name: "OTEL_SERVICE_NAME", value: "api" },
50
+ RELEASE_ENV,
51
+ {
52
+ name: "OTEL_RESOURCE_ATTRIBUTES",
53
+ value: "chant.workspace=acme,chant.member=delivery,chant.decl=apiWorkload,deployment.environment.name=prod$(CHANT_RELEASE_ATTRIBUTES)",
54
+ },
55
+ ]);
56
+ });
57
+
58
+ test("without a telemetry context the output is the same bytes as with an empty one, and has no OTEL_ variables", () => {
59
+ const entities = new Map([["api", mockResource("K8s::Apps::Deployment", { metadata: { name: "api" }, spec: { template: { spec: podSpec([{ name: "api", image: "nginx:1" }]) } } })]]);
60
+ const plain = serialize(entities);
61
+ expect(plain).toBe(k8sSerializer.serialize(entities as Map<string, any>, [], {}));
62
+ expect(plain).not.toContain("OTEL_");
63
+ });
64
+
65
+ test("a variable the container sets is kept, its own resource attributes keep their keys, and valueFrom is left alone", () => {
66
+ const containers = [
67
+ {
68
+ name: "own",
69
+ image: "x",
70
+ env: [
71
+ { name: "PORT", value: "80" },
72
+ { name: "OTEL_SERVICE_NAME", value: "checkout" },
73
+ { name: "OTEL_RESOURCE_ATTRIBUTES", value: "chant.member=mine,team=pay" },
74
+ ],
75
+ },
76
+ { name: "ref", image: "y", env: [{ name: "OTEL_RESOURCE_ATTRIBUTES", valueFrom: { configMapKeyRef: { name: "otel", key: "attrs" } } }] },
77
+ ];
78
+ const entities = new Map([["api", mockResource("K8s::Apps::Deployment", { metadata: { name: "api" }, spec: { template: { spec: podSpec(containers) } } })]]);
79
+ const [own, ref] = docs(serialize(entities, attrs))[0].spec.template.spec.containers;
80
+ expect(own.env).toEqual([
81
+ { name: "PORT", value: "80" },
82
+ { name: "OTEL_SERVICE_NAME", value: "checkout" },
83
+ RELEASE_ENV,
84
+ { name: "OTEL_RESOURCE_ATTRIBUTES", value: "chant.member=mine,team=pay,chant.workspace=acme,chant.decl=api,deployment.environment.name=prod$(CHANT_RELEASE_ATTRIBUTES)" },
85
+ ]);
86
+ expect(ref.env).toEqual([
87
+ { name: "OTEL_RESOURCE_ATTRIBUTES", valueFrom: { configMapKeyRef: { name: "otel", key: "attrs" } } },
88
+ { name: "OTEL_SERVICE_NAME", value: "api" },
89
+ ]);
90
+ });
91
+
92
+ test("an env given as a map keeps its keys and gains the missing ones, without the release reference a map cannot order", () => {
93
+ const containers = [{ name: "api", image: "x", env: { PORT: "80", OTEL_SERVICE_NAME: "checkout" } }];
94
+ const entities = new Map([["api", mockResource("K8s::Core::Pod", { metadata: { name: "api" }, spec: podSpec(containers) })]]);
95
+ const env = docs(serialize(entities, { workspace: "acme" }))[0].spec.containers[0].env;
96
+ expect(env).toEqual({ PORT: "80", OTEL_SERVICE_NAME: "checkout", OTEL_RESOURCE_ATTRIBUTES: "chant.workspace=acme,chant.decl=api" });
97
+ });
98
+
99
+ test("an image pinned by digest gives service.version, per container", () => {
100
+ const containers = [
101
+ { name: "api", image: "ghcr.io/acme/api@sha256:abc123" },
102
+ { name: "proxy", image: "envoyproxy/envoy:v1.31" },
103
+ ];
104
+ const entities = new Map([["api", mockResource("K8s::Apps::Deployment", { metadata: { name: "api" }, spec: { template: { spec: podSpec(containers) } } })]]);
105
+ const [api, proxy] = docs(serialize(entities, { workspace: "acme" }))[0].spec.template.spec.containers;
106
+ expect(valueOf(api.env, "OTEL_RESOURCE_ATTRIBUTES")).toBe("chant.workspace=acme,chant.decl=api,service.version=sha256%3Aabc123$(CHANT_RELEASE_ATTRIBUTES)");
107
+ expect(valueOf(proxy.env, "OTEL_RESOURCE_ATTRIBUTES")).toBe("chant.workspace=acme,chant.decl=api$(CHANT_RELEASE_ATTRIBUTES)");
108
+ });
109
+
110
+ test("init containers, non-workload kinds and a CRD that reuses a workload kind name are not stamped", () => {
111
+ const entities = new Map<string, unknown>([
112
+ ["api", mockResource("K8s::Apps::Deployment", { metadata: { name: "api" }, spec: { template: { spec: { initContainers: [{ name: "init", image: "x" }], containers: [{ name: "api", image: "x" }] } } } })],
113
+ ["svc", mockResource("K8s::Core::Service", { metadata: { name: "api" }, spec: { ports: [{ port: 80 }] } })],
114
+ ["crd", mockResource("K8s::Apps::Deployment", { apiVersion: "example.com/v1", kind: "Deployment", metadata: { name: "x" }, spec: { template: { spec: podSpec([{ name: "x", image: "x" }]) } } })],
115
+ ]);
116
+ const out = docs(serialize(entities, attrs));
117
+ const deployment = out.find((d) => d.apiVersion === "apps/v1")!;
118
+ expect(deployment.spec.template.spec.initContainers[0].env).toBeUndefined();
119
+ expect(deployment.spec.template.spec.containers[0].env).toHaveLength(3);
120
+ expect(JSON.stringify(out.filter((d) => d !== deployment))).not.toContain("OTEL_");
121
+ });
122
+
123
+ test("a workload without metadata.name takes the name the serializer derives for it", () => {
124
+ const entities = new Map([["worker", mockResource("K8s::Batch::Job", { spec: { template: { spec: podSpec([{ name: "w", image: "x" }]) } } })]]);
125
+ const [doc] = docs(serialize(entities, { workspace: "acme" }));
126
+ expect(doc.spec.template.spec.containers[0].env[0]).toEqual({ name: "OTEL_SERVICE_NAME", value: doc.metadata.name });
127
+ });
128
+
129
+ test("the release reference is added once, and the variable is always defined before it", () => {
130
+ const containers = [
131
+ { name: "a", image: "x", env: [{ name: "OTEL_RESOURCE_ATTRIBUTES", value: "team=pay$(CHANT_RELEASE_ATTRIBUTES)" }] },
132
+ { name: "b", image: "x", env: [{ name: "CHANT_RELEASE_ATTRIBUTES", value: ",team=ops" }] },
133
+ ];
134
+ const entities = new Map([["api", mockResource("K8s::Apps::Deployment", { metadata: { name: "api" }, spec: { template: { spec: podSpec(containers) } } })]]);
135
+ const [a, b] = docs(serialize(entities, { workspace: "acme" }))[0].spec.template.spec.containers;
136
+ expect(valueOf(a.env, "OTEL_RESOURCE_ATTRIBUTES")).toBe("team=pay$(CHANT_RELEASE_ATTRIBUTES),chant.workspace=acme,chant.decl=api");
137
+ // The reference is already there, but the variable still has to be defined before it.
138
+ expect(a.env.map((e: Doc) => e.name)).toEqual(["CHANT_RELEASE_ATTRIBUTES", "OTEL_RESOURCE_ATTRIBUTES", "OTEL_SERVICE_NAME"]);
139
+ // The container's own definition comes first, so the reference reads it.
140
+ expect(b.env).toEqual([
141
+ { name: "CHANT_RELEASE_ATTRIBUTES", value: ",team=ops" },
142
+ { name: "OTEL_SERVICE_NAME", value: "api" },
143
+ { name: "OTEL_RESOURCE_ATTRIBUTES", value: "chant.workspace=acme,chant.decl=api$(CHANT_RELEASE_ATTRIBUTES)" },
144
+ ]);
145
+ });
146
+ });
package/src/serializer.ts CHANGED
@@ -9,6 +9,8 @@ import { createRequire } from "module";
9
9
  import type { Declarable } from "@intentius/chant/declarable";
10
10
  import { isPropertyDeclarable, isResourceDeclarable } from "@intentius/chant/declarable";
11
11
  import type { Serializer, SerializerResult, SerializeContext } from "@intentius/chant/serializer";
12
+ import { mergeResourceAttributes, RELEASE_ATTRIBUTES_VARIABLE, telemetryEnvironment, type TelemetryAttribution } from "@intentius/chant/telemetry-attribution";
13
+ import { podSpecOf, releaseAttributesEnv } from "./telemetry-release";
12
14
  import { ownershipEntries, LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership";
13
15
  import {
14
16
  isEffectReceipt,
@@ -300,6 +302,77 @@ function toYAMLValue(value: unknown, entityNames: Map<Declarable, string>): unkn
300
302
  /**
301
303
  * Kubernetes YAML serializer implementation.
302
304
  */
305
+ // ── Telemetry attribution (#2558, D22, #3059) ──────────────────────
306
+
307
+ /** The digest of an image reference pinned with `@sha256:...`, or undefined. */
308
+ function imageDigest(image: unknown): string | undefined {
309
+ if (typeof image !== "string") return undefined;
310
+ const at = image.lastIndexOf("@");
311
+ return at === -1 ? undefined : image.slice(at + 1);
312
+ }
313
+
314
+ /**
315
+ * Stamp `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` into the `env` of
316
+ * each container of a workload. `service.name` is the workload's
317
+ * `metadata.name`, `chant.decl` its declaration id (`decl`), and an image
318
+ * pinned by digest gives `service.version`. A variable the container already
319
+ * sets is kept: its own `OTEL_SERVICE_NAME` wins, and its own resource
320
+ * attributes keep their keys while the missing ones are appended. One set
321
+ * through `valueFrom` is left alone. Init containers are not stamped.
322
+ *
323
+ * `OTEL_RESOURCE_ATTRIBUTES` ends with `$(CHANT_RELEASE_ATTRIBUTES)`, read
324
+ * from the pod annotation a release deploy sets (#3061, ws-081), so a
325
+ * release adds `service.version` and `vcs.ref.head.revision` without
326
+ * changing this output.
327
+ */
328
+ function stampWorkloadTelemetry(manifest: Record<string, unknown>, decl: string, telemetry: TelemetryAttribution): void {
329
+ const podSpec = podSpecOf(manifest);
330
+ const containers = podSpec?.containers;
331
+ if (!Array.isArray(containers)) return;
332
+ const service = String((manifest.metadata as Record<string, unknown> | undefined)?.name ?? decl);
333
+ const releaseRef = `$(${RELEASE_ATTRIBUTES_VARIABLE})`;
334
+ for (const container of containers) {
335
+ if (!container || typeof container !== "object") continue;
336
+ const c = container as Record<string, unknown>;
337
+ const version = imageDigest(c.image);
338
+ const vars = telemetryEnvironment(telemetry, { service, decl, ...(version ? { version } : {}) });
339
+ if (c.env !== undefined && !Array.isArray(c.env) && typeof c.env === "object" && c.env !== null) {
340
+ // A map, as some composites and hand-written props give it before the API's list form. A map
341
+ // has no order, so it cannot hold the $(VAR) reference to the release attributes.
342
+ const map: Record<string, unknown> = { ...(c.env as Record<string, unknown>) };
343
+ if (!("OTEL_SERVICE_NAME" in map)) map.OTEL_SERVICE_NAME = vars.OTEL_SERVICE_NAME;
344
+ const own = map.OTEL_RESOURCE_ATTRIBUTES;
345
+ if (own === undefined) map.OTEL_RESOURCE_ATTRIBUTES = vars.OTEL_RESOURCE_ATTRIBUTES;
346
+ else if (typeof own === "string") map.OTEL_RESOURCE_ATTRIBUTES = mergeResourceAttributes(own, vars.OTEL_RESOURCE_ATTRIBUTES);
347
+ c.env = map;
348
+ continue;
349
+ }
350
+ const env = Array.isArray(c.env) ? [...(c.env as Array<Record<string, unknown>>)] : [];
351
+ const at = (key: string) => env.findIndex((e) => e && typeof e === "object" && e.name === key);
352
+ if (at("OTEL_SERVICE_NAME") === -1) env.push({ name: "OTEL_SERVICE_NAME", value: vars.OTEL_SERVICE_NAME });
353
+ let i = at("OTEL_RESOURCE_ATTRIBUTES");
354
+ if (i === -1) {
355
+ env.push({ name: "OTEL_RESOURCE_ATTRIBUTES", value: vars.OTEL_RESOURCE_ATTRIBUTES });
356
+ i = env.length - 1;
357
+ } else if (typeof env[i]!.value === "string") {
358
+ env[i] = { ...env[i]!, value: mergeResourceAttributes(env[i]!.value as string, vars.OTEL_RESOURCE_ATTRIBUTES) };
359
+ }
360
+ // The release attributes (#3061, ws-081): a $(VAR) reference expands only to a variable defined
361
+ // earlier in the list, so the downward-API entry goes just before OTEL_RESOURCE_ATTRIBUTES. A
362
+ // container that defines the variable itself keeps its own, and gets the reference only when
363
+ // its definition comes first.
364
+ if (typeof env[i]!.value === "string") {
365
+ if (at(RELEASE_ATTRIBUTES_VARIABLE) === -1) {
366
+ env.splice(i, 0, releaseAttributesEnv());
367
+ i++;
368
+ }
369
+ const value = env[i]!.value as string;
370
+ if (at(RELEASE_ATTRIBUTES_VARIABLE) < i && !value.includes(releaseRef)) env[i] = { ...env[i]!, value: `${value}${releaseRef}` };
371
+ }
372
+ c.env = env;
373
+ }
374
+ }
375
+
303
376
  export const k8sSerializer: Serializer = {
304
377
  name: "k8s",
305
378
  rulePrefix: "WK8",
@@ -489,6 +562,8 @@ export const k8sSerializer: Serializer = {
489
562
  }
490
563
  }
491
564
 
565
+ if (context?.telemetry) stampWorkloadTelemetry(manifest, name, context.telemetry);
566
+
492
567
  // Emit as YAML — sort Namespaces first so kubectl apply succeeds
493
568
  const yamlDoc = emitK8sManifest(manifest);
494
569
  if (gvk.kind === "Namespace") {
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Telemetry attribution through a real k8s build (#3059): inside a workspace
3
+ * the workloads are stamped with the workspace and the member,
4
+ * `telemetry.attribution: false` turns that off, and outside a workspace
5
+ * nothing is stamped unless `telemetry.attribution: true` opts in.
6
+ */
7
+ import { afterAll, describe, expect, test } from "vitest";
8
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { dirname, join, resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { buildCommand } from "@intentius/chant/cli/commands/build";
13
+ import { loadPlugins, resolveProjectLexicons } from "@intentius/chant/cli";
14
+
15
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
16
+ const made: string[] = [];
17
+ afterAll(() => {
18
+ for (const dir of made) rmSync(dir, { recursive: true, force: true });
19
+ });
20
+
21
+ const APP = `import { Deployment } from "@intentius/chant-lexicon-k8s";
22
+
23
+ export const api = new Deployment({
24
+ metadata: { name: "api" },
25
+ spec: {
26
+ selector: { matchLabels: { app: "api" } },
27
+ template: {
28
+ metadata: { labels: { app: "api" } },
29
+ spec: { containers: [{ name: "api", image: "nginx:1.27" }] },
30
+ },
31
+ },
32
+ });
33
+ `;
34
+
35
+ /** A k8s project, inside a one-member workspace or on its own, built to YAML. */
36
+ async function build(options: { workspace: boolean; attribution?: boolean }): Promise<string> {
37
+ const root = mkdtempSync(join(tmpdir(), "chant-3059-"));
38
+ made.push(root);
39
+ mkdirSync(join(root, ".git"));
40
+ const project = options.workspace ? join(root, "svc") : root;
41
+ mkdirSync(join(project, "src"), { recursive: true });
42
+ if (options.workspace) {
43
+ writeFileSync(
44
+ join(root, "chant.workspace.json"),
45
+ JSON.stringify({ name: "acme", schema: 1, members: [{ name: "svc", dir: "svc", kind: "chant" }] }, null, 2),
46
+ );
47
+ }
48
+ const telemetry = options.attribution === undefined ? "" : ` telemetry: { attribution: ${options.attribution} },\n`;
49
+ writeFileSync(join(project, "chant.config.ts"), `export default {\n lexicons: ["k8s"],\n${telemetry}};\n`);
50
+ writeFileSync(join(project, "src", "app.ts"), APP);
51
+ symlinkSync(join(repoRoot, "node_modules"), join(project, "node_modules"), "dir");
52
+
53
+ const src = join(project, "src");
54
+ const plugins = await loadPlugins(await resolveProjectLexicons(src));
55
+ const serializers = plugins.map((p) => p.serializer).filter((s) => s.name === "k8s");
56
+ const output = join(project, "k8s.yaml");
57
+ const result = await buildCommand({ path: src, output, format: "yaml", serializers, plugins });
58
+ expect(result.success, result.errors.join("\n")).toBe(true);
59
+ return readFileSync(output, "utf-8");
60
+ }
61
+
62
+ describe("telemetry attribution in a k8s build (#3059)", () => {
63
+ test("inside a workspace the containers name the workspace, the member and the declaration", async () => {
64
+ const out = await build({ workspace: true });
65
+ expect(out).toContain("value: api");
66
+ expect(out).toContain("value: chant.workspace=acme,chant.member=svc,chant.decl=api");
67
+ });
68
+
69
+ test("telemetry.attribution false turns it off inside a workspace", async () => {
70
+ expect(await build({ workspace: true, attribution: false })).not.toContain("OTEL_");
71
+ });
72
+
73
+ test("outside a workspace nothing is stamped, and telemetry.attribution true opts in without workspace or member", async () => {
74
+ expect(await build({ workspace: false })).not.toContain("OTEL_");
75
+ const optedIn = await build({ workspace: false, attribution: true });
76
+ expect(optedIn).toContain("value: chant.decl=api");
77
+ expect(optedIn).not.toContain("chant.workspace");
78
+ });
79
+ });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Where a workload keeps its pod spec, and the release attributes a deploy
3
+ * writes onto it (#3059, #3061, ws-081).
4
+ *
5
+ * The build stamps each container of a workload with `OTEL_SERVICE_NAME` and
6
+ * `OTEL_RESOURCE_ATTRIBUTES` (the serializer), and with
7
+ * `CHANT_RELEASE_ATTRIBUTES` read through the downward API from the pod
8
+ * annotation `chant.intentius.io/release-attributes`, which
9
+ * `OTEL_RESOURCE_ATTRIBUTES` ends with as `$(CHANT_RELEASE_ATTRIBUTES)`. An
10
+ * absent annotation reads as empty, so the built manifest works as it is. A
11
+ * release deploy (`kubectl-apply` with a release on its context) sets the
12
+ * annotation on the pod template of each stamped workload in what it applies,
13
+ * leaving the committed manifest the same bytes.
14
+ *
15
+ * Kept free of the API client and the serializer so the capability module can
16
+ * import it without loading either.
17
+ */
18
+ import { RELEASE_ATTRIBUTES_ANNOTATION, RELEASE_ATTRIBUTES_VARIABLE } from "@intentius/chant/telemetry-attribution";
19
+
20
+ /** Where each workload kind keeps its pod spec. */
21
+ export const POD_SPEC_PATHS: Record<string, readonly string[]> = {
22
+ Pod: ["spec"],
23
+ Deployment: ["spec", "template", "spec"],
24
+ StatefulSet: ["spec", "template", "spec"],
25
+ DaemonSet: ["spec", "template", "spec"],
26
+ ReplicaSet: ["spec", "template", "spec"],
27
+ Job: ["spec", "template", "spec"],
28
+ CronJob: ["spec", "jobTemplate", "spec", "template", "spec"],
29
+ };
30
+
31
+ /** The core API groups those kinds live in; a CRD that reuses a kind name is not a workload. */
32
+ const WORKLOAD_API_VERSIONS = new Set(["v1", "apps/v1", "batch/v1"]);
33
+
34
+ type Obj = Record<string, unknown>;
35
+
36
+ function isObj(value: unknown): value is Obj {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+
40
+ function at(value: unknown, path: readonly string[]): unknown {
41
+ let cur = value;
42
+ for (const key of path) {
43
+ if (!isObj(cur)) return undefined;
44
+ cur = cur[key];
45
+ }
46
+ return cur;
47
+ }
48
+
49
+ /** A workload's pod spec, or undefined for anything else. */
50
+ export function podSpecOf(manifest: Obj): Obj | undefined {
51
+ const path = POD_SPEC_PATHS[manifest.kind as string];
52
+ if (!path || !WORKLOAD_API_VERSIONS.has(manifest.apiVersion as string)) return undefined;
53
+ const spec = at(manifest, path);
54
+ return isObj(spec) ? spec : undefined;
55
+ }
56
+
57
+ /** The env entry that reads the release attributes from the pod annotation. */
58
+ export function releaseAttributesEnv(): Obj {
59
+ return {
60
+ name: RELEASE_ATTRIBUTES_VARIABLE,
61
+ valueFrom: { fieldRef: { fieldPath: `metadata.annotations['${RELEASE_ATTRIBUTES_ANNOTATION}']` } },
62
+ };
63
+ }
64
+
65
+ /** True when some container of the workload reads the release attributes, i.e. the build stamped it. */
66
+ function readsRelease(podSpec: Obj): boolean {
67
+ const containers = podSpec.containers;
68
+ if (!Array.isArray(containers)) return false;
69
+ return containers.some(
70
+ (c) => isObj(c) && Array.isArray(c.env) && c.env.some((e) => isObj(e) && e.name === RELEASE_ATTRIBUTES_VARIABLE && isObj(e.valueFrom)),
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Set the release-attributes annotation on the pod template (or the Pod) of
76
+ * every stamped workload in `documents`, in place, and return how many it
77
+ * set. A workload the build did not stamp is left alone.
78
+ */
79
+ export function annotateRelease(documents: Obj[], suffix: string): number {
80
+ let count = 0;
81
+ for (const doc of documents) {
82
+ const podSpec = podSpecOf(doc);
83
+ if (!podSpec || !readsRelease(podSpec)) continue;
84
+ const path = POD_SPEC_PATHS[doc.kind as string]!;
85
+ const owner = path.length === 1 ? doc : at(doc, path.slice(0, -1));
86
+ if (!isObj(owner)) continue;
87
+ const metadata = isObj(owner.metadata) ? owner.metadata : {};
88
+ const annotations = isObj(metadata.annotations) ? metadata.annotations : {};
89
+ owner.metadata = { ...metadata, annotations: { ...annotations, [RELEASE_ATTRIBUTES_ANNOTATION]: suffix } };
90
+ count++;
91
+ }
92
+ return count;
93
+ }