@intentius/chant-lexicon-k8s 0.106.4 → 0.107.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 (116) hide show
  1. package/dist/codegen/naming.d.ts.map +1 -1
  2. package/dist/composites/catalog.d.ts.map +1 -1
  3. package/dist/composites/index.d.ts +2 -0
  4. package/dist/composites/index.d.ts.map +1 -1
  5. package/dist/composites/otel-collector-shape.d.ts +2 -0
  6. package/dist/composites/otel-collector-shape.d.ts.map +1 -1
  7. package/dist/composites/otel-operator-collector.d.ts +101 -0
  8. package/dist/composites/otel-operator-collector.d.ts.map +1 -0
  9. package/dist/crd/crd-sources.d.ts.map +1 -1
  10. package/dist/generated/index.d.d.ts +172 -2
  11. package/dist/generated/index.d.ts +301 -0
  12. package/dist/generated/index.d.ts.map +1 -1
  13. package/dist/group-namespace.d.ts.map +1 -1
  14. package/dist/import/embedded.d.ts +3 -0
  15. package/dist/import/embedded.d.ts.map +1 -1
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/integrity.json +16 -9
  19. package/dist/lint/audit-catalog.d.ts.map +1 -1
  20. package/dist/lint/post-synth/index.d.ts.map +1 -1
  21. package/dist/lint/post-synth/monitoring-selection-helpers.d.ts +55 -0
  22. package/dist/lint/post-synth/monitoring-selection-helpers.d.ts.map +1 -0
  23. package/dist/lint/post-synth/otel-placement-helpers.d.ts +16 -0
  24. package/dist/lint/post-synth/otel-placement-helpers.d.ts.map +1 -1
  25. package/dist/lint/post-synth/wk8604.d.ts +6 -0
  26. package/dist/lint/post-synth/wk8604.d.ts.map +1 -1
  27. package/dist/lint/post-synth/wk8605.d.ts.map +1 -1
  28. package/dist/lint/post-synth/wk8606.d.ts +17 -0
  29. package/dist/lint/post-synth/wk8606.d.ts.map +1 -0
  30. package/dist/lint/post-synth/wk8701.d.ts +17 -0
  31. package/dist/lint/post-synth/wk8701.d.ts.map +1 -0
  32. package/dist/lint/post-synth/wk8702.d.ts +17 -0
  33. package/dist/lint/post-synth/wk8702.d.ts.map +1 -0
  34. package/dist/lint/post-synth/wk8703.d.ts +17 -0
  35. package/dist/lint/post-synth/wk8703.d.ts.map +1 -0
  36. package/dist/lint/post-synth/wk8704.d.ts +21 -0
  37. package/dist/lint/post-synth/wk8704.d.ts.map +1 -0
  38. package/dist/lint/post-synth/wk8705.d.ts +18 -0
  39. package/dist/lint/post-synth/wk8705.d.ts.map +1 -0
  40. package/dist/manifest.json +1 -1
  41. package/dist/meta.json +2284 -370
  42. package/dist/okf/index.md +20 -1
  43. package/dist/okf/rules/WK8604.md +6 -2
  44. package/dist/okf/rules/WK8605.md +4 -0
  45. package/dist/okf/rules/WK8606.md +15 -0
  46. package/dist/okf/rules/WK8701.md +18 -0
  47. package/dist/okf/rules/WK8702.md +20 -0
  48. package/dist/okf/rules/WK8703.md +17 -0
  49. package/dist/okf/rules/WK8704.md +22 -0
  50. package/dist/okf/rules/WK8705.md +18 -0
  51. package/dist/okf/types/Alertmanager.md +18 -0
  52. package/dist/okf/types/AlertmanagerConfig.md +18 -0
  53. package/dist/okf/types/ClusterObservability.md +14 -0
  54. package/dist/okf/types/CronJob.md +1 -0
  55. package/dist/okf/types/DaemonSet.md +1 -0
  56. package/dist/okf/types/Instrumentation.md +14 -0
  57. package/dist/okf/types/MonitoringProbe.md +14 -0
  58. package/dist/okf/types/Namespace.md +3 -0
  59. package/dist/okf/types/OpAMPBridge.md +14 -0
  60. package/dist/okf/types/OpenTelemetryCollector.md +19 -0
  61. package/dist/okf/types/Pod.md +1 -0
  62. package/dist/okf/types/PodMonitor.md +20 -0
  63. package/dist/okf/types/Prometheus.md +21 -0
  64. package/dist/okf/types/PrometheusAgent.md +18 -0
  65. package/dist/okf/types/PrometheusRule.md +6 -1
  66. package/dist/okf/types/ScrapeConfig.md +19 -0
  67. package/dist/okf/types/Service.md +1 -0
  68. package/dist/okf/types/ServiceMonitor.md +7 -1
  69. package/dist/okf/types/StatefulSet.md +1 -0
  70. package/dist/okf/types/TargetAllocator.md +14 -0
  71. package/dist/okf/types/ThanosRuler.md +18 -0
  72. package/dist/rules/monitoring-selection-helpers.ts +185 -0
  73. package/dist/rules/otel-placement-helpers.ts +61 -1
  74. package/dist/rules/wk8601.ts +1 -1
  75. package/dist/rules/wk8603.ts +1 -1
  76. package/dist/rules/wk8604.ts +8 -2
  77. package/dist/rules/wk8605.ts +5 -3
  78. package/dist/rules/wk8606.ts +27 -0
  79. package/dist/rules/wk8701.ts +37 -0
  80. package/dist/rules/wk8702.ts +43 -0
  81. package/dist/rules/wk8703.ts +37 -0
  82. package/dist/rules/wk8704.ts +134 -0
  83. package/dist/rules/wk8705.ts +45 -0
  84. package/dist/types/index.d.ts +172 -2
  85. package/package.json +3 -3
  86. package/src/codegen/naming.ts +15 -1
  87. package/src/composites/catalog.ts +105 -0
  88. package/src/composites/index.ts +2 -0
  89. package/src/composites/otel-collector-shape.ts +2 -0
  90. package/src/composites/otel-operator-collector.test.ts +267 -0
  91. package/src/composites/otel-operator-collector.ts +221 -0
  92. package/src/crd/crd-sources.ts +41 -2
  93. package/src/generated/index.d.ts +172 -2
  94. package/src/generated/index.ts +303 -2
  95. package/src/generated/lexicon-k8s.json +2284 -370
  96. package/src/generated/operations.json +208 -0
  97. package/src/group-namespace.test.ts +4 -0
  98. package/src/group-namespace.ts +4 -0
  99. package/src/import/embedded.ts +26 -0
  100. package/src/import/operator-collector-roundtrip.test.ts +105 -0
  101. package/src/index.ts +2 -2
  102. package/src/lint/audit-catalog.ts +6 -0
  103. package/src/lint/post-synth/index.ts +12 -0
  104. package/src/lint/post-synth/monitoring-selection-helpers.ts +185 -0
  105. package/src/lint/post-synth/monitoring-selection.test.ts +316 -0
  106. package/src/lint/post-synth/otel-placement-helpers.ts +61 -1
  107. package/src/lint/post-synth/wk8601.ts +1 -1
  108. package/src/lint/post-synth/wk8603.ts +1 -1
  109. package/src/lint/post-synth/wk8604.ts +8 -2
  110. package/src/lint/post-synth/wk8605.ts +5 -3
  111. package/src/lint/post-synth/wk8606.ts +27 -0
  112. package/src/lint/post-synth/wk8701.ts +37 -0
  113. package/src/lint/post-synth/wk8702.ts +43 -0
  114. package/src/lint/post-synth/wk8703.ts +37 -0
  115. package/src/lint/post-synth/wk8704.ts +134 -0
  116. package/src/lint/post-synth/wk8705.ts +45 -0
