@intentius/chant-lexicon-k8s 0.105.1 → 0.106.3

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.
@@ -9,7 +9,14 @@
9
9
  * JSON);
10
10
  * - a `monitoring.coreos.com` PrometheusRule's `spec.groups`, as the rule file
11
11
  * `{ groups }` those groups would make;
12
- * - a Grafana Operator `GrafanaDashboard`'s `spec.json`, as text (#3015).
12
+ * - a Grafana Operator `GrafanaDashboard`'s `spec.json`, as text (#3015);
13
+ * - the alerting content of the Grafana Operator's `GrafanaAlertRuleGroup`
14
+ * (`spec.rules`), `GrafanaContactPoint` (`spec.receivers`),
15
+ * `GrafanaNotificationPolicy` (`spec.route`), `GrafanaNotificationPolicyRoute`
16
+ * (the whole `spec`, offered as `route`), `GrafanaMuteTiming`
17
+ * (`spec.time_intervals`) and `GrafanaNotificationTemplate`
18
+ * (`spec.template`), each with the whole `spec` as the document so the
19
+ * owner can read the fields beside it (#3538).
13
20
  *
14
21
  * Which lexicon imports the content is decided by core at run time, from the
15
22
  * lexicons that register an `embeddedImporters()`; this module names none of
@@ -27,6 +34,15 @@ function isObject(v: unknown): v is Record<string, unknown> {
27
34
  /** The `grafana_dashboard` label the Grafana dashboard sidecar looks for (kube-prometheus-stack, the Grafana Helm chart). */
28
35
  export const GRAFANA_DASHBOARD_LABEL = "grafana_dashboard";
29
36
 
37
+ /** The Grafana Operator alerting kinds, and the `spec` field holding what the grafana lexicon imports. */
38
+ const GRAFANA_ALERTING_FIELDS: Record<string, { field: string; what: string }> = {
39
+ "K8s::Grafana::GrafanaAlertRuleGroup": { field: "rules", what: "Grafana alert rules" },
40
+ "K8s::Grafana::GrafanaContactPoint": { field: "receivers", what: "Grafana contact point receivers" },
41
+ "K8s::Grafana::GrafanaNotificationPolicy": { field: "route", what: "a Grafana notification policy" },
42
+ "K8s::Grafana::GrafanaMuteTiming": { field: "time_intervals", what: "Grafana mute timing intervals" },
43
+ "K8s::Grafana::GrafanaNotificationTemplate": { field: "template", what: "a Grafana notification template" },
44
+ };
45
+
30
46
  function looksLikeRuleGroups(groups: unknown): boolean {
31
47
  return Array.isArray(groups) && groups.length > 0 && groups.every((g) => isObject(g) && typeof g.name === "string" && Array.isArray(g.rules));
32
48
  }
@@ -116,6 +132,39 @@ export function delegateEmbedded(
116
132
  return;
117
133
  }
118
134
 
135
+ // A GrafanaNotificationPolicyRoute's spec is the route itself, so the whole spec is offered (as `route`) and replaced.
136
+ if (type === "K8s::Grafana::GrafanaNotificationPolicyRoute" && isObject(properties.spec) && typeof properties.spec.receiver === "string") {
137
+ const ref = embedded.resolve({
138
+ host: "k8s",
139
+ hostType: type,
140
+ location: `${kind} ${name} spec`,
141
+ directory: name,
142
+ document: { route: properties.spec },
143
+ select: "route",
144
+ labels,
145
+ expectedOwner: { lexicon: "grafana", what: "a Grafana notification policy route" },
146
+ });
147
+ if (ref) properties.spec = ref as unknown as Record<string, unknown>;
148
+ return;
149
+ }
150
+
151
+ const alerting = GRAFANA_ALERTING_FIELDS[type];
152
+ if (alerting && isObject(properties.spec) && properties.spec[alerting.field] !== undefined) {
153
+ const spec = properties.spec;
154
+ const ref = embedded.resolve({
155
+ host: "k8s",
156
+ hostType: type,
157
+ location: `${kind} ${name} spec.${alerting.field}`,
158
+ directory: name,
159
+ document: spec,
160
+ select: alerting.field,
161
+ labels,
162
+ expectedOwner: { lexicon: "grafana", what: alerting.what },
163
+ });
164
+ if (ref) properties.spec = { ...spec, [alerting.field]: ref };
165
+ return;
166
+ }
167
+
119
168
  if (type === "K8s::Monitoring::PrometheusRule" && isObject(properties.spec) && Array.isArray(properties.spec.groups)) {
120
169
  const groups = properties.spec.groups;
121
170
  const ref = embedded.resolve({
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Grafana Operator alerting through `chant import` (#3538): the output of
3
+ * `GrafanaOperatorResources` (#3156) for a set of alerting declarations,
4
+ * imported as grafana declarations, builds back to the same resources, and
5
+ * the declarations build the same alerting provisioning file.
6
+ *
7
+ * The manifest is written by `GrafanaOperatorResources` itself, so the test
8
+ * holds the writer and the reader to each other. A rule group's folder is
9
+ * the one thing that changes on the way: the resource names its
10
+ * GrafanaFolder and the declaration wants the folder's title, so the
11
+ * provisioning comparison puts the folder name in the source's `folder`.
12
+ */
13
+
14
+ import { describe, expect, test } from "vitest";
15
+ import { load, loadAll } from "js-yaml";
16
+ import { build } from "@intentius/chant/build";
17
+ import { expandComposite } from "@intentius/chant/composite";
18
+ import type { SerializerResult } from "@intentius/chant/serializer";
19
+ import {
20
+ AlertRule,
21
+ AlertRuleGroup,
22
+ ALERTING_FILE,
23
+ ContactPoint,
24
+ Datasource,
25
+ MuteTiming,
26
+ NotificationPolicy,
27
+ NotificationTemplate,
28
+ PromQuery,
29
+ grafanaSerializer,
30
+ } from "@intentius/chant-lexicon-grafana";
31
+ import { buildGrafana } from "@intentius/chant-lexicon-grafana/build";
32
+ import { normalizeAlerting } from "@intentius/chant-lexicon-grafana/import/normalize-alerting";
33
+ import { GrafanaOperatorResources } from "@intentius/chant-lexicon-grafana/k8s";
34
+ import { k8sSerializer } from "../serializer";
35
+ import { importManifest, removeDir } from "./testdata/embedded/fixtures";
36
+
37
+ type Json = Record<string, unknown>;
38
+
39
+ const prometheus = new Datasource({ name: "Prometheus", type: "prometheus", url: "http://prometheus:9090" });
40
+ const oncall = new ContactPoint({
41
+ name: "oncall",
42
+ receivers: [
43
+ { uid: "oncall-slack", type: "slack", settings: { url: "${SLACK_URL}", title: "chant" } },
44
+ { uid: "oncall-mail", type: "email", settings: { addresses: "a@example.com" }, disableResolveMessage: true },
45
+ ],
46
+ });
47
+ const weekends = new MuteTiming({ name: "weekends", time_intervals: [{ weekdays: ["saturday", "sunday"] }] });
48
+ const template = new NotificationTemplate({ name: "t", template: '{{ define "t" }}x{{ end }}' });
49
+ const policy = new NotificationPolicy({
50
+ receiver: oncall,
51
+ group_by: ["alertname"],
52
+ routes: [{ receiver: "tickets", matchers: ['severity="ticket"', 'team=~"a|b"'], mute_time_intervals: [weekends], routes: [{ matchers: ['env!="dev"'] }] }],
53
+ });
54
+ const errors = new AlertRule({
55
+ title: "High errors",
56
+ data: [new PromQuery({ datasource: prometheus, expr: "up" })],
57
+ dashboardUid: "dash1",
58
+ panelId: 2,
59
+ for: "5m",
60
+ labels: { severity: "page" },
61
+ });
62
+ const fewSeries = new AlertRule({
63
+ title: "Few series",
64
+ data: [new PromQuery({ datasource: prometheus, expr: "count(up)" })],
65
+ missing_series_evals_to_resolve: 3,
66
+ notification_settings: { receiver: oncall, group_by: ["alertname"] },
67
+ });
68
+ const group = new AlertRuleGroup({ name: "errors", folder: "Alerts", interval: "30s", rules: [errors, fewSeries] });
69
+ const alerting = [oncall, weekends, template, policy, group];
70
+ const entities = [prometheus, ...alerting];
71
+
72
+ const KINDS = ["GrafanaAlertRuleGroup", "GrafanaContactPoint", "GrafanaNotificationPolicy", "GrafanaMuteTiming", "GrafanaNotificationTemplate"];
73
+
74
+ function primary(out: string | SerializerResult | undefined): string {
75
+ if (out === undefined) return "";
76
+ return typeof out === "string" ? out : out.primary;
77
+ }
78
+
79
+ function manifest(policyRoutes = false): string {
80
+ const instance = GrafanaOperatorResources({
81
+ entities: entities as never,
82
+ instanceSelector: { matchLabels: { dashboards: "grafana" } },
83
+ secretName: "grafana-secrets",
84
+ namespace: "monitoring",
85
+ policyRoutes,
86
+ });
87
+ return primary(k8sSerializer.serialize(expandComposite("grafana", instance)));
88
+ }
89
+
90
+ function find(docs: Json[], kind: string): Json {
91
+ const doc = docs.find((d) => d.kind === kind);
92
+ if (!doc) throw new Error(`no ${kind}`);
93
+ return doc;
94
+ }
95
+
96
+ describe("GrafanaOperatorResources -> chant import -> chant build", () => {
97
+ test("the five alerting kinds are imported as grafana declarations and build back to the same resources", async () => {
98
+ const yaml = manifest();
99
+ const input = (loadAll(yaml) as Json[]).filter((d) => d);
100
+ expect(KINDS.every((k) => input.some((d) => d.kind === k))).toBe(true);
101
+
102
+ const imported = await importManifest(yaml);
103
+ try {
104
+ expect(imported.result.error).toBeUndefined();
105
+ expect(imported.result.success).toBe(true);
106
+
107
+ // Each field the grafana lexicon reads is a call over its declarations.
108
+ const main = imported.files["other.ts"];
109
+ expect(main).toContain('from "@intentius/chant-lexicon-grafana/k8s"');
110
+ for (const fn of ["operatorRules", "operatorPolicy", "operatorTimeIntervals", "operatorTemplate"]) expect(main).toContain(`${fn}(`);
111
+ // The contact point reads a Secret, so its receivers come from a module naming it.
112
+ const receivers = imported.files["grafana-contact-point-oncall/receivers.ts"];
113
+ expect(receivers).toContain("operatorReceivers(");
114
+ expect(receivers).toContain('"grafana-secrets"');
115
+ expect(imported.files["grafana-contact-point-oncall/notifications.ts"]).toContain("${SLACK_URL}");
116
+ expect(imported.files["grafana-rule-group-alerts-errors/alert-rules.ts"]).toContain("new AlertRuleGroup(");
117
+ expect(imported.files["grafana-notification-policy/notifications.ts"]).toContain("new NotificationPolicy(");
118
+ expect(imported.result.warnings.join("\n")).toContain('rule group "errors"');
119
+
120
+ const result = await build(imported.srcDir, [k8sSerializer, grafanaSerializer]);
121
+ expect(result.errors).toEqual([]);
122
+
123
+ const output = (loadAll(primary(result.outputs.get("k8s"))) as Json[]).filter((d) => d);
124
+ for (const kind of KINDS) expect(find(output, kind)).toEqual(find(input, kind));
125
+
126
+ // The declarations build the alerting file the source declares.
127
+ const expected = buildGrafana(entities as never).alerting!;
128
+ const groups = (expected.groups ?? []).map((g) => ({ ...g, folder: "grafana-folder-alerts" }));
129
+ const text = (result.outputs.get("grafana") as SerializerResult | undefined)?.files?.[ALERTING_FILE];
130
+ expect(text).toBeDefined();
131
+ expect(normalizeAlerting(load(text!) as Json)).toEqual(normalizeAlerting({ ...expected, groups } as unknown as Json));
132
+ } finally {
133
+ removeDir(imported.dir);
134
+ }
135
+ });
136
+
137
+ test("a policy route is imported as a declaration and builds back to the same resource, its policy kept as written", async () => {
138
+ const yaml = manifest(true);
139
+ const input = (loadAll(yaml) as Json[]).filter((d) => d);
140
+ const route = find(input, "GrafanaNotificationPolicyRoute");
141
+
142
+ const imported = await importManifest(yaml);
143
+ try {
144
+ expect(imported.result.error).toBeUndefined();
145
+ expect(imported.result.success).toBe(true);
146
+ expect(imported.files["other.ts"]).toContain("operatorRouteSpec(");
147
+ expect(imported.files["grafana-notification-policy-route-1/notifications.ts"]).toContain("new NotificationPolicy(");
148
+
149
+ const result = await build(imported.srcDir, [k8sSerializer, grafanaSerializer]);
150
+ expect(result.errors).toEqual([]);
151
+ const output = (loadAll(primary(result.outputs.get("k8s"))) as Json[]).filter((d) => d);
152
+ expect(find(output, "GrafanaNotificationPolicyRoute")).toEqual(route);
153
+ expect(find(output, "GrafanaNotificationPolicy")).toEqual(find(input, "GrafanaNotificationPolicy"));
154
+ } finally {
155
+ removeDir(imported.dir);
156
+ }
157
+ });
158
+ });
@@ -2645,51 +2645,51 @@ data:
2645
2645
  rules:
2646
2646
  - record: slo:sli_error:ratio_rate5m
2647
2647
  expr: |-
2648
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[5m])))
2648
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[5m]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[5m]))) > 0))
2649
2649
  /
