@intentius/chant-lexicon-k8s 0.102.0 → 0.104.0

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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-k8s",
3
- "version": "0.102.0",
3
+ "version": "0.104.0",
4
4
  "description": "Kubernetes lexicon for chant — declarative IaC in TypeScript",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -78,7 +78,7 @@
78
78
  "@types/js-yaml": "^4.0.9"
79
79
  },
80
80
  "optionalDependencies": {
81
- "@intentius/chant-k8s-client": "^0.102.0"
81
+ "@intentius/chant-k8s-client": "^0.104.0"
82
82
  },
83
83
  "devDependencies": {
84
84
  "@intentius/chant": "*",
@@ -86,7 +86,7 @@
86
86
  },
87
87
  "peerDependencies": {
88
88
  "zod": "^4.3.6",
89
- "@intentius/chant": "^0.102.0",
89
+ "@intentius/chant": "^0.104.0",
90
90
  "typescript": "^5.9.3"
91
91
  }
92
92
  }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A CRD source that fails to load fails generation, naming the source (#3310).
3
+ */
4
+
5
+ import { describe, expect, it } from "vitest";
6
+ import { loadCrdSources } from "./generate";
7
+ import type { CRDSource } from "../crd/types";
8
+ import type { K8sParseResult } from "../spec/parse";
9
+
10
+ const good: CRDSource = { type: "url", url: "https://example.test/good.yaml" };
11
+ const down: CRDSource = { type: "helm", chart: "oci://registry.example.test/charts/operator", version: "1.0.0" };
12
+ const moved: CRDSource = { type: "url", url: "https://example.test/moved.yaml" };
13
+
14
+ const fakeResult = { resource: { typeName: "K8s::Example::Thing" } } as unknown as K8sParseResult;
15
+
16
+ async function fakeLoad(sources: CRDSource[]): Promise<K8sParseResult[]> {
17
+ const [source] = sources;
18
+ if (source === down) throw new Error("registry unreachable");
19
+ if (source === moved) throw new Error("404 Not Found");
20
+ return [fakeResult];
21
+ }
22
+
23
+ describe("loadCrdSources (#3310)", () => {
24
+ it("returns every source's types when all load", async () => {
25
+ const out = await loadCrdSources([good], () => {}, { load: fakeLoad });
26
+ expect(out.results).toEqual([fakeResult]);
27
+ expect(out.warnings).toEqual([]);
28
+ });
29
+
30
+ it("fails naming each source that failed to load, after trying them all", async () => {
31
+ const attempted: CRDSource[] = [];
32
+ const load = async (sources: CRDSource[]) => {
33
+ attempted.push(...sources);
34
+ return fakeLoad(sources);
35
+ };
36
+ const run = loadCrdSources([down, good, moved], () => {}, { load });
37
+ await expect(run).rejects.toThrow(/2 CRD source\(s\) failed to load/);
38
+ await expect(run).rejects.toThrow(/oci:\/\/registry\.example\.test\/charts\/operator: registry unreachable/);
39
+ await expect(run).rejects.toThrow(/https:\/\/example\.test\/moved\.yaml: 404 Not Found/);
40
+ await expect(run).rejects.toThrow(/CHANT_K8S_ALLOW_CRD_FAILURES=1/);
41
+ expect(attempted).toEqual([down, good, moved]);
42
+ });
43
+
44
+ it("generates without a failed source, as a warning, only when allowed", async () => {
45
+ const out = await loadCrdSources([down, good], () => {}, { load: fakeLoad, allowFailures: true });
46
+ expect(out.results).toEqual([fakeResult]);
47
+ expect(out.warnings).toEqual([{ file: "oci://registry.example.test/charts/operator", error: "registry unreachable" }]);
48
+ });
49
+ });
@@ -21,6 +21,7 @@ import {
21
21
  } from "../spec/parse";
22
22
  import { loadMultipleCRDs } from "../crd/loader";
23
23
  import { CRD_SOURCES } from "../crd/crd-sources";
24
+ import type { CRDSource } from "../crd/types";
24
25
  import { NamingStrategy, propertyTypeName, extractDefName } from "./naming";
25
26
  import { generateLexiconJSON } from "./generate-lexicon";
26
27
  import { generateOperationsJSON } from "./generate-operations";
@@ -37,6 +38,56 @@ export type { GenerateResult };
37
38
  export interface K8sGenerateOptions extends GenerateOptions {
38
39
  /** Kubernetes version tag to fetch the schema from. */
39
40
  schemaVersion?: string;
41
+ /**
42
+ * Generate without a CRD source that fails to load, as a warning, instead
43
+ * of failing (#3310). For a deliberate offline or partial run only: the
44
+ * output then lacks that source's kinds. Defaults to
45
+ * `CHANT_K8S_ALLOW_CRD_FAILURES=1` in the environment.
46
+ */
47
+ allowCrdFailures?: boolean;
48
+ }
49
+
50
+ /** Where a CRD source comes from, as a log line or an error names it. */
51
+ function crdSourceLabel(source: CRDSource): string {
52
+ return source.url ?? source.path ?? source.chart ?? "cluster";
53
+ }
54
+
55
+ /**
56
+ * Load every CRD source. A source that fails to load fails generation and the
57
+ * error names it (#3310): skipping it shrinks the output silently, and the loss
58
+ * shows up only later as a surface-snapshot diff. Every source is tried first,
59
+ * so one run names all the failures. `allowFailures` turns them back into
60
+ * warnings for a deliberate partial run.
61
+ */
62
+ export async function loadCrdSources(
63
+ sources: readonly CRDSource[],
64
+ log: (msg: string) => void,
65
+ opts: { allowFailures?: boolean; load?: (sources: CRDSource[]) => Promise<K8sParseResult[]> } = {},
66
+ ): Promise<{ results: K8sParseResult[]; warnings: Array<{ file: string; error: string }> }> {
67
+ const load = opts.load ?? loadMultipleCRDs;
68
+ const results: K8sParseResult[] = [];
69
+ const failures: Array<{ file: string; error: string }> = [];
70
+ for (const source of sources) {
71
+ const label = crdSourceLabel(source);
72
+ try {
73
+ const parsed = await load([source]);
74
+ results.push(...parsed);
75
+ log(`Loaded ${parsed.length} CRD type(s) from ${label}`);
76
+ } catch (err) {
77
+ const msg = err instanceof Error ? err.message : String(err);
78
+ failures.push({ file: label, error: msg });
79
+ log(`${opts.allowFailures ? "Warning: skipping" : "Error:"} CRD source ${label} failed to load: ${msg}`);
80
+ }
81
+ }
82
+ if (failures.length > 0 && !opts.allowFailures) {
83
+ const lines = failures.map((f) => ` ${f.file}: ${f.error}`).join("\n");
84
+ throw new Error(
85
+ `${failures.length} CRD source(s) failed to load, so generation would drop their kinds:\n${lines}\n` +
86
+ `Set CHANT_K8S_ALLOW_CRD_FAILURES=1 to generate without them deliberately.`,
87
+ );
88
+ }
89
+ log(`Total CRD types loaded: ${results.length}`);
90
+ return { results, warnings: failures };
40
91
  }
41
92
 
42
93
  /**
@@ -74,20 +125,8 @@ export async function generate(opts: K8sGenerateOptions = {}): Promise<GenerateR
74
125
  augmentSchemas: async (schemas, _opts, log) => {
75
126
  // Load third-party CRDs and return as extraResults so they are
76
127
  // included in the generated types alongside the core K8s resources.
77
- const crdResults: K8sParseResult[] = [];
78
- const warnings: Array<{ file: string; error: string }> = [];
79
- for (const source of CRD_SOURCES) {
80
- try {
81
- const parsed = await loadMultipleCRDs([source]);
82
- crdResults.push(...parsed);
83
- log(`Loaded ${parsed.length} CRD type(s) from ${source.url ?? source.path ?? source.chart ?? "cluster"}`);
84
- } catch (err) {
85
- const msg = err instanceof Error ? err.message : String(err);
86
- warnings.push({ file: source.url ?? source.path ?? source.chart ?? "cluster", error: msg });
87
- log(`Warning: failed to load CRD: ${msg}`);
88
- }
89
- }
90
- log(`Total CRD types loaded: ${crdResults.length}`);
128
+ const allowFailures = opts.allowCrdFailures ?? process.env.CHANT_K8S_ALLOW_CRD_FAILURES === "1";
129
+ const { results: crdResults, warnings } = await loadCrdSources(CRD_SOURCES, log, { allowFailures });
91
130
  return { schemas, extraResults: crdResults, warnings };
92
131
  },
93
132
 
@@ -39,3 +39,90 @@ describe("kubectl-apply capability (#1495 piece 2)", () => {
39
39
  expect(units).toEqual([{ unit: "kubemicrovm-ops", lexicon: "k8s" }]);
40
40
  });
41
41
  });
42
+
43
+ describe("kubectl-apply with a release (#3061, ws-081)", () => {
44
+ const stamped = () => ({
45
+ apiVersion: "apps/v1",
46
+ kind: "Deployment",
47
+ metadata: { name: "api" },
48
+ spec: {
49
+ template: {
50
+ metadata: { labels: { app: "api" } },
51
+ spec: {
52
+ containers: [
53
+ {
54
+ name: "api",
55
+ image: "x",
56
+ env: [
57
+ { name: "CHANT_RELEASE_ATTRIBUTES", valueFrom: { fieldRef: { fieldPath: "metadata.annotations['chant.intentius.io/release-attributes']" } } },
58
+ { name: "OTEL_RESOURCE_ATTRIBUTES", value: "chant.decl=api$(CHANT_RELEASE_ATTRIBUTES)" },
59
+ ],
60
+ },
61
+ ],
62
+ },
63
+ },
64
+ },
65
+ });
66
+ const plain = () => ({ apiVersion: "v1", kind: "Service", metadata: { name: "api" }, spec: { ports: [{ port: 80 }] } });
67
+ const release = { version: "sha256:abc", revision: "0123abc" };
68
+
69
+ test("sets the release attributes on the pod template of each stamped workload it applies", async () => {
70
+ let seen: { documents?: Record<string, any>[] } = {};
71
+ const cap = createKubectlApplyCapability(
72
+ async (args) => {
73
+ seen = args as typeof seen;
74
+ return { applied: [], pruned: [], fieldManager: "chant:x" };
75
+ },
76
+ () => [stamped(), plain()],
77
+ );
78
+ await cap.run({ env: "prod", component: "api", release }, { manifest: "k8s.yaml", stack: "x" });
79
+ expect(seen.documents![0].spec.template.metadata).toEqual({
80
+ labels: { app: "api" },
81
+ annotations: { "chant.intentius.io/release-attributes": ",service.version=sha256%3Aabc,vcs.ref.head.revision=0123abc" },
82
+ });
83
+ expect(seen.documents![1]).toEqual(plain());
84
+ });
85
+
86
+ test("without a release, or with no stamped workload, it applies the manifest as read", async () => {
87
+ const calls: Record<string, unknown>[] = [];
88
+ let reads = 0;
89
+ const cap = createKubectlApplyCapability(
90
+ async (args) => {
91
+ calls.push({ ...args });
92
+ return { applied: [], pruned: [], fieldManager: "chant:x" };
93
+ },
94
+ () => {
95
+ reads++;
96
+ return [plain()];
97
+ },
98
+ );
99
+ await cap.run({ env: "prod", component: "api" }, { manifest: "k8s.yaml" });
100
+ await cap.run({ env: "prod", component: "api", release }, { manifest: "k8s.yaml" });
101
+ expect(reads).toBe(1);
102
+ expect(calls.every((c) => !("documents" in c))).toBe(true);
103
+ });
104
+
105
+ test("the committed manifest is the same bytes after a release apply", async () => {
106
+ const { mkdtempSync, readFileSync, rmSync, writeFileSync } = await import("node:fs");
107
+ const { tmpdir } = await import("node:os");
108
+ const { join } = await import("node:path");
109
+ const { dump } = await import("js-yaml");
110
+ const { readManifestDocuments } = await import("../op/activities/kubectl");
111
+ const dir = mkdtempSync(join(tmpdir(), "chant-3061-"));
112
+ try {
113
+ const file = join(dir, "k8s.yaml");
114
+ writeFileSync(file, `${dump(stamped())}---\n${dump(plain())}`);
115
+ const before = readFileSync(file, "utf-8");
116
+ let annotated = 0;
117
+ const cap = createKubectlApplyCapability(async (args) => {
118
+ annotated = (args.documents ?? []).filter((d: any) => d.spec?.template?.metadata?.annotations).length;
119
+ return { applied: [], pruned: [], fieldManager: "chant:x" };
120
+ }, readManifestDocuments);
121
+ await cap.run({ env: "prod", component: "api", release }, { manifest: file });
122
+ expect(annotated).toBe(1);
123
+ expect(readFileSync(file, "utf-8")).toBe(before);
124
+ } finally {
125
+ rmSync(dir, { recursive: true, force: true });
126
+ }
127
+ });
128
+ });
@@ -16,6 +16,8 @@
16
16
  * pairing `cfn-deploy` has with its stack.
17
17
  */
18
18
  import type { Capability, DeployContext } from "@intentius/chant/components/capability";
19
+ import { releaseAttributesSuffix } from "@intentius/chant/telemetry-attribution";
20
+ import { annotateRelease } from "../telemetry-release";
19
21
 
20
22
  /**
21
23
  * Structural mirrors of the activity module's argument/result shapes.
@@ -51,6 +53,8 @@ export interface KubectlApplyOutcome {
51
53
 
52
54
  interface ApplierArgs {
53
55
  manifest: string;
56
+ /** The parsed documents to apply instead of reading `manifest`, when the step changed them in memory. */
57
+ documents?: Record<string, unknown>[];
54
58
  environment?: string;
55
59
  stack?: string;
56
60
  context?: string;
@@ -58,6 +62,7 @@ interface ApplierArgs {
58
62
  }
59
63
 
60
64
  type Applier = (args: ApplierArgs) => Promise<KubectlApplyOutcome>;
65
+ type ManifestReader = (path: string) => Record<string, unknown>[];
61
66
 
62
67
  export interface KubectlApplyInput {
63
68
  /** Path to a manifest file, or a directory of them. */
@@ -86,6 +91,7 @@ export interface KubectlApplyInput {
86
91
  * chain off the build path (#1074). */
87
92
  export function createKubectlApplyCapability(
88
93
  apply?: Applier,
94
+ read?: ManifestReader,
89
95
  ): Capability<KubectlApplyInput, KubectlApplyOutcome> {
90
96
  return {
91
97
  kind: "kubectl-apply",
@@ -94,9 +100,19 @@ export function createKubectlApplyCapability(
94
100
  // the compensation gap — the same posture as s3-sync/run-migration.
95
101
  rollbackPolicy: "needs-opt-out",
96
102
  async run(ctx: DeployContext, input: KubectlApplyInput): Promise<KubectlApplyOutcome> {
97
- const applier: Applier = apply ?? (await import("../op/activities/kubectl")).applyManifest;
103
+ const activities = apply && read ? undefined : await import("../op/activities/kubectl");
104
+ const applier: Applier = apply ?? activities!.applyManifest;
105
+ // A release run (#3061, ws-081) sets the release attributes on the pod template of each
106
+ // workload the build stamped, in what it applies; the committed manifest is not touched.
107
+ const suffix = releaseAttributesSuffix(ctx.release);
108
+ let documents: Record<string, unknown>[] | undefined;
109
+ if (suffix !== "") {
110
+ documents = (read ?? activities!.readManifestDocuments)(input.manifest);
111
+ if (annotateRelease(documents, suffix) === 0) documents = undefined;
112
+ }
98
113
  return applier({
99
114
  manifest: input.manifest,
115
+ ...(documents ? { documents } : {}),
100
116
  environment: ctx.env,
101
117
  ...(input.stack !== undefined ? { stack: input.stack } : {}),
102
118
  ...(input.context !== undefined ? { context: input.context } : {}),
@@ -9,6 +9,8 @@ import {
9
9
  LoadBalancingExporter,
10
10
  OtlpReceiver,
11
11
  Pipeline,
12
+ PrometheusExporter,
13
+ defineComponent,
12
14
  Service as CollectorService,
13
15
  TailSamplingProcessor,
14
16
  collectorTopology,
@@ -80,6 +82,26 @@ describe("OtelCollectorGateway", () => {
80
82
  expect(container.securityContext.capabilities).toEqual({ drop: ["ALL"] });
81
83
  });
82
84
 
85
+ test("a UDP receiver's port is UDP on the container and the Services, and the prometheus exporter's port is exposed (#3122)", () => {
86
+ const StatsdReceiver = defineComponent<{ endpoint: string }>()({
87
+ kind: "receiver",
88
+ type: "statsd",
89
+ pin: { source: "github.com/open-telemetry/opentelemetry-collector-contrib", version: "v0.130.0" },
90
+ });
91
+ const statsd = new StatsdReceiver({ endpoint: "0.0.0.0:8125" });
92
+ const prom = new PrometheusExporter({ endpoint: "0.0.0.0:8889" });
93
+ const gw = OtelCollectorGateway({ config: [new Pipeline({ signal: "metrics", receivers: [statsd], exporters: [prom] })] });
94
+ expect(p(gw.service).spec.ports).toEqual([
95
+ { name: "statsd", port: 8125, targetPort: "statsd", protocol: "UDP" },
96
+ { name: "prometheus", port: 8889, targetPort: "prometheus", protocol: "TCP" },
97
+ ]);
98
+ const container = p(gw.deployment).spec.template.spec.containers[0];
99
+ expect(container.ports).toEqual([
100
+ { containerPort: 8125, name: "statsd", protocol: "UDP" },
101
+ { containerPort: 8889, name: "prometheus" },
102
+ ]);
103
+ });
104
+
83
105
  test("clusterRules adds a ClusterRole bound to the gateway's ServiceAccount", () => {
84
106
  const rules = [{ apiGroups: [""], resources: ["pods", "nodes"], verbs: ["get", "list", "watch"] }];
85
107
  const gw = OtelCollectorGateway({ name: "gw", namespace: "obs", clusterRules: rules });
@@ -199,7 +221,8 @@ describe("gatewayExporter", () => {
199
221
  const agent = agentOf(exporter, { name: "agent" });
200
222
  expect(config(agent).exporters?.["otlphttp/gateway"]).toEqual({ endpoint: "http://otel-gateway.observability.svc:4318" });
201
223
  expect(p(agent.configMap).metadata.annotations[A.gateways]).toBe("observability/otel-gateway=service");
202
- expect(validateCollectorConfig(config(agent))).toEqual([]);
224
+ // agentOf's pipeline has no batch processor, which OTEL125 reports for an otlphttp exporter.
225
+ expect(validateCollectorConfig(config(agent)).filter((i) => i.code !== "OTEL125")).toEqual([]);
203
226
  });
204
227
 
205
228
  test("with protocol http and TLS, https and the TLS settings without insecure", () => {
@@ -200,7 +200,7 @@ export const OtelCollectorGateway = Composite((props: OtelCollectorGatewayProps)
200
200
  },
201
201
  }, defs?.deployment));
202
202
 
203
- const servicePorts = runtime.servicePorts.map((p) => ({ name: p.name, port: p.port, targetPort: p.name, protocol: "TCP" }));
203
+ const servicePorts = runtime.servicePorts.map((p) => ({ name: p.name, port: p.port, targetPort: p.name, protocol: p.protocol ?? "TCP" }));
204
204
 
205
205
  const service = new Service(mergeDefaults({
206
206
  metadata: { name, namespace, labels: gatewayLabels },
@@ -50,6 +50,25 @@ describe("collectorNodeAccess", () => {
50
50
  expect(access.env).toEqual([{ name: "KUBE_NODE_NAME", valueFrom: { fieldRef: { fieldPath: "spec.nodeName" } } }]);
51
51
  });
52
52
 
53
+ test("the collector's newer names read the node the same as the old ones", () => {
54
+ const old = collectorNodeAccess(
55
+ cfg(
56
+ { kubeletstats: { node: "${env:K8S_NODE_NAME}" }, hostmetrics: { root_path: "/hostfs" }, filelog: { include: ["/var/log/pods/*/*/*.log"] } },
57
+ { k8sattributes: { filter: { node_from_env_var: "KUBE_NODE_NAME" } } },
58
+ ),
59
+ );
60
+ const renamed = collectorNodeAccess(
61
+ cfg(
62
+ { kubelet_stats: { node: "${env:K8S_NODE_NAME}" }, host_metrics: { root_path: "/hostfs" }, file_log: { include: ["/var/log/pods/*/*/*.log"] } },
63
+ { k8s_attributes: { filter: { node_from_env_var: "KUBE_NODE_NAME" } } },
64
+ ),
65
+ );
66
+ expect(renamed.env).toEqual(old.env);
67
+ expect(renamed.mounts.map(({ component: _, ...m }) => m)).toEqual(old.mounts.map(({ component: _, ...m }) => m));
68
+ expect(renamed.readsLogs).toBe(true);
69
+ expect(renamed.mounts).toHaveLength(2);
70
+ });
71
+
53
72
  test("kubeletstats: node and a NODE_NAME endpoint get the node name, a NODE_IP endpoint the host IP", () => {
54
73
  expect(collectorNodeAccess(cfg({ kubeletstats: { endpoint: "https://${env:K8S_NODE_NAME}:10250", node: "${env:K8S_NODE_NAME}" } })).env).toEqual([NODE_NAME]);
55
74
  expect(collectorNodeAccess(cfg({ kubeletstats: { endpoint: "https://${env:K8S_NODE_IP}:10250" } })).env).toEqual([
@@ -38,6 +38,8 @@
38
38
  * deal with (see `logAccess` on `OtelCollector`).
39
39
  */
40
40
 
41
+ import { canonicalTypeOf } from "@intentius/chant-lexicon-otel/model";
42
+
41
43
  /** A variable set from the downward API. A type alias, so it fits where container fields are a plain record. */
42
44
  export type NodeEnvVar = {
43
45
  name: string;
@@ -77,11 +79,6 @@ function isRecord(v: unknown): v is Record<string, unknown> {
77
79
  return typeof v === "object" && v !== null && !Array.isArray(v);
78
80
  }
79
81
 
80
- function typeOf(id: string): string {
81
- const slash = id.indexOf("/");
82
- return slash === -1 ? id : id.slice(0, slash);
83
- }
84
-
85
82
  /** Component ids of one kind that some pipeline runs. */
86
83
  function runningIds(config: NodeReadingConfig, kind: "receivers" | "processors"): Set<string> {
87
84
  const ids = new Set<string>();
@@ -93,12 +90,13 @@ function runningIds(config: NodeReadingConfig, kind: "receivers" | "processors")
93
90
  return ids;
94
91
  }
95
92
 
96
- /** [id, settings] of each running component of `type`. */
93
+ /** [id, settings] of each running component of `type`, under its old or new name (`kubelet_stats`). */
97
94
  function running(config: NodeReadingConfig, kind: "receivers" | "processors", type: string): Array<[string, Record<string, unknown>]> {
98
95
  const ids = runningIds(config, kind);
99
96
  const section = isRecord(config[kind]) ? (config[kind] as Record<string, unknown>) : {};
97
+ const componentKind = kind === "receivers" ? "receiver" : "processor";
100
98
  return Object.entries(section)
101
- .filter(([id]) => ids.has(id) && typeOf(id) === type)
99
+ .filter(([id]) => ids.has(id) && canonicalTypeOf(componentKind, id) === type)
102
100
  .map(([id, cfg]) => [id, isRecord(cfg) ? cfg : {}]);
103
101
  }
104
102
 
@@ -49,6 +49,17 @@ describe("agentClusterRules", () => {
49
49
  expect(rules[2].resources).toEqual(["nodes/stats"]);
50
50
  });
51
51
 
52
+ test("k8s_attributes and kubelet_stats, the collector's newer names, get the same rules as the old ones", () => {
53
+ const kubelet = { extra_metadata_labels: ["container.id"], k8s_api_config: { auth_type: "serviceAccount" } };
54
+ const extract = { extract: { labels: [{ key: "team", from: "deployment" }] } };
55
+ const old = agentClusterRules(cfg({ processors: { "k8sattributes/x": extract }, receivers: { kubeletstats: kubelet } } as any));
56
+ const renamed = agentClusterRules(cfg({ processors: { "k8s_attributes/x": extract }, receivers: { kubelet_stats: kubelet } } as any));
57
+ expect(renamed).toEqual(old);
58
+ expect(renamed.flatMap((r) => r.resources)).toEqual(
59
+ expect.arrayContaining(["deployments", "nodes/stats", "nodes/proxy", "persistentvolumes"]),
60
+ );
61
+ });
62
+
52
63
  test("kubeletstats with k8s_api_config reads persistent volumes and claims", () => {
53
64
  const rules = agentClusterRules(cfg({ receivers: { kubeletstats: { k8s_api_config: { auth_type: "serviceAccount" } } } as any }));
54
65
  expect(rules.at(-1)).toEqual({ apiGroups: [""], resources: ["persistentvolumeclaims", "persistentvolumes"], verbs: ["get"] });
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { mergeDefaults } from "@intentius/chant";
18
18
  import type { CollectorConfig } from "@intentius/chant-lexicon-otel";
19
+ import { canonicalTypeOf, type ComponentKind } from "@intentius/chant-lexicon-otel/model";
19
20
  import { Role, RoleBinding } from "../generated";
20
21
 
21
22
  /** One RBAC rule, as a Role or ClusterRole lists it. */
@@ -28,9 +29,10 @@ export interface CollectorPolicyRule {
28
29
 
29
30
  const READ = ["get", "list", "watch"];
30
31
 
31
- function componentsOfType(section: Record<string, unknown> | undefined, type: string): Array<Record<string, unknown>> {
32
+ /** The configs of the components of `kind` whose type is `type`, under its old or new name (`k8s_attributes`). */
33
+ function componentsOfType(kind: ComponentKind, section: Record<string, unknown> | undefined, type: string): Array<Record<string, unknown>> {
32
34
  return Object.entries(section ?? {})
33
- .filter(([id]) => id === type || id.startsWith(`${type}/`))
35
+ .filter(([id]) => canonicalTypeOf(kind, id) === type)
34
36
  .map(([, cfg]) => (cfg && typeof cfg === "object" ? (cfg as Record<string, unknown>) : {}));
35
37
  }
36
38
 
@@ -58,7 +60,7 @@ function componentsOfType(section: Record<string, unknown> | undefined, type: st
58
60
  */
59
61
  export function agentClusterRules(config: CollectorConfig): CollectorPolicyRule[] {
60
62
  const apps = ["replicasets"];
61
- const k8sattributes = componentsOfType(config.processors as Record<string, unknown> | undefined, "k8sattributes");
63
+ const k8sattributes = componentsOfType("processor", config.processors as Record<string, unknown> | undefined, "k8sattributes");
62
64
  const fromDeployment = k8sattributes.some((p) => {
63
65
  const extract = p.extract as { labels?: Array<{ from?: string }>; annotations?: Array<{ from?: string }> } | undefined;
64
66
  return [...(extract?.labels ?? []), ...(extract?.annotations ?? [])].some((f) => f?.from === "deployment");
@@ -70,7 +72,7 @@ export function agentClusterRules(config: CollectorConfig): CollectorPolicyRule[
70
72
  { apiGroups: ["apps"], resources: apps, verbs: READ },
71
73
  ];
72
74
 
73
- const kubeletstats = componentsOfType(config.receivers as Record<string, unknown> | undefined, "kubeletstats");
75
+ const kubeletstats = componentsOfType("receiver", config.receivers as Record<string, unknown> | undefined, "kubeletstats");
74
76
  if (kubeletstats.length) {
75
77
  const nodeSubresources = ["nodes/stats"];
76
78
  const needsProxy = kubeletstats.some((r) => {
@@ -14,6 +14,7 @@
14
14
  import type { Declarable } from "@intentius/chant/declarable";
15
15
  import {
16
16
  buildCollectorConfig,
17
+ canonicalTypeOf,
17
18
  collectorEndpoints,
18
19
  collectorYaml,
19
20
  COLLECTOR_CONFIG_PATH,
@@ -79,9 +80,9 @@ export interface CollectorRuntime {
79
80
  built: BuiltCollector;
80
81
  configYaml: string;
81
82
  configDir: string;
82
- containerPorts: Array<{ containerPort: number; name: string }>;
83
- /** The receiver ports, which the Services expose. The health port is left out. */
84
- servicePorts: Array<{ name: string; port: number }>;
83
+ containerPorts: Array<{ containerPort: number; name: string; protocol?: "UDP" }>;
84
+ /** The receiver and exporter ports, which the Services expose. The health port is left out. */
85
+ servicePorts: Array<{ name: string; port: number; protocol?: "UDP" }>;
85
86
  /** Security context and, when the config enables `health_check`, the probes. */
86
87
  containerExtra: Record<string, unknown>;
87
88
  }
@@ -93,11 +94,11 @@ export function collectorRuntime(entities: Declarable[]): CollectorRuntime {
93
94
 
94
95
  // The probe names the port. A health_check on a receiver's port reuses that
95
96
  // port's name, since a container port is declared once.
96
- const healthPortName = healthCheck ? (ports.find((p) => p.port === healthCheck.port)?.name ?? "health") : undefined;
97
+ const healthPortName = healthCheck ? (ports.find((p) => p.port === healthCheck.port && !p.protocol)?.name ?? "health") : undefined;
97
98
  const probe = healthCheck ? { httpGet: { path: healthCheck.path, port: healthPortName } } : undefined;
98
99
  const containerPorts = [
99
- ...ports.map((p) => ({ containerPort: p.port, name: p.name })),
100
- ...(healthCheck && !ports.some((p) => p.port === healthCheck.port)
100
+ ...ports.map((p) => ({ containerPort: p.port, name: p.name, ...(p.protocol ? { protocol: p.protocol } : {}) })),
101
+ ...(healthCheck && !ports.some((p) => p.port === healthCheck.port && !p.protocol)
101
102
  ? [{ containerPort: healthCheck.port, name: "health" }]
102
103
  : []),
103
104
  ];
@@ -107,7 +108,7 @@ export function collectorRuntime(entities: Declarable[]): CollectorRuntime {
107
108
  configYaml: collectorYaml(entities),
108
109
  configDir,
109
110
  containerPorts,
110
- servicePorts: ports.map((p) => ({ name: p.name, port: p.port })),
111
+ servicePorts: ports.map((p) => ({ name: p.name, port: p.port, ...(p.protocol ? { protocol: p.protocol } : {}) })),
111
112
  containerExtra: {
112
113
  imagePullPolicy: "IfNotPresent",
113
114
  securityContext: {
@@ -130,7 +131,7 @@ export function collectorRuntime(entities: Declarable[]): CollectorRuntime {
130
131
  export function k8sResolverNamespaces(built: BuiltCollector, ownNamespace: string): string[] {
131
132
  const out: string[] = [];
132
133
  for (const [id, cfg] of Object.entries(built.config.exporters ?? {})) {
133
- if (id !== "loadbalancing" && !id.startsWith("loadbalancing/")) continue;
134
+ if (canonicalTypeOf("exporter", id) !== "loadbalancing") continue;
134
135
  const service = (cfg as { resolver?: { k8s?: { service?: string } } })?.resolver?.k8s?.service;
135
136
  if (!service) continue;
136
137
  const dot = service.indexOf(".");
@@ -180,7 +180,7 @@ export const OtelCollector = Composite((props: OtelCollectorProps) => {
180
180
  spec: {
181
181
  selector: { "app.kubernetes.io/name": name },
182
182
  internalTrafficPolicy: "Local",
183
- ports: runtime.servicePorts.map((p) => ({ name: p.name, port: p.port, targetPort: p.name, protocol: "TCP" })),
183
+ ports: runtime.servicePorts.map((p) => ({ name: p.name, port: p.port, targetPort: p.name, protocol: p.protocol ?? "TCP" })),
184
184
  },
185
185
  }, defs?.service));
186
186
 
@@ -489,9 +489,10 @@ const ACK_EKS_CRD_BASE = `https://raw.githubusercontent.com/aws-controllers-k8s/
489
489
  * K8s::Grafana::GrafanaDashboard → grafana.integreatly.org/v1beta1, kind: GrafanaDashboard
490
490
  * K8s::Grafana::GrafanaDatasource → grafana.integreatly.org/v1beta1, kind: GrafanaDatasource
491
491
  * K8s::Grafana::GrafanaFolder → grafana.integreatly.org/v1beta1, kind: GrafanaFolder
492
+ * K8s::Grafana::GrafanaLibraryPanel → grafana.integreatly.org/v1beta1, kind: GrafanaLibraryPanel
492
493
  *
493
- * The operator's other kinds (Grafana itself, alerting, library panels,
494
- * service accounts, manifests) are left out until something uses them.
494
+ * The operator's other kinds (Grafana itself, alerting, service accounts,
495
+ * manifests) are left out until something uses them.
495
496
  *
496
497
  * Operator install: kubectl apply --server-side -f
497
498
  * https://github.com/grafana/grafana-operator/releases/download/v5.25.0/kustomize-cluster_scoped.yaml
@@ -587,4 +588,5 @@ export const CRD_SOURCES: CRDSource[] = [
587
588
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanadashboards.yaml` },
588
589
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanadatasources.yaml` },
589
590
  { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanafolders.yaml` },
591
+ { type: "url", url: `${GRAFANA_OPERATOR_CRD_BASE}/grafana.integreatly.org_grafanalibrarypanels.yaml` },
590
592
  ];
@@ -1159,6 +1159,19 @@ export declare class GrafanaFolder {
1159
1159
  readonly uid: string;
1160
1160
  }
1161
1161
 
1162
+ export declare class GrafanaLibraryPanel {
1163
+ constructor(props: {
1164
+ /** GrafanaLibraryPanelSpec defines the desired state of GrafanaLibraryPanel */
1165
+ spec: Record<string, unknown>;
1166
+ /** Standard object's metadata. */
1167
+ metadata?: ObjectMeta;
1168
+ });
1169
+ readonly name: string;
1170
+ readonly namespace: string;
1171
+ readonly status: Record<string, unknown>;
1172
+ readonly uid: string;
1173
+ }
1174
+
1162
1175
  export declare class GRPCRoute {
1163
1176
  constructor(props: {
1164
1177
  /** Standard object's metadata. */
@@ -86,6 +86,7 @@ export const GitRepository = createResource("K8s::Flux::GitRepository", "k8s", {
86
86
  export const GrafanaDashboard = createResource("K8s::Grafana::GrafanaDashboard", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
87
87
  export const GrafanaDatasource = createResource("K8s::Grafana::GrafanaDatasource", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
88
88
  export const GrafanaFolder = createResource("K8s::Grafana::GrafanaFolder", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
89
+ export const GrafanaLibraryPanel = createResource("K8s::Grafana::GrafanaLibraryPanel", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
89
90
  export const GRPCRoute = createResource("K8s::Gateway::GRPCRoute", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
90
91
  export const HelmChartConfig = createResource("K8s::K3s::HelmChartConfig", "k8s", {"name":"name","namespace":"namespace","uid":"uid"});
91
92
  export const HelmChartProxy = createResource("K8s::Addons::HelmChartProxy", "k8s", {"name":"name","namespace":"namespace","uid":"uid","status":"status"});
@@ -461,6 +462,17 @@ export const GrafanaDatasource_Status = createProperty("K8s::Grafana::GrafanaDat
461
462
  export const GrafanaDatasource_ValuesFrom = createProperty("K8s::Grafana::GrafanaDatasource.valuesFrom", "k8s");
462
463
  export const GrafanaFolder_InstanceSelector = createProperty("K8s::Grafana::GrafanaFolder.instanceSelector", "k8s");
463
464
  export const GrafanaFolder_Status = createProperty("K8s::Grafana::GrafanaFolder.status", "k8s");
465
+ export const GrafanaLibraryPanel_ConfigMapRef = createProperty("K8s::Grafana::GrafanaLibraryPanel.configMapRef", "k8s");
466
+ export const GrafanaLibraryPanel_Datasource = createProperty("K8s::Grafana::GrafanaLibraryPanel.datasources", "k8s");
467
+ export const GrafanaLibraryPanel_Env = createProperty("K8s::Grafana::GrafanaLibraryPanel.envs", "k8s");
468
+ export const GrafanaLibraryPanel_EnvFrom = createProperty("K8s::Grafana::GrafanaLibraryPanel.envFrom", "k8s");
469
+ export const GrafanaLibraryPanel_GrafanaCom = createProperty("K8s::Grafana::GrafanaLibraryPanel.grafanaCom", "k8s");
470
+ export const GrafanaLibraryPanel_InstanceSelector = createProperty("K8s::Grafana::GrafanaLibraryPanel.instanceSelector", "k8s");
471
+ export const GrafanaLibraryPanel_JsonnetLib = createProperty("K8s::Grafana::GrafanaLibraryPanel.jsonnetLib", "k8s");
472
+ export const GrafanaLibraryPanel_Oci = createProperty("K8s::Grafana::GrafanaLibraryPanel.oci", "k8s");
473
+ export const GrafanaLibraryPanel_Plugin = createProperty("K8s::Grafana::GrafanaLibraryPanel.plugins", "k8s");
474
+ export const GrafanaLibraryPanel_Status = createProperty("K8s::Grafana::GrafanaLibraryPanel.status", "k8s");
475
+ export const GrafanaLibraryPanel_UrlAuthorization = createProperty("K8s::Grafana::GrafanaLibraryPanel.urlAuthorization", "k8s");
464
476
  export const GRPCRoute_ParentRef = createProperty("K8s::Gateway::GRPCRoute.parentRefs", "k8s");
465
477
  export const GRPCRoute_Rule = createProperty("K8s::Gateway::GRPCRoute.rules", "k8s");
466
478
  export const GRPCRoute_Status = createProperty("K8s::Gateway::GRPCRoute.status", "k8s");