@@ -0,0 +1,267 @@
1
+ /**
2
+ * OtelOperatorCollector (#3367): the OpenTelemetryCollector custom resource
3
+ * built from otel entities, and the checks that read it: WK8604 over
4
+ * `spec.config`, WK8601, WK8602, WK8603 and WK8605 over `spec.mode`,
5
+ * `spec.replicas`, `spec.env` and `spec.volumeMounts`.
6
+ */
7
+ import { describe, expect, test } from "vitest";
8
+ import { dump, loadAll } from "js-yaml";
9
+ import { expandComposite } from "@intentius/chant";
10
+ import type { Declarable } from "@intentius/chant/declarable";
11
+ import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
12
+ import { makePostSynthCtx } from "@intentius/chant-test-utils";
13
+ import {
14
+ DebugExporter,
15
+ FileLogReceiver,
16
+ K8sAttributesProcessor,
17
+ K8sClusterReceiver,
18
+ LoadBalancingExporter,
19
+ OtlpExporter,
20
+ OtlpReceiver,
21
+ Pipeline,
22
+ TailSamplingProcessor,
23
+ collectorConfig,
24
+ defineComponent,
25
+ type CollectorConfig,
26
+ } from "@intentius/chant-lexicon-otel";
27
+ import { k8sSerializer } from "../serializer";
28
+ import { OtelOperatorCollector } from "./otel-operator-collector";
29
+ import { OtelCollector } from "./otel-collector";
30
+ import { OTEL_COLLECTOR_ANNOTATIONS as A } from "./otel-collector-shape";
31
+ import { collectorPlacements } from "../lint/post-synth/otel-placement-helpers";
32
+ import { docsToManifests } from "../lint/post-synth/k8s-helpers";
33
+ import { wk8601 } from "../lint/post-synth/wk8601";
34
+ import { wk8602 } from "../lint/post-synth/wk8602";
35
+ import { wk8603 } from "../lint/post-synth/wk8603";
36
+ import { wk8604 } from "../lint/post-synth/wk8604";
37
+ import { wk8605 } from "../lint/post-synth/wk8605";
38
+
39
+ function p(member: unknown): any {
40
+ return (member as { props: unknown }).props;
41
+ }
42
+
43
+ function built(instances: Record<string, unknown>): PostSynthContext {
44
+ const entities = new Map<string, Declarable>();
45
+ for (const [name, instance] of Object.entries(instances)) {
46
+ for (const [k, v] of expandComposite(name, instance as never)) entities.set(k, v);
47
+ }
48
+ const out = k8sSerializer.serialize(entities);
49
+ return makePostSynthCtx("k8s", typeof out === "string" ? out : out.primary);
50
+ }
51
+
52
+ /** Hand-written manifests as a multi-document stream. */
53
+ const yaml = (...docs: object[]) => makePostSynthCtx("k8s", docs.map((d) => dump(d, { lineWidth: -1 })).join("---\n"));
54
+
55
+ const otlp = () => new OtlpReceiver({ protocols: { grpc: { endpoint: "0.0.0.0:4317" } } });
56
+ const tail = () =>
57
+ new TailSamplingProcessor({
58
+ decision_wait: "5s",
59
+ policies: [{ name: "errors", type: "status_code", status_code: { status_codes: ["ERROR"] } }],
60
+ });
61
+ const tracesTo = (...processors: Declarable[]) => [
62
+ new Pipeline({ signal: "traces", receivers: [otlp()], processors: processors as never, exporters: [new DebugExporter({})] }),
63
+ ];
64
+
65
+ function cr(name: string, spec: Record<string, unknown>, namespace = "obs"): object {
66
+ return { apiVersion: "opentelemetry.io/v1beta1", kind: "OpenTelemetryCollector", metadata: { name, namespace }, spec };
67
+ }
68
+
69
+ const PLAIN: CollectorConfig = {
70
+ receivers: { otlp: { protocols: { grpc: {} } } },
71
+ exporters: { debug: {} },
72
+ service: { pipelines: { traces: { receivers: ["otlp"], exporters: ["debug"] } } },
73
+ };
74
+
75
+ describe("OtelOperatorCollector", () => {
76
+ test("returns an OpenTelemetryCollector, a ServiceAccount, a ClusterRole and a ClusterRoleBinding", () => {
77
+ const c = OtelOperatorCollector({});
78
+ for (const key of ["collector", "serviceAccount", "clusterRole", "clusterRoleBinding"]) expect((c as any)[key], key).toBeDefined();
79
+ expect((c as any).configMap).toBeUndefined();
80
+ expect((c as any).daemonSet).toBeUndefined();
81
+ });
82
+
83
+ test("sets spec.config to the built config, an object, and spec.mode to the agent shape by default", () => {
84
+ const entities = tracesTo();
85
+ const c = OtelOperatorCollector({ config: entities });
86
+ const spec = p(c.collector).spec;
87
+ expect(spec.mode).toBe("daemonset");
88
+ expect(spec.config).toEqual(collectorConfig(entities));
89
+ expect(typeof spec.config).toBe("object");
90
+ expect(spec.serviceAccount).toBe("otel-collector-sa");
91
+ expect(p(c.collector).metadata).toMatchObject({ name: "otel-collector", namespace: "observability" });
92
+ });
93
+
94
+ test("renders opentelemetry.io/v1beta1 with the config as a YAML map", () => {
95
+ const docs = loadAll(
96
+ (() => {
97
+ const out = k8sSerializer.serialize(new Map(expandComposite("c", OtelOperatorCollector({ config: tracesTo() }) as never)));
98
+ return typeof out === "string" ? out : out.primary;
99
+ })(),
100
+ ) as Array<Record<string, any>>;
101
+ const doc = docs.find((d) => d.kind === "OpenTelemetryCollector")!;
102
+ expect(doc.apiVersion).toBe("opentelemetry.io/v1beta1");
103
+ expect(doc.spec.config.service.pipelines.traces.exporters).toEqual(["debug"]);
104
+ expect(doc.spec.config.receivers.otlp.protocols.grpc.endpoint).toBe("0.0.0.0:4317");
105
+ });
106
+
107
+ test("a deployment takes replicas; a daemonset refuses them", () => {
108
+ const d = OtelOperatorCollector({ mode: "deployment", replicas: 3 });
109
+ expect(p(d.collector).spec).toMatchObject({ mode: "deployment", replicas: 3 });
110
+ expect(p(d.collector).spec.tolerations).toBeUndefined();
111
+ expect(() => OtelOperatorCollector({ mode: "daemonset", replicas: 2 })).toThrow(/replicas does not apply/);
112
+ expect(p(OtelOperatorCollector({}).collector).spec.replicas).toBeUndefined();
113
+ });
114
+
115
+ test("ports are read back from the config, and the RBAC matches OtelCollector's", () => {
116
+ const config = [new Pipeline({ signal: "traces", receivers: [otlp()], processors: [new K8sAttributesProcessor({})], exporters: [new DebugExporter({})] })];
117
+ const c = OtelOperatorCollector({ config });
118
+ const agent = OtelCollector({ config });
119
+ expect(p(c.collector).spec.ports).toEqual([{ name: "otlp-grpc", port: 4317, protocol: "TCP" }]);
120
+ expect(p(c.clusterRole).rules).toEqual(p(agent.clusterRole).rules);
121
+ expect(p(c.clusterRoleBinding).subjects).toEqual([{ kind: "ServiceAccount", name: "otel-collector-sa", namespace: "observability" }]);
122
+ });
123
+
124
+ test("node access goes in spec.env, spec.volumes and spec.volumeMounts, and log group in spec.podSecurityContext", () => {
125
+ const config = [
126
+ new Pipeline({
127
+ signal: "logs",
128
+ receivers: [new FileLogReceiver({ include: ["/var/log/pods/*/*/*.log"] })],
129
+ processors: [new K8sAttributesProcessor({ filter: { node_from_env_var: "K8S_NODE_NAME" } })],
130
+ exporters: [new DebugExporter({})],
131
+ }),
132
+ ];
133
+ const spec = p(OtelOperatorCollector({ config }).collector).spec;
134
+ expect(spec.env).toEqual([{ name: "K8S_NODE_NAME", valueFrom: { fieldRef: { fieldPath: "spec.nodeName" } } }]);
135
+ expect(spec.volumes.map((v: any) => v.hostPath.path)).toContain("/var/log/pods");
136
+ expect(spec.volumeMounts.every((m: any) => m.readOnly === true)).toBe(true);
137
+ expect(spec.podSecurityContext).toEqual({ supplementalGroups: [0] });
138
+
139
+ const root = p(OtelOperatorCollector({ config, logAccess: "root" }).collector).spec;
140
+ expect(root.podSecurityContext).toBeUndefined();
141
+ expect(root.securityContext).toMatchObject({ runAsUser: 0, runAsNonRoot: false });
142
+ });
143
+
144
+ test("the # chant: header lines go in the otel.chant.dev/header annotation, one per line", () => {
145
+ const Mycorp = defineComponent<{ endpoint: string }>()({
146
+ kind: "receiver",
147
+ type: "mycorp",
148
+ pin: { source: "github.com/mycorp/otel", version: "v1.2.3" },
149
+ });
150
+ const config = [new Pipeline({ signal: "traces", receivers: [new Mycorp({ endpoint: "0.0.0.0:9999" })], exporters: [new DebugExporter({})] })];
151
+ const header = p(OtelOperatorCollector({ config }).collector).metadata.annotations[A.header] as string;
152
+ expect(header).toBe("chant: receiver mycorp schema github.com/mycorp/otel@v1.2.3");
153
+ // A config with no pins writes no annotation.
154
+ expect(p(OtelOperatorCollector({ config: tracesTo() }).collector).metadata.annotations[A.header]).toBeUndefined();
155
+ });
156
+ });
157
+
158
+ describe("WK8604 over an OpenTelemetryCollector's spec.config", () => {
159
+ test("passes what OtelOperatorCollector renders", () => {
160
+ expect(wk8604.check(built({ agent: OtelOperatorCollector({ config: tracesTo() }) }))).toEqual([]);
161
+ expect(wk8604.check(built({ gw: OtelOperatorCollector({ mode: "deployment", replicas: 2 }) }))).toEqual([]);
162
+ });
163
+
164
+ test("reports an undeclared exporter under OTEL101, naming the custom resource", () => {
165
+ const broken = { ...PLAIN, service: { pipelines: { traces: { receivers: ["otlp"], exporters: ["debug", "otlp/tempo"] } } } };
166
+ const diags = wk8604.check(yaml(cr("agent", { mode: "daemonset", config: broken })));
167
+ expect(diags).toHaveLength(1);
168
+ expect(diags[0]).toMatchObject({ checkId: "OTEL101", severity: "error", lexicon: "otel" });
169
+ expect(diags[0].message).toMatch(/^OpenTelemetryCollector obs\/agent, spec\.config: /);
170
+ expect(diags[0].message).toContain("otlp/tempo");
171
+ });
172
+
173
+ test("reads a v1alpha1 CR's config text", () => {
174
+ const text = dump({ ...PLAIN, service: { pipelines: { traces: { receivers: ["otlp"], exporters: ["debug", "nope"] } } } });
175
+ const doc = { apiVersion: "opentelemetry.io/v1alpha1", kind: "OpenTelemetryCollector", metadata: { name: "old" }, spec: { config: text } };
176
+ const diags = wk8604.check(yaml(doc));
177
+ expect(diags.map((d) => d.checkId)).toEqual(["OTEL101"]);
178
+ expect(diags[0].message).toMatch(/^OpenTelemetryCollector default\/old, spec\.config: /);
179
+ });
180
+
181
+ test("ignores another group's OpenTelemetryCollector and a CR without a pipelines map", () => {
182
+ expect(wk8604.check(yaml({ ...cr("x", { config: { exporters: ["a"] } }) }))).toEqual([]);
183
+ expect(wk8604.check(yaml({ ...(cr("x", { config: PLAIN }) as object), apiVersion: "example.com/v1" }))).toEqual([]);
184
+ });
185
+ });
186
+
187
+ describe("the placement checks over an OpenTelemetryCollector", () => {
188
+ test("a CR is joined as a workload: kind from spec.mode, replicas from spec.replicas, config from spec.config", () => {
189
+ const manifests = docsToManifests(
190
+ yaml(
191
+ cr("a", { mode: "daemonset", config: PLAIN }),
192
+ cr("b", { replicas: 4, config: PLAIN }),
193
+ cr("c", { mode: "statefulset", config: PLAIN, autoscaler: { maxReplicas: 6 } }),
194
+ cr("d", { mode: "sidecar", config: PLAIN }),
195
+ ),
196
+ );
197
+ const placements = collectorPlacements(manifests).map((x) => [x.name, x.kind, x.replicas, x.key]);
198
+ expect(placements).toEqual([
199
+ ["a", "DaemonSet", undefined, "spec.config"],
200
+ ["b", "Deployment", 4, "spec.config"],
201
+ ["c", "StatefulSet", 6, "spec.config"],
202
+ ]);
203
+ });
204
+
205
+ test("WK8601 reports tail_sampling in a daemonset CR, and not in a deployment CR", () => {
206
+ const agent = wk8601.check(built({ agent: OtelOperatorCollector({ config: tracesTo(tail()) }) }));
207
+ expect(agent).toHaveLength(1);
208
+ expect(agent[0].message).toContain("OpenTelemetryCollector observability/otel-collector (mode daemonset)");
209
+ expect(agent[0].message).toContain("spec.config");
210
+ expect(wk8601.check(built({ gw: OtelOperatorCollector({ mode: "deployment", config: tracesTo(tail()) }) }))).toEqual([]);
211
+ });
212
+
213
+ test("WK8602 reports a multi-replica gateway CR that a collector sends traces to through its Service without trace-aware routing", () => {
214
+ const gateway = OtelOperatorCollector({ name: "gw", mode: "deployment", replicas: 3, config: tracesTo(tail()) });
215
+ const sender = (exporter: Declarable) =>
216
+ OtelOperatorCollector({
217
+ name: "agent",
218
+ config: [new Pipeline({ signal: "traces", receivers: [otlp()], exporters: [exporter as never] })],
219
+ });
220
+
221
+ const direct = wk8602.check(built({ gateway, agent: sender(new OtlpExporter({ endpoint: "gw-collector.observability.svc:4317" })) }));
222
+ expect(direct).toHaveLength(1);
223
+ expect(direct[0].message).toContain("OpenTelemetryCollector observability/gw (mode deployment)");
224
+ expect(direct[0].message).toContain("sends to Service gw-collector.observability directly");
225
+
226
+ const balanced = new LoadBalancingExporter({
227
+ routing_key: "traceID",
228
+ protocol: { otlp: { tls: { insecure: true } } },
229
+ resolver: { dns: { hostname: "gw-collector-headless.observability.svc" } },
230
+ });
231
+ expect(wk8602.check(built({ gateway, agent: sender(balanced) }))).toEqual([]);
232
+
233
+ const single = OtelOperatorCollector({ name: "gw", mode: "deployment", replicas: 1, config: tracesTo(tail()) });
234
+ expect(wk8602.check(built({ gateway: single, agent: sender(new OtlpExporter({ endpoint: "gw-collector.observability.svc:4317" })) }))).toEqual([]);
235
+ });
236
+
237
+ test("WK8603 reports k8s_cluster on a daemonset or multi-replica CR, and not on one replica", () => {
238
+ const config = [new Pipeline({ signal: "metrics", receivers: [new K8sClusterReceiver({})], exporters: [new DebugExporter({})] })];
239
+ expect(wk8603.check(built({ a: OtelOperatorCollector({ config }) }))).toHaveLength(1);
240
+ expect(wk8603.check(built({ a: OtelOperatorCollector({ mode: "deployment", replicas: 2, config }) }))).toHaveLength(1);
241
+ expect(wk8603.check(built({ a: OtelOperatorCollector({ mode: "deployment", replicas: 1, config }) }))).toEqual([]);
242
+ });
243
+
244
+ test("WK8605 passes the node access the composite adds, and reports a hand-written CR without it", () => {
245
+ const config = [
246
+ new Pipeline({
247
+ signal: "logs",
248
+ receivers: [new FileLogReceiver({ include: ["/var/log/pods/*/*/*.log"] })],
249
+ processors: [new K8sAttributesProcessor({ filter: { node_from_env_var: "K8S_NODE_NAME" } })],
250
+ exporters: [new DebugExporter({})],
251
+ }),
252
+ ];
253
+ expect(wk8605.check(built({ a: OtelOperatorCollector({ config }) }))).toEqual([]);
254
+
255
+ const bare = collectorConfig(config);
256
+ const diags = wk8605.check(yaml(cr("bare", { mode: "daemonset", config: bare })));
257
+ expect(diags).toHaveLength(1);
258
+ expect(diags[0].message).toContain("no K8S_NODE_NAME variable");
259
+ expect(diags[0].message).toContain("/var/log/pods");
260
+ });
261
+ });
262
+
263
+ describe("annotation keys", () => {
264
+ test("header is one of OTEL_COLLECTOR_ANNOTATIONS", () => {
265
+ expect(A.header).toBe("otel.chant.dev/header");
266
+ });
267
+ });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * OtelOperatorCollector composite: an OpenTelemetry Collector run by the
3
+ * OpenTelemetry Operator, as an `OpenTelemetryCollector` custom resource
4
+ * (opentelemetry.io/v1beta1).
5
+ *
6
+ * `OtelCollector` builds the DaemonSet, ConfigMap and Service itself. Here the
7
+ * operator builds them from one custom resource, and the otel lexicon's
8
+ * config goes straight into `spec.config`, which v1beta1 declares as an
9
+ * object (`exporters`, `receivers` and `service` required). The ports, the
10
+ * node access (downward API variables, host mounts, log group) and the RBAC
11
+ * come from the same readers `OtelCollector` uses, so the two follow a config
12
+ * the same way.
13
+ *
14
+ * An object has no comment lines, so the `# chant:` header that carries
15
+ * custom-component pins and semconv use (see `buildCollectorConfig`) is kept
16
+ * in the `otel.chant.dev/header` annotation, one line per entry. `chant
17
+ * import` puts it back on top of the config when it reads the CR.
18
+ *
19
+ * The operator names the workload `<name>-collector` and, with
20
+ * `spec.serviceAccount` set as it is here, runs it as the ServiceAccount this
21
+ * composite makes. The ClusterRole is bound to that ServiceAccount.
22
+ */
23
+
24
+ import { Composite, mergeDefaults } from "@intentius/chant";
25
+ import type { Declarable } from "@intentius/chant/declarable";
26
+ import {
27
+ otlpCollector,
28
+ COLLECTOR_IMAGE,
29
+ type OTelComponent,
30
+ type Signal,
31
+ } from "@intentius/chant-lexicon-otel";
32
+ import { ServiceAccount, ClusterRole, ClusterRoleBinding, Role, RoleBinding, OpenTelemetryCollector } from "../generated";
33
+ import type { MemberDefaults } from "./member-defaults";
34
+ import type { CollectorLogAccess } from "./otel-collector-agent";
35
+ import { collectorNodeAccess, nodeVolumeMounts, nodeVolumes } from "./otel-collector-node";
36
+ import { agentClusterRules, namespacedRoles } from "./otel-collector-rbac";
37
+ import {
38
+ collectorRuntime,
39
+ gatewaysAnnotation,
40
+ gatewayTargetsOf,
41
+ k8sResolverNamespaces,
42
+ OTEL_COLLECTOR_ANNOTATIONS,
43
+ } from "./otel-collector-shape";
44
+
45
+ /** How the operator runs the collector. `sidecar` is left out: it injects into other pods, which this composite does not name. */
46
+ export type OtelOperatorMode = "daemonset" | "deployment" | "statefulset";
47
+
48
+ export interface OtelOperatorCollectorProps {
49
+ /** Custom resource name (default: "otel-collector"). The operator names the workload `<name>-collector`. */
50
+ name?: string;
51
+ /** Namespace (default: "observability"). */
52
+ namespace?: string;
53
+ /** How the operator runs it (default: "daemonset", the agent shape `OtelCollector` has). */
54
+ mode?: OtelOperatorMode;
55
+ /** Replica count for `deployment` and `statefulset` (left to the operator's default of 1 when unset). Not allowed for `daemonset`. */
56
+ replicas?: number;
57
+ /** Collector image (default: the contrib image at the otel lexicon's pinned collector version). */
58
+ image?: string;
59
+ /**
60
+ * The collector config, as otel lexicon entities (components and
61
+ * pipelines). Replaces the default config, and `exporters` and `signals`
62
+ * are then ignored.
63
+ */
64
+ config?: Iterable<Declarable>;
65
+ /** Exporters for the default config (default: one `debug` exporter). */
66
+ exporters?: OTelComponent<"exporter", string, any>[];
67
+ /** Signals the default config has pipelines for (default: traces, metrics and logs). */
68
+ signals?: Signal[];
69
+ /** Additional labels. */
70
+ labels?: Record<string, string>;
71
+ /** How a config with a `filelog` receiver reads the node's container logs; see `OtelCollector`. Ignored for a config that reads no logs from the node. */
72
+ logAccess?: CollectorLogAccess;
73
+ /** CPU request (default: "100m"). */
74
+ cpuRequest?: string;
75
+ /** Memory request (default: "256Mi"). */
76
+ memoryRequest?: string;
77
+ /** CPU limit (default: "500m"). */
78
+ cpuLimit?: string;
79
+ /** Memory limit (default: "512Mi"). */
80
+ memoryLimit?: string;
81
+ /** Per-member defaults for fine-grained overrides. */
82
+ defaults?: {
83
+ collector?: MemberDefaults<"OpenTelemetryCollector">;
84
+ serviceAccount?: MemberDefaults<"ServiceAccount">;
85
+ clusterRole?: MemberDefaults<"ClusterRole">;
86
+ clusterRoleBinding?: MemberDefaults<"ClusterRoleBinding">;
87
+ endpointsRole?: MemberDefaults<"Role">;
88
+ endpointsRoleBinding?: MemberDefaults<"RoleBinding">;
89
+ };
90
+ }
91
+
92
+ export type OtelOperatorCollectorResult = {
93
+ collector: InstanceType<typeof OpenTelemetryCollector>;
94
+ serviceAccount: InstanceType<typeof ServiceAccount>;
95
+ clusterRole: InstanceType<typeof ClusterRole>;
96
+ clusterRoleBinding: InstanceType<typeof ClusterRoleBinding>;
97
+ /** Read access to Endpoints for a `loadbalancing` exporter's `k8s` resolver, as in `OtelCollectorResult`. */
98
+ endpointsRole?: InstanceType<typeof Role>;
99
+ endpointsRoleBinding?: InstanceType<typeof RoleBinding>;
100
+ [member: `endpointsRoleIn${string}`]: InstanceType<typeof Role>;
101
+ [member: `endpointsRoleBindingIn${string}`]: InstanceType<typeof RoleBinding>;
102
+ };
103
+
104
+ /**
105
+ * Create an OtelOperatorCollector composite. Returns an OpenTelemetryCollector
106
+ * custom resource, a ServiceAccount, a ClusterRole and a ClusterRoleBinding.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { OtelOperatorCollector } from "@intentius/chant-lexicon-k8s";
111
+ * import { OtlpExporter } from "@intentius/chant-lexicon-otel";
112
+ *
113
+ * export const collector = OtelOperatorCollector({
114
+ * mode: "deployment",
115
+ * replicas: 2,
116
+ * exporters: [new OtlpExporter({ endpoint: "tempo.observability.svc:4317", tls: { insecure: true } })],
117
+ * });
118
+ * ```
119
+ */
120
+ export const OtelOperatorCollector = Composite((props: OtelOperatorCollectorProps) => {
121
+ const {
122
+ name = "otel-collector",
123
+ namespace = "observability",
124
+ mode = "daemonset",
125
+ image = COLLECTOR_IMAGE,
126
+ labels: extraLabels = {},
127
+ logAccess = "group",
128
+ cpuRequest = "100m",
129
+ memoryRequest = "256Mi",
130
+ cpuLimit = "500m",
131
+ memoryLimit = "512Mi",
132
+ defaults: defs,
133
+ } = props;
134
+
135
+ if (mode === "daemonset" && props.replicas !== undefined) {
136
+ throw new Error(`${name}: a daemonset runs one collector per node, so replicas does not apply`);
137
+ }
138
+
139
+ const commonLabels: Record<string, string> = {
140
+ "app.kubernetes.io/name": name,
141
+ "app.kubernetes.io/managed-by": "chant",
142
+ ...extraLabels,
143
+ };
144
+
145
+ const entities = props.config ? [...props.config] : otlpCollector({ exporters: props.exporters, signals: props.signals });
146
+ const runtime = collectorRuntime(entities);
147
+ const gateways = gatewayTargetsOf(runtime.built);
148
+ const saName = `${name}-sa`;
149
+
150
+ const access = collectorNodeAccess(runtime.built.config, runtime.configDir);
151
+ const asRoot = access.readsLogs && logAccess === "root";
152
+ const container = runtime.containerExtra.securityContext as Record<string, unknown>;
153
+
154
+ const annotations: Record<string, string> = {
155
+ [OTEL_COLLECTOR_ANNOTATIONS.role]: mode === "daemonset" ? "agent" : "gateway",
156
+ ...(gateways.length ? { [OTEL_COLLECTOR_ANNOTATIONS.gateways]: gatewaysAnnotation(gateways) } : {}),
157
+ ...(runtime.built.header.length ? { [OTEL_COLLECTOR_ANNOTATIONS.header]: runtime.built.header.join("\n") } : {}),
158
+ };
159
+
160
+ const collector = new OpenTelemetryCollector(mergeDefaults({
161
+ metadata: {
162
+ name,
163
+ namespace,
164
+ labels: { ...commonLabels, "app.kubernetes.io/component": mode === "daemonset" ? "agent" : "gateway" },
165
+ annotations,
166
+ },
167
+ spec: {
168
+ mode,
169
+ ...(props.replicas !== undefined ? { replicas: props.replicas } : {}),
170
+ image,
171
+ serviceAccount: saName,
172
+ config: runtime.built.config,
173
+ ports: runtime.servicePorts.map((p) => ({ name: p.name, port: p.port, protocol: p.protocol ?? "TCP" })),
174
+ resources: {
175
+ requests: { cpu: cpuRequest, memory: memoryRequest },
176
+ limits: { cpu: cpuLimit, memory: memoryLimit },
177
+ },
178
+ securityContext: asRoot ? { ...container, runAsNonRoot: false, runAsUser: 0 } : container,
179
+ ...(access.readsLogs && !asRoot ? { podSecurityContext: { supplementalGroups: [0] } } : {}),
180
+ ...(access.env.length ? { env: access.env } : {}),
181
+ ...(access.mounts.length ? { volumes: nodeVolumes(access.mounts), volumeMounts: nodeVolumeMounts(access.mounts) } : {}),
182
+ ...(mode === "daemonset" ? { tolerations: [{ operator: "Exists" }] } : {}),
183
+ },
184
+ }, defs?.collector));
185
+
186
+ const serviceAccount = new ServiceAccount(mergeDefaults({
187
+ metadata: {
188
+ name: saName,
189
+ namespace,
190
+ labels: { ...commonLabels, "app.kubernetes.io/component": "rbac" },
191
+ },
192
+ }, defs?.serviceAccount));
193
+
194
+ const clusterRoleName = `${name}-role`;
195
+ const clusterRole = new ClusterRole(mergeDefaults({
196
+ metadata: { name: clusterRoleName, labels: { ...commonLabels, "app.kubernetes.io/component": "rbac" } },
197
+ rules: agentClusterRules(runtime.built.config),
198
+ }, defs?.clusterRole));
199
+
200
+ const clusterRoleBinding = new ClusterRoleBinding(mergeDefaults({
201
+ metadata: { name: `${name}-binding`, labels: { ...commonLabels, "app.kubernetes.io/component": "rbac" } },
202
+ roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "ClusterRole", name: clusterRoleName },
203
+ subjects: [{ kind: "ServiceAccount", name: saName, namespace }],
204
+ }, defs?.clusterRoleBinding));
205
+
206
+ const endpointsRbac = namespacedRoles({
207
+ key: "endpoints",
208
+ name: `${name}-endpoints`,
209
+ namespaces: k8sResolverNamespaces(runtime.built, namespace),
210
+ rules: [
211
+ { apiGroups: [""], resources: ["endpoints"], verbs: ["get", "list", "watch"] },
212
+ { apiGroups: ["discovery.k8s.io"], resources: ["endpointslices"], verbs: ["get", "list", "watch"] },
213
+ ],
214
+ labels: { ...commonLabels, "app.kubernetes.io/component": "rbac" },
215
+ serviceAccount: { name: saName, namespace },
216
+ roleDefaults: defs?.endpointsRole,
217
+ roleBindingDefaults: defs?.endpointsRoleBinding,
218
+ });
219
+
220
+ return { collector, serviceAccount, clusterRole, clusterRoleBinding, ...endpointsRbac } as OtelOperatorCollectorResult;
221
+ }, "OtelOperatorCollector");
@@ -199,17 +199,24 @@ const INFISICAL_OPERATOR_VERSION = "infisical-k8-operator/v0.11.7";
199
199
  const INFISICAL_CRD_BASE = `https://raw.githubusercontent.com/Infisical/kubernetes-operator/${INFISICAL_OPERATOR_VERSION}/config/crd/bases`;
