@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,185 @@
1
+ /**
2
+ * Shared plumbing for the Prometheus Operator selection checks (WK8701-WK8705).
3
+ *
4
+ * An operator accepts a PrometheusRule, monitor or AlertmanagerConfig that no
5
+ * Prometheus or Alertmanager selects and then ignores it without an error.
6
+ * These helpers decide, from the manifests in one build, whether a selector
7
+ * picks an object, following the operator's rules for a label selector:
8
+ *
9
+ * - an object selector that is null (or absent) matches nothing, `{}` matches all;
10
+ * - a namespace selector that is null (or absent) matches only the selecting
11
+ * resource's own namespace, `{}` matches every namespace.
12
+ *
13
+ * Namespace labels come from the Namespace manifests in the build, plus the
14
+ * `kubernetes.io/metadata.name` label every namespace carries. A selector on a
15
+ * label the build cannot know (the namespace is not declared in it) answers
16
+ * "unknown", and the checks stay silent on "unknown".
17
+ */
18
+
19
+ import { docsToManifests, type K8sManifest } from "./k8s-helpers";
20
+ import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
21
+
22
+ export const MONITORING_GROUP = "monitoring.coreos.com/";
23
+
24
+ export type Match = "yes" | "no" | "unknown";
25
+
26
+ function isRecord(v: unknown): v is Record<string, unknown> {
27
+ return typeof v === "object" && v !== null && !Array.isArray(v);
28
+ }
29
+
30
+ /** A manifest of a monitoring.coreos.com kind, whatever the version. */
31
+ export function ofMonitoringKind(m: K8sManifest, kind: string): boolean {
32
+ return m.kind === kind && typeof m.apiVersion === "string" && m.apiVersion.startsWith(MONITORING_GROUP);
33
+ }
34
+
35
+ export function monitoringKind(manifests: K8sManifest[], kind: string): K8sManifest[] {
36
+ return manifests.filter((m) => ofMonitoringKind(m, kind));
37
+ }
38
+
39
+ export function namespaceOf(m: K8sManifest): string {
40
+ return typeof m.metadata?.namespace === "string" && m.metadata.namespace !== "" ? m.metadata.namespace : "default";
41
+ }
42
+
43
+ export function nameOf(m: K8sManifest): string {
44
+ return typeof m.metadata?.name === "string" ? m.metadata.name : "";
45
+ }
46
+
47
+ export function describe(m: K8sManifest): string {
48
+ return `${m.kind} ${namespaceOf(m)}/${nameOf(m)}`;
49
+ }
50
+
51
+ /**
52
+ * Whether a label selector matches a label set. Null, undefined and anything
53
+ * that is not an object match nothing; `{}` matches everything.
54
+ * `unknownKeys` are label keys the caller cannot read (a namespace the build
55
+ * does not declare); a requirement on one answers "unknown".
56
+ */
57
+ export function matchLabelSelector(selector: unknown, labels: Record<string, string>, unknownKeys: ReadonlySet<string> = new Set()): Match {
58
+ if (!isRecord(selector)) return "no";
59
+ let unknown = false;
60
+ const matchLabels = isRecord(selector.matchLabels) ? selector.matchLabels : {};
61
+ for (const [k, v] of Object.entries(matchLabels)) {
62
+ if (unknownKeys.has(k)) {
63
+ unknown = true;
64
+ } else if (labels[k] !== String(v)) {
65
+ return "no";
66
+ }
67
+ }
68
+ const exprs = Array.isArray(selector.matchExpressions) ? selector.matchExpressions : [];
69
+ for (const e of exprs) {
70
+ if (!isRecord(e) || typeof e.key !== "string") continue;
71
+ if (unknownKeys.has(e.key)) {
72
+ unknown = true;
73
+ continue;
74
+ }
75
+ const values = Array.isArray(e.values) ? e.values.map(String) : [];
76
+ const has = Object.prototype.hasOwnProperty.call(labels, e.key);
77
+ switch (e.operator) {
78
+ case "In":
79
+ if (!has || !values.includes(labels[e.key])) return "no";
80
+ break;
81
+ case "NotIn":
82
+ if (has && values.includes(labels[e.key])) return "no";
83
+ break;
84
+ case "Exists":
85
+ if (!has) return "no";
86
+ break;
87
+ case "DoesNotExist":
88
+ if (has) return "no";
89
+ break;
90
+ }
91
+ }
92
+ return unknown ? "unknown" : "yes";
93
+ }
94
+
95
+ export function labelsOf(m: K8sManifest): Record<string, string> {
96
+ const out: Record<string, string> = {};
97
+ const labels = m.metadata?.labels;
98
+ if (isRecord(labels)) for (const [k, v] of Object.entries(labels)) out[k] = String(v);
99
+ return out;
100
+ }
101
+
102
+ /** The namespaces a build declares, with their labels. */
103
+ function declaredNamespaces(manifests: K8sManifest[]): Map<string, Record<string, string>> {
104
+ const out = new Map<string, Record<string, string>>();
105
+ for (const m of manifests) {
106
+ if (m.kind === "Namespace" && (m.apiVersion === "v1" || m.apiVersion === undefined) && nameOf(m)) {
107
+ out.set(nameOf(m), { ...labelsOf(m), "kubernetes.io/metadata.name": nameOf(m) });
108
+ }
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /**
114
+ * Whether a selecting resource's namespace selector picks `targetNamespace`.
115
+ * Null or absent: the selecting resource's own namespace only.
116
+ */
117
+ export function matchNamespaceSelector(
118
+ selector: unknown,
119
+ ownNamespace: string,
120
+ targetNamespace: string,
121
+ namespaces: Map<string, Record<string, string>>,
122
+ ): Match {
123
+ if (!isRecord(selector)) return ownNamespace === targetNamespace ? "yes" : "no";
124
+ const declared = namespaces.get(targetNamespace);
125
+ const labels = declared ?? { "kubernetes.io/metadata.name": targetNamespace };
126
+ // A namespace the build does not declare has labels the build cannot know, except the name label.
127
+ const unknownKeys = new Set<string>();
128
+ if (!declared) {
129
+ const keys = [
130
+ ...Object.keys(isRecord(selector.matchLabels) ? selector.matchLabels : {}),
131
+ ...(Array.isArray(selector.matchExpressions) ? selector.matchExpressions : []).map((e) => (isRecord(e) ? String(e.key) : "")),
132
+ ];
133
+ for (const k of keys) if (k !== "kubernetes.io/metadata.name") unknownKeys.add(k);
134
+ }
135
+ return matchLabelSelector(selector, labels, unknownKeys);
136
+ }
137
+
138
+ /** A selecting resource's reach over one object: its object selector, then its namespace selector. */
139
+ export function selects(
140
+ selector: unknown,
141
+ namespaceSelector: unknown,
142
+ selecting: K8sManifest,
143
+ object: K8sManifest,
144
+ namespaces: Map<string, Record<string, string>>,
145
+ ): Match {
146
+ const ns = matchNamespaceSelector(namespaceSelector, namespaceOf(selecting), namespaceOf(object), namespaces);
147
+ if (ns === "no") return "no";
148
+ const obj = matchLabelSelector(selector, labelsOf(object));
149
+ if (obj === "no") return "no";
150
+ return ns === "unknown" || obj === "unknown" ? "unknown" : "yes";
151
+ }
152
+
153
+ export interface SelectionContext {
154
+ manifests: K8sManifest[];
155
+ namespaces: Map<string, Record<string, string>>;
156
+ }
157
+
158
+ export function selectionContext(ctx: PostSynthContext): SelectionContext {
159
+ const manifests = docsToManifests(ctx);
160
+ return { manifests, namespaces: declaredNamespaces(manifests) };
161
+ }
162
+
163
+ /**
164
+ * Objects of `kinds` that no resource in `selectors` selects, by the named
165
+ * object selector and namespace selector fields of each selector's spec.
166
+ * Silent (empty) when `selectors` is empty, since the stack is often installed
167
+ * separately. A selector that answers "unknown" counts as selecting.
168
+ */
169
+ export function unselected(
170
+ sc: SelectionContext,
171
+ objects: K8sManifest[],
172
+ selectors: K8sManifest[],
173
+ fields: (selecting: K8sManifest, object: K8sManifest) => [string, string] | null,
174
+ ): K8sManifest[] {
175
+ if (selectors.length === 0) return [];
176
+ return objects.filter((object) => {
177
+ for (const sel of selectors) {
178
+ const f = fields(sel, object);
179
+ if (!f) continue;
180
+ const spec = (sel.spec ?? {}) as Record<string, unknown>;
181
+ if (selects(spec[f[0]], spec[f[1]], sel, object, sc.namespaces) !== "no") return false;
182
+ }
183
+ return true;
184
+ });
185
+ }
@@ -15,6 +15,13 @@
15
15
  * When a container passes `--config=<path>`, only keys named by those
16
16
  * paths count.
17
17
  *
18
+ * 3. An OpenTelemetry Operator `OpenTelemetryCollector` carries its config in
19
+ * `spec.config` (an object in v1beta1, a YAML string in v1alpha1) and its
20
+ * placement in `spec.mode` and `spec.replicas`; it is its own workload. A
21
+ * `sidecar` runs inside other pods and is left out. The Services the
22
+ * operator makes (`<name>-collector`, `<name>-collector-headless`) are not
23
+ * in the build, so \`servicesSelecting\` names them from the CR.
24
+ *
18
25
  * Anything this can't resolve (a ConfigMap or workload outside the build, a
19
26
  * replica count that isn't a number) is left out, so the checks stay silent
20
27
  * rather than guess. Like every bundle-join check they see one build root at
@@ -33,6 +40,7 @@ export const PLACEMENT_ANNOTATIONS = {
33
40
  workload: "otel.chant.dev/workload",
34
41
  config: "otel.chant.dev/config",
35
42
  gateways: "otel.chant.dev/gateways",
43
+ header: "otel.chant.dev/header",
36
44
  } as const;
37
45
 
38
46
  /** The part of a collector config the placement checks read. */
@@ -59,13 +67,51 @@ export interface CollectorPlacement {
59
67
  * Undefined for a DaemonSet, or when the count isn't a number.
60
68
  */
61
69
  replicas: number | undefined;
70
+ /** The ConfigMap holding the config; the CR's own name for an `OpenTelemetryCollector`. */
62
71
  configMap: string;
72
+ /** The data key holding the config; `spec.config` for an `OpenTelemetryCollector`. */
63
73
  key: string;
64
74
  config: CollectorConfigShape;
75
+ /** Where the config is, for messages: `ConfigMap observability/x, config.yaml` or `spec.config`. */
76
+ where: string;
77
+ /** The workload is an OpenTelemetry Operator `OpenTelemetryCollector`, which the operator turns into the pods. */
78
+ operatorCR?: true;
65
79
  }
66
80
 
67
81
  const PLACED_KINDS = new Set(["DaemonSet", "Deployment", "StatefulSet"]);
68
82
 
83
+ const OTEL_OPERATOR_KINDS = { daemonset: "DaemonSet", deployment: "Deployment", statefulset: "StatefulSet" } as const;
84
+
85
+ /** An OpenTelemetry Operator `OpenTelemetryCollector` (any version of `opentelemetry.io`). */
86
+ export function isOperatorCollector(m: K8sManifest): boolean {
87
+ return m.kind === "OpenTelemetryCollector" && typeof m.apiVersion === "string" && m.apiVersion.startsWith("opentelemetry.io/");
88
+ }
89
+
90
+ /** The placement of one `OpenTelemetryCollector`, or undefined for a sidecar, a missing name or a config that isn't one. */
91
+ function operatorPlacement(cr: K8sManifest): CollectorPlacement | undefined {
92
+ const name = cr.metadata?.name;
93
+ if (typeof name !== "string") return undefined;
94
+ const mode = cr.spec?.mode === undefined || cr.spec.mode === null ? "deployment" : cr.spec.mode;
95
+ if (typeof mode !== "string" || !(mode in OTEL_OPERATOR_KINDS)) return undefined;
96
+ const kind = OTEL_OPERATOR_KINDS[mode as keyof typeof OTEL_OPERATOR_KINDS];
97
+
98
+ // v1beta1 holds the config as an object, v1alpha1 as YAML text.
99
+ const raw = cr.spec?.config;
100
+ const config = isRecord(raw)
101
+ ? (parseCollectorConfig(JSON.stringify(raw)) as CollectorConfigShape | undefined)
102
+ : parseCollectorConfig(raw);
103
+ if (!config) return undefined;
104
+
105
+ let replicas: number | undefined;
106
+ if (kind !== "DaemonSet") {
107
+ const r = cr.spec?.replicas;
108
+ const base = r === undefined || r === null ? 1 : typeof r === "number" ? r : undefined;
109
+ const auto = isRecord(cr.spec?.autoscaler) ? cr.spec.autoscaler.maxReplicas : undefined;
110
+ replicas = base === undefined ? undefined : Math.max(base, typeof auto === "number" ? auto : 0);
111
+ }
112
+ return { workload: cr, kind, name, namespace: ns(cr), replicas, configMap: name, key: "spec.config", config, where: "spec.config", operatorCR: true };
113
+ }
114
+
69
115
  function ns(m: K8sManifest): string {
70
116
  const n = m.metadata?.namespace;
71
117
  return typeof n === "string" && n.length > 0 ? n : "default";
@@ -212,15 +258,21 @@ export function collectorPlacements(manifests: K8sManifest[]): CollectorPlacemen
212
258
  }
213
259
  const named = parsed.filter(([key]) => argNames.includes(key));
214
260
  for (const [key, config] of named.length > 0 ? named : parsed) {
215
- out.push({ workload, kind, name, namespace, replicas, configMap, key, config });
261
+ out.push({ workload, kind, name, namespace, replicas, configMap, key, config, where: `ConfigMap ${configMap}, ${key}` });
216
262
  }
217
263
  }
218
264
  }
265
+ for (const m of manifests) {
266
+ if (!isOperatorCollector(m)) continue;
267
+ const p = operatorPlacement(m);
268
+ if (p) out.push(p);
269
+ }
219
270
  return out;
220
271
  }
221
272
 
222
273
  /** How a placement is described in a message: `DaemonSet observability/otel-agent`. */
223
274
  export function describePlacement(p: CollectorPlacement): string {
275
+ if (p.operatorCR) return `OpenTelemetryCollector ${p.namespace}/${p.name} (mode ${p.kind.toLowerCase()})`;
224
276
  return `${p.kind} ${p.namespace}/${p.name}`;
225
277
  }
226
278
 
@@ -235,6 +287,14 @@ export interface SelectingService {
235
287
 
236
288
  /** The Services in a workload's namespace whose selector matches its pod template labels. */
237
289
  export function servicesSelecting(manifests: K8sManifest[], workload: K8sManifest): SelectingService[] {
290
+ // The operator's Services for a CR are not in the build; their names are fixed by the operator.
291
+ if (isOperatorCollector(workload) && typeof workload.metadata?.name === "string") {
292
+ const name = workload.metadata.name;
293
+ return [
294
+ { name: `${name}-collector`, namespace: ns(workload), headless: false },
295
+ { name: `${name}-collector-headless`, namespace: ns(workload), headless: true },
296
+ ];
297
+ }
238
298
  const template = isRecord(workload.spec?.template) ? workload.spec.template : undefined;
239
299
  const labels = isRecord(template?.metadata) && isRecord(template.metadata.labels) ? template.metadata.labels : {};
240
300
  const out: SelectingService[] = [];
@@ -32,7 +32,7 @@ export const wk8601: PostSynthCheck = {
32
32
  checkId: "WK8601",
33
33
  severity: "warning",
34
34
  message:
35
- `${describePlacement(p)} runs ${ids.join(", ")} (ConfigMap ${p.configMap}, ${p.key}) on every node. ` +
35
+ `${describePlacement(p)} runs ${ids.join(", ")} (${p.where}) on every node. ` +
36
36
  `Each agent sees only its own node's spans, so sampling decisions are made on partial traces. ` +
37
37
  `Move tail sampling to a gateway (OtelCollectorGateway) and send traces to it through a loadbalancing exporter routed by traceID.`,
38
38
  entity: p.name,
@@ -54,7 +54,7 @@ export const wk8603: PostSynthCheck = {
54
54
  checkId: "WK8603",
55
55
  severity: "warning",
56
56
  message:
57
- `${describePlacement(p)} runs the k8s_cluster receiver on ${copies} (ConfigMap ${p.configMap}, ${p.key}): ${reasons.join("; ")}. ` +
57
+ `${describePlacement(p)} runs the k8s_cluster receiver on ${copies} (${p.where}): ${reasons.join("; ")}. ` +
58
58
  `Each copy reports every cluster object, duplicating series and API server watches. ` +
59
59
  `Run it in a single-replica Deployment, or reference a k8s_leader_elector extension from the receiver and enable it in service.extensions.`,
60
60
  entity: p.name,
@@ -10,6 +10,12 @@
10
10
  * otel lexicon's `validateCollectorConfig`, and through `attributionIssues`
11
11
  * (OTEL118) when the build stamps telemetry attribution.
12
12
  *
13
+ * An OpenTelemetry Operator `OpenTelemetryCollector` carries its config in
14
+ * `spec.config` (an object in v1beta1, YAML text in v1alpha1), and goes
15
+ * through the same checks; its findings name `OpenTelemetryCollector
16
+ * <namespace>/<name>, spec.config` where a ConfigMap's name the ConfigMap and
17
+ * key (#3367).
18
+ *
13
19
  * Findings keep the otel rule ids (OTEL101-OTEL106, OTEL112-OTEL127, and any config
14
20
  * check the otel lexicon adds later), so `lint.rules` and suppressions name
15
21
  * one id wherever the config lives. Each message names the ConfigMap's
@@ -22,9 +28,9 @@ import { collectorConfigDiagnostics } from "@intentius/chant-lexicon-otel/lint/p
22
28
  export const wk8604: PostSynthCheck = {
23
29
  id: "WK8604",
24
30
  description:
25
- "OpenTelemetry Collector config in a ConfigMap fails the otel lexicon's config checks; findings are reported under their OTEL1xx ids, naming the ConfigMap and key.",
31
+ "OpenTelemetry Collector config in a ConfigMap or an OpenTelemetryCollector's spec.config fails the otel lexicon's config checks; findings are reported under their OTEL1xx ids, naming the ConfigMap and key, or the OpenTelemetryCollector.",
26
32
 
27
33
  check(ctx: PostSynthContext): PostSynthDiagnostic[] {
28
- return collectorConfigDiagnostics(ctx, { configMapsOnly: true });
34
+ return collectorConfigDiagnostics(ctx, { hostedOnly: true });
29
35
  },
30
36
  };
@@ -21,7 +21,7 @@
21
21
 
22
22
  import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
23
23
  import { docsToManifests, extractContainers, extractPodSpec, type K8sContainer, type K8sManifest } from "./k8s-helpers";
24
- import { collectorPlacements, describePlacement } from "./otel-placement-helpers";
24
+ import { collectorPlacements, describePlacement, isOperatorCollector } from "./otel-placement-helpers";
25
25
  import { collectorNodeAccess, type NodeHostMount } from "../../composites/otel-collector-node";
26
26
 
27
27
  function isRecord(v: unknown): v is Record<string, unknown> {
@@ -38,6 +38,8 @@ function within(path: string, dir: string): boolean {
38
38
  * container when none does. A sidecar's variables and mounts don't count.
39
39
  */
40
40
  function collectorContainers(workload: K8sManifest): K8sContainer[] {
41
+ // An OpenTelemetryCollector's `spec.env` and `spec.volumeMounts` are the collector container's own.
42
+ if (isOperatorCollector(workload)) return [{ env: workload.spec?.env as K8sContainer["env"], volumeMounts: workload.spec?.volumeMounts }];
41
43
  const all = extractContainers(workload);
42
44
  const withConfig = all.filter((c) =>
43
45
  [...(Array.isArray(c.command) ? c.command : []), ...(Array.isArray(c.args) ? c.args : [])].some(
@@ -49,7 +51,7 @@ function collectorContainers(workload: K8sManifest): K8sContainer[] {
49
51
 
50
52
  /** Each container mount backed by a hostPath volume, as [host path, container path]. */
51
53
  function hostMounts(workload: K8sManifest, containers: K8sContainer[]): Array<[string, string]> {
52
- const pod = extractPodSpec(workload);
54
+ const pod = isOperatorCollector(workload) ? workload.spec : extractPodSpec(workload);
53
55
  const hostPaths = new Map<string, string>();
54
56
  for (const v of Array.isArray(pod?.volumes) ? pod.volumes : []) {
55
57
  if (isRecord(v) && typeof v.name === "string" && isRecord(v.hostPath) && typeof v.hostPath.path === "string") {
@@ -119,7 +121,7 @@ export const wk8605: PostSynthCheck = {
119
121
  checkId: "WK8605",
120
122
  severity: "warning",
121
123
  message:
122
- `${describePlacement(p)} runs a collector config that reads the node (ConfigMap ${p.configMap}, ${p.key}), but: ${gaps.join("; ")}. ` +
124
+ `${describePlacement(p)} runs a collector config that reads the node (${p.where}), but: ${gaps.join("; ")}. ` +
123
125
  `Without them the collector reports on its own container, or nothing. OtelCollector adds these from the config; ` +
124
126
  `in a hand-written workload, add them read-only.`,
125
127
  entity: p.name,
@@ -0,0 +1,27 @@
1
+ /**
2
+ * WK8606: the prometheus rule checks over PrometheusRule groups
3
+ *
4
+ * `PrometheusRule.spec.groups` is a rule file's `groups`. `chant build` gives
5
+ * each lexicon's checks only that lexicon's output, so the prometheus
6
+ * lexicon's PROM checks never see a rule that lives in the k8s output. This
7
+ * check runs them there: every PrometheusRule's groups go through the
8
+ * prometheus lexicon's rule-file checks (PROM101-PROM107, PROM211,
9
+ * PROM213-PROM219; PROM212 stays opt-in).
10
+ *
11
+ * Findings keep the PROM ids, so `lint.rules` and suppressions name one id
12
+ * wherever the rules live. Each message names the PrometheusRule's namespace
13
+ * and name. Needs only the k8s lexicon in the project.
14
+ */
15
+
16
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
17
+ import { prometheusRuleDiagnostics } from "@intentius/chant-lexicon-prometheus/lint/post-synth/prom-helpers";
18
+
19
+ export const wk8606: PostSynthCheck = {
20
+ id: "WK8606",
21
+ description:
22
+ "A PrometheusRule's groups fail the prometheus lexicon's rule-file checks; findings are reported under their PROM ids, naming the PrometheusRule.",
23
+
24
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
25
+ return prometheusRuleDiagnostics(ctx);
26
+ },
27
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * WK8701: a PrometheusRule that no Prometheus or ThanosRuler selects
3
+ *
4
+ * A Prometheus or ThanosRuler runs the rules whose labels match its `ruleSelector` in the namespaces its
5
+ * `ruleNamespaceSelector` picks. A PrometheusRule neither selects is accepted by the API server and then
6
+ * never evaluated: no error, no alert.
7
+ *
8
+ * Selection is worked out from the manifests in one build root (chant #1939),
9
+ * by the operator's rules: a null object selector matches nothing, `{}`
10
+ * matches all; a null namespace selector matches only the selecting resource's
11
+ * own namespace, `{}` every namespace. Silent when the build has no Prometheus or ThanosRuler, since the
12
+ * stack is often installed separately. A selector on a namespace label the
13
+ * build cannot read (the Namespace is not declared in it) counts as selecting.
14
+ */
15
+
16
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
17
+ import { describe, monitoringKind, nameOf, selectionContext, unselected } from "./monitoring-selection-helpers";
18
+
19
+ export const wk8701: PostSynthCheck = {
20
+ id: "WK8701",
21
+ description:
22
+ "A PrometheusRule that no Prometheus or ThanosRuler in the build selects through ruleSelector and ruleNamespaceSelector is never evaluated. A null selector matches nothing, {} matches all. Silent when the build has no Prometheus or ThanosRuler.",
23
+
24
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
25
+ const sc = selectionContext(ctx);
26
+ const selectors = [...monitoringKind(sc.manifests, "Prometheus"), ...monitoringKind(sc.manifests, "ThanosRuler")];
27
+ return unselected(sc, monitoringKind(sc.manifests, "PrometheusRule"), selectors, () => ["ruleSelector", "ruleNamespaceSelector"]).map((r) => ({
28
+ checkId: "WK8701",
29
+ severity: "warning",
30
+ message:
31
+ `${describe(r)} is selected by no Prometheus or ThanosRuler in this build, so the operator never loads it and its rules are never evaluated. ` +
32
+ `Match its labels (and namespace) with ruleSelector and ruleNamespaceSelector: null selects nothing, {} selects all.`,
33
+ entity: nameOf(r),
34
+ lexicon: "k8s",
35
+ }));
36
+ },
37
+ };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * WK8702: a ServiceMonitor, PodMonitor, Probe or ScrapeConfig that no Prometheus or PrometheusAgent selects
3
+ *
4
+ * A Prometheus or PrometheusAgent scrapes the monitors whose labels match its `serviceMonitorSelector`,
5
+ * `podMonitorSelector`, `probeSelector` or `scrapeConfigSelector`, in the namespaces the matching
6
+ * `*NamespaceSelector` picks. A monitor none selects is accepted and then never scraped.
7
+ *
8
+ * Selection is worked out from the manifests in one build root (chant #1939),
9
+ * by the operator's rules: a null object selector matches nothing, `{}`
10
+ * matches all; a null namespace selector matches only the selecting resource's
11
+ * own namespace, `{}` every namespace. Silent when the build has no Prometheus or PrometheusAgent, since the
12
+ * stack is often installed separately. A selector on a namespace label the
13
+ * build cannot read (the Namespace is not declared in it) counts as selecting.
14
+ */
15
+
16
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
17
+ import { describe, monitoringKind, nameOf, selectionContext, unselected } from "./monitoring-selection-helpers";
18
+
19
+ export const wk8702: PostSynthCheck = {
20
+ id: "WK8702",
21
+ description:
22
+ "A ServiceMonitor, PodMonitor, Probe or ScrapeConfig that no Prometheus or PrometheusAgent in the build selects is never scraped. A null selector matches nothing, {} matches all. Silent when the build has no Prometheus or PrometheusAgent.",
23
+
24
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
25
+ const sc = selectionContext(ctx);
26
+ const selectors = [...monitoringKind(sc.manifests, "Prometheus"), ...monitoringKind(sc.manifests, "PrometheusAgent")];
27
+ const out: PostSynthDiagnostic[] = [];
28
+ for (const [kind, prefix] of [["ServiceMonitor", "serviceMonitor"], ["PodMonitor", "podMonitor"], ["Probe", "probe"], ["ScrapeConfig", "scrapeConfig"]] as const) {
29
+ for (const m of unselected(sc, monitoringKind(sc.manifests, kind), selectors, () => [`${prefix}Selector`, `${prefix}NamespaceSelector`])) {
30
+ out.push({
31
+ checkId: "WK8702",
32
+ severity: "warning",
33
+ message:
34
+ `${describe(m)} is selected by no Prometheus or PrometheusAgent in this build, so it is never scraped. ` +
35
+ `Match its labels (and namespace) with ${prefix}Selector and ${prefix}NamespaceSelector: null selects nothing, {} selects all.`,
36
+ entity: nameOf(m),
37
+ lexicon: "k8s",
38
+ });
39
+ }
40
+ }
41
+ return out;
42
+ },
43
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * WK8703: an AlertmanagerConfig that no Alertmanager selects
3
+ *
4
+ * An Alertmanager merges the AlertmanagerConfigs whose labels match its `alertmanagerConfigSelector` in the
5
+ * namespaces its `alertmanagerConfigNamespaceSelector` picks. One neither selects is accepted and then
6
+ * never routes an alert.
7
+ *
8
+ * Selection is worked out from the manifests in one build root (chant #1939),
9
+ * by the operator's rules: a null object selector matches nothing, `{}`
10
+ * matches all; a null namespace selector matches only the selecting resource's
11
+ * own namespace, `{}` every namespace. Silent when the build has no Alertmanager, since the
12
+ * stack is often installed separately. A selector on a namespace label the
13
+ * build cannot read (the Namespace is not declared in it) counts as selecting.
14
+ */
15
+
16
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
17
+ import { describe, monitoringKind, nameOf, selectionContext, unselected } from "./monitoring-selection-helpers";
18
+
19
+ export const wk8703: PostSynthCheck = {
20
+ id: "WK8703",
21
+ description:
22
+ "An AlertmanagerConfig that no Alertmanager in the build selects through alertmanagerConfigSelector and alertmanagerConfigNamespaceSelector never routes an alert. A null selector matches nothing, {} matches all. Silent when the build has no Alertmanager.",
23
+
24
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
25
+ const sc = selectionContext(ctx);
26
+ const configs = monitoringKind(sc.manifests, "AlertmanagerConfig");
27
+ return unselected(sc, configs, monitoringKind(sc.manifests, "Alertmanager"), () => ["alertmanagerConfigSelector", "alertmanagerConfigNamespaceSelector"]).map((c) => ({
28
+ checkId: "WK8703",
29
+ severity: "warning",
30
+ message:
31
+ `${describe(c)} is selected by no Alertmanager in this build, so its routes and receivers are never used. ` +
32
+ `Match its labels (and namespace) with alertmanagerConfigSelector and alertmanagerConfigNamespaceSelector: null selects nothing, {} selects all.`,
33
+ entity: nameOf(c),
34
+ lexicon: "k8s",
35
+ }));
36
+ },
37
+ };
@@ -0,0 +1,134 @@
1
+ /**
2
+ * WK8704: a ServiceMonitor or PodMonitor that selects no Service or pod, or names a port that is not there
3
+ *
4
+ * A ServiceMonitor's `selector` picks Services (in its own namespace, the
5
+ * `namespaceSelector.matchNames` ones, or every namespace with `any: true`),
6
+ * and each `endpoints[].port` names a port on them. A PodMonitor's `selector`
7
+ * picks pods, and each `podMetricsEndpoints[].port` names a container port.
8
+ * When nothing matches, or the port name is on none of the matches, Prometheus
9
+ * scrapes nothing and says nothing. This check needs no Prometheus in the
10
+ * build: it reads the monitor against the Services and workloads declared
11
+ * beside it.
12
+ *
13
+ * Pods come from the pod templates of Deployment, StatefulSet, DaemonSet, Job
14
+ * and CronJob, and from Pods themselves. An empty `selector` ({}) matches
15
+ * everything, as the operator does. Only a port given by name is checked;
16
+ * `targetPort` and `portNumber` are left alone. One build root at a time
17
+ * (chant #1939): a Service or workload installed from another root is not seen.
18
+ */
19
+
20
+ import type { PostSynthCheck, PostSynthContext, PostSynthDiagnostic } from "@intentius/chant/lint/post-synth";
21
+ import { extractContainers, type K8sManifest } from "./k8s-helpers";
22
+ import { describe, labelsOf, matchLabelSelector, monitoringKind, nameOf, namespaceOf, selectionContext } from "./monitoring-selection-helpers";
23
+
24
+ function isRecord(v: unknown): v is Record<string, unknown> {
25
+ return typeof v === "object" && v !== null && !Array.isArray(v);
26
+ }
27
+
28
+ /** Whether a monitor looks in this namespace: its own, `matchNames`, or all of them with `any`. */
29
+ function reaches(monitor: K8sManifest, namespace: string): boolean {
30
+ const ns = (monitor.spec as Record<string, unknown> | undefined)?.namespaceSelector;
31
+ if (isRecord(ns)) {
32
+ if (ns.any === true) return true;
33
+ if (Array.isArray(ns.matchNames) && ns.matchNames.length > 0) return ns.matchNames.includes(namespace);
34
+ }
35
+ return namespaceOf(monitor) === namespace;
36
+ }
37
+
38
+ /** The labels a pod from this workload carries, and its manifest to read ports from. */
39
+ function podsOf(manifests: K8sManifest[]): Array<{ manifest: K8sManifest; labels: Record<string, string> }> {
40
+ const out: Array<{ manifest: K8sManifest; labels: Record<string, string> }> = [];
41
+ for (const m of manifests) {
42
+ const spec = (m.spec ?? {}) as Record<string, any>;
43
+ if (m.kind === "Pod") {
44
+ out.push({ manifest: m, labels: labelsOf(m) });
45
+ } else if (m.kind === "Deployment" || m.kind === "StatefulSet" || m.kind === "DaemonSet" || m.kind === "Job") {
46
+ out.push({ manifest: m, labels: labelsOf({ metadata: spec.template?.metadata } as K8sManifest) });
47
+ } else if (m.kind === "CronJob") {
48
+ out.push({ manifest: m, labels: labelsOf({ metadata: spec.jobTemplate?.spec?.template?.metadata } as K8sManifest) });
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function containerPortNames(workload: K8sManifest): Set<string> {
55
+ const names = new Set<string>();
56
+ for (const c of extractContainers(workload)) {
57
+ for (const p of Array.isArray(c.ports) ? c.ports : []) {
58
+ if (isRecord(p) && typeof p.name === "string") names.add(p.name);
59
+ }
60
+ }
61
+ return names;
62
+ }
63
+
64
+ function servicePortNames(service: K8sManifest): Set<string> {
65
+ const names = new Set<string>();
66
+ const ports = (service.spec as Record<string, unknown> | undefined)?.ports;
67
+ for (const p of Array.isArray(ports) ? ports : []) {
68
+ if (isRecord(p) && typeof p.name === "string") names.add(p.name);
69
+ }
70
+ return names;
71
+ }
72
+
73
+ export const wk8704: PostSynthCheck = {
74
+ id: "WK8704",
75
+ description:
76
+ "A ServiceMonitor whose selector matches no Service in the build, or whose endpoints[].port names no port on the matched Services; the same for a PodMonitor against pod container ports. Needs no Prometheus in the build. Sees one build root at a time (chant #1939).",
77
+
78
+ check(ctx: PostSynthContext): PostSynthDiagnostic[] {
79
+ const { manifests } = selectionContext(ctx);
80
+ const out: PostSynthDiagnostic[] = [];
81
+ const diag = (m: K8sManifest, message: string): PostSynthDiagnostic => ({
82
+ checkId: "WK8704",
83
+ severity: "warning",
84
+ message,
85
+ entity: nameOf(m),
86
+ lexicon: "k8s",
87
+ });
88
+
89
+ const services = manifests.filter((m) => m.kind === "Service" && (m.apiVersion === "v1" || m.apiVersion === undefined));
90
+ for (const sm of monitoringKind(manifests, "ServiceMonitor")) {
91
+ const spec = (sm.spec ?? {}) as Record<string, unknown>;
92
+ // A ServiceMonitor's selector is required; treat a missing one like {}.
93
+ const selector = isRecord(spec.selector) ? spec.selector : {};
94
+ const matched = services.filter((s) => reaches(sm, namespaceOf(s)) && matchLabelSelector(selector, labelsOf(s)) !== "no");
95
+ if (matched.length === 0) {
96
+ out.push(diag(sm, `${describe(sm)} has a selector that matches no Service in this build (looking in ${where(sm)}), so Prometheus scrapes nothing for it. Make spec.selector match the labels on the Service, or fix namespaceSelector.`));
97
+ continue;
98
+ }
99
+ const known = new Set<string>();
100
+ for (const s of matched) for (const n of servicePortNames(s)) known.add(n);
101
+ for (const e of Array.isArray(spec.endpoints) ? spec.endpoints : []) {
102
+ if (!isRecord(e) || typeof e.port !== "string" || known.has(e.port)) continue;
103
+ out.push(diag(sm, `${describe(sm)} scrapes endpoint port "${e.port}", but the Service(s) it selects (${matched.map(nameOf).join(", ")}) declare no port with that name${known.size > 0 ? ` (they have: ${[...known].join(", ")})` : ""}. Name the Service port, or point the endpoint at an existing one.`));
104
+ }
105
+ }
106
+
107
+ const pods = podsOf(manifests);
108
+ for (const pm of monitoringKind(manifests, "PodMonitor")) {
109
+ const spec = (pm.spec ?? {}) as Record<string, unknown>;
110
+ const selector = isRecord(spec.selector) ? spec.selector : {};
111
+ const matched = pods.filter((p) => reaches(pm, namespaceOf(p.manifest)) && matchLabelSelector(selector, p.labels) !== "no");
112
+ if (matched.length === 0) {
113
+ out.push(diag(pm, `${describe(pm)} has a selector that matches no pod in this build (looking in ${where(pm)}), so Prometheus scrapes nothing for it. Make spec.selector match the pod template labels, or fix namespaceSelector.`));
114
+ continue;
115
+ }
116
+ const known = new Set<string>();
117
+ for (const p of matched) for (const n of containerPortNames(p.manifest)) known.add(n);
118
+ for (const e of Array.isArray(spec.podMetricsEndpoints) ? spec.podMetricsEndpoints : []) {
119
+ if (!isRecord(e) || typeof e.port !== "string" || known.has(e.port)) continue;
120
+ out.push(diag(pm, `${describe(pm)} scrapes container port "${e.port}", but the pods it selects (${matched.map((p) => nameOf(p.manifest)).join(", ")}) declare no container port with that name${known.size > 0 ? ` (they have: ${[...known].join(", ")})` : ""}. Name the container port, or point the endpoint at an existing one.`));
121
+ }
122
+ }
123
+ return out;
124
+ },
125
+ };
126
+
127
+ function where(m: K8sManifest): string {
128
+ const ns = (m.spec as Record<string, unknown> | undefined)?.namespaceSelector;
129
+ if (isRecord(ns)) {
130
+ if (ns.any === true) return "every namespace";
131
+ if (Array.isArray(ns.matchNames) && ns.matchNames.length > 0) return `namespace ${ns.matchNames.join(", ")}`;
132
+ }
133
+ return `namespace ${namespaceOf(m)}`;
134
+ }