2650
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[5m])))
2650
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[5m]))) > 0)
2651
2651
  labels:
2652
2652
  slo: support-agent-runs
2653
2653
  - record: slo:sli_error:ratio_rate30m
2654
2654
  expr: |-
2655
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[30m])))
2655
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[30m]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[30m]))) > 0))
2656
2656
  /
2657
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[30m])))
2657
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[30m]))) > 0)
2658
2658
  labels:
2659
2659
  slo: support-agent-runs
2660
2660
  - record: slo:sli_error:ratio_rate1h
2661
2661
  expr: |-
2662
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[1h])))
2662
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[1h]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1h]))) > 0))
2663
2663
  /
2664
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1h])))
2664
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1h]))) > 0)
2665
2665
  labels:
2666
2666
  slo: support-agent-runs
2667
2667
  - record: slo:sli_error:ratio_rate2h
2668
2668
  expr: |-
2669
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[2h])))
2669
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[2h]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[2h]))) > 0))
2670
2670
  /
2671
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[2h])))
2671
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[2h]))) > 0)
2672
2672
  labels:
2673
2673
  slo: support-agent-runs
2674
2674
  - record: slo:sli_error:ratio_rate6h
2675
2675
  expr: |-
2676
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[6h])))
2676
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[6h]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[6h]))) > 0))
2677
2677
  /
2678
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[6h])))
2678
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[6h]))) > 0)
2679
2679
  labels:
2680
2680
  slo: support-agent-runs
2681
2681
  - record: slo:sli_error:ratio_rate1d
2682
2682
  expr: |-
2683
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[1d])))
2683
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[1d]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1d]))) > 0))
2684
2684
  /
2685
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1d])))
2685
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[1d]))) > 0)
2686
2686
  labels:
2687
2687
  slo: support-agent-runs
2688
2688
  - record: slo:sli_error:ratio_rate3d
2689
2689
  expr: |-
2690
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[3d])))
2690
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support",status_code="STATUS_CODE_ERROR"}[3d]))) or 0 * ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[3d]))) > 0))
2691
2691
  /
2692
- (sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[3d])))
2692
+ ((sum(rate(traces_span_metrics_calls_total{service_name="support-agent",span_name="invoke_agent support"}[3d]))) > 0)
2693
2693
  labels:
2694
2694
  slo: support-agent-runs
2695
2695
  - record: slo:sli_error:ratio_rate28d