200
200
 
201
201
  /**
202
- * Prometheus Operator CRDs — monitoring.coreos.com/v1
202
+ * Prometheus Operator CRDs — monitoring.coreos.com/v1 and v1alpha1
203
203
  *
204
204
  * Produces (the `monitoring.coreos.com` group maps to the `Monitoring`
205
205
  * namespace):
206
206
  * K8s::Monitoring::ServiceMonitor → apiVersion: monitoring.coreos.com/v1, kind: ServiceMonitor
207
207
  * K8s::Monitoring::PrometheusRule → apiVersion: monitoring.coreos.com/v1, kind: PrometheusRule
208
+ * K8s::Monitoring::Prometheus / Alertmanager / PodMonitor / Probe / ThanosRuler
209
+ * → apiVersion: monitoring.coreos.com/v1
210
+ * K8s::Monitoring::PrometheusAgent / AlertmanagerConfig / ScrapeConfig
211
+ * → apiVersion: monitoring.coreos.com/v1alpha1
212
+ *
213
+ * `Probe` is also the core container probe property type, so the CRD class is
214
+ * `MonitoringProbe` (priorityNames in codegen/naming.ts).
208
215
  *
209
216
  * Operator install: kube-prometheus-stack chart, or
210
217
  * https://github.com/prometheus-operator/prometheus-operator
211
218
  */
212
- const PROM_OPERATOR_VERSION = "v0.79.2";
219
+ const PROM_OPERATOR_VERSION = "v0.94.1";
213
220
  const PROM_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/${PROM_OPERATOR_VERSION}/example/prometheus-operator-crd`;
214
221
 
215
222
  /**
@@ -503,6 +510,25 @@ const ACK_EKS_CRD_BASE = `https://raw.githubusercontent.com/aws-controllers-k8s/
503
510
  const GRAFANA_OPERATOR_VERSION = "v5.25.0";
504
511
  const GRAFANA_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/grafana/grafana-operator/${GRAFANA_OPERATOR_VERSION}/config/crd/bases`;
505
512
 
513
+ /**
514
+ * OpenTelemetry Operator CRDs — opentelemetry.io (#3367)
515
+ *
516
+ * The `opentelemetry.io` group is mapped to the `OpenTelemetry` namespace (see
517
+ * GROUP_NAMESPACE_OVERRIDES in group-namespace.ts). Each CRD is generated at
518
+ * its storage version:
519
+ * K8s::OpenTelemetry::OpenTelemetryCollector → opentelemetry.io/v1beta1 (spec.config is a structured object)
520
+ * K8s::OpenTelemetry::Instrumentation → opentelemetry.io/v1alpha1
521
+ * K8s::OpenTelemetry::TargetAllocator → opentelemetry.io/v1alpha1
522
+ * K8s::OpenTelemetry::OpAMPBridge → opentelemetry.io/v1alpha1
523
+ * K8s::OpenTelemetry::ClusterObservability → opentelemetry.io/v1alpha1 (new in v0.160.0: one CR that
524
+ * sets up the operator's collectors and instrumentation cluster-wide)
525
+ *
526
+ * Operator install: kubectl apply -f
527
+ * https://github.com/open-telemetry/opentelemetry-operator/releases/download/v0.160.0/opentelemetry-operator.yaml
528
+ */
529
+ const OTEL_OPERATOR_VERSION = "v0.160.0";
530
+ const OTEL_OPERATOR_CRD_BASE = `https://raw.githubusercontent.com/open-telemetry/opentelemetry-operator/${OTEL_OPERATOR_VERSION}/config/crd/bases`;
531
+
506
532
  export const CRD_SOURCES: CRDSource[] = [
507
533
  { type: "url", url: `${KUBERAY_CRD_BASE}/ray.io_rayclusters.yaml` },
508
534
  { type: "url", url: `${KUBERAY_CRD_BASE}/ray.io_rayjobs.yaml` },
@@ -519,6 +545,14 @@ export const CRD_SOURCES: CRDSource[] = [
519
545
  { type: "url", url: CERT_MANAGER_CRD_BUNDLE },
520
546
  { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_servicemonitors.yaml` },
521
547
  { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheusrules.yaml` },
548
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheuses.yaml` },
549
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_alertmanagers.yaml` },
550
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_podmonitors.yaml` },
551
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_probes.yaml` },
552
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_thanosrulers.yaml` },
553
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_prometheusagents.yaml` },
554
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_alertmanagerconfigs.yaml` },
555
+ { type: "url", url: `${PROM_OPERATOR_CRD_BASE}/monitoring.coreos.com_scrapeconfigs.yaml` },
522
556
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_clusters.yaml` },
523
557
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_scheduledbackups.yaml` },
524
558
  { type: "url", url: `${CNPG_CRD_BASE}/postgresql.cnpg.io_backups.yaml` },
@@ -598,4 +632,9 @@ export const CRD_SOURCES: CRDSource[] = [
598
632
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafananotificationpolicyroutes.yaml` },
599
633
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanamutetimings.yaml` },
600
634
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafananotificationtemplates.yaml` },
635
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_opentelemetrycollectors.yaml` },
636
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_instrumentations.yaml` },
637
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_targetallocators.yaml` },
638
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_opampbridges.yaml` },
639
+ { type: "url", url: `${OTEL_OPERATOR_CRD_BASE}/opentelemetry.io_clusterobservabilities.yaml` },
601
640
  ];