@backstage-community/plugin-grafana 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @backstage-community/plugin-grafana
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 48dbddf: Initial plugin version. It's a copy of its original [repo](https://github.com/K-Phoen/backstage-plugin-grafana)
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # Grafana plugin for Backstage
2
+
3
+ The Grafana plugin is a frontend plugin that lists Grafana alerts and dashboards. It includes two components that can be integrated into Backstage:
4
+
5
+ - The `EntityGrafanaDashboardsCard` component which can display dashboards for a specific entity
6
+ - The `EntityGrafanaAlertsCard` component which can display recent alerts for a specific entity
7
+ - The `EntityOverviewDashboardViewer` component which can embed an "overview" dashboard for a specific entity
8
+ - The `DashboardViewer` component which can embed any dashboard
9
+
10
+ ## Setup
11
+
12
+ Find [installation instructions](./docs/index.md#installation) in our documentation.
13
+
14
+ ## How does it look?
15
+
16
+ Entity alerts card:
17
+
18
+ ![Alerts card](./docs/alerts_card.png)
19
+
20
+ Entity dashboards card:
21
+
22
+ ![Dashboards card](./docs/dashboards_card.png)
23
+
24
+ ## Special thanks & Disclaimer
25
+
26
+ Thanks to K-Phoen for creating the grafana plugin found [here](https://github.com/K-Phoen/backstage-plugin-grafana). As an outcome
27
+ of [this discussion](https://github.com/K-Phoen/backstage-plugin-grafana/issues/78), he gave us permission to keep working on this plugin.
package/config.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ /*
2
+ * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ export interface Config {
18
+ grafana: {
19
+ /**
20
+ * Domain used by users to access Grafana web UI.
21
+ * Example: https://monitoring.eu.my-company.com/
22
+ * @visibility frontend
23
+ */
24
+ domain: string;
25
+
26
+ /**
27
+ * Path to use for requests via the proxy, defaults to /grafana/api
28
+ * @visibility frontend
29
+ */
30
+ proxyPath?: string;
31
+
32
+ /**
33
+ * Is Grafana using unified alerting?
34
+ * @visibility frontend
35
+ */
36
+ unifiedAlerting?: boolean;
37
+ };
38
+ }
@@ -0,0 +1,187 @@
1
+ import { createApiRef } from '@backstage/core-plugin-api';
2
+ import { QueryEvaluator } from './query/QueryEvaluator.esm.js';
3
+
4
+ var __defProp = Object.defineProperty;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __publicField = (obj, key, value) => {
7
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ return value;
9
+ };
10
+ const grafanaApiRef = createApiRef({
11
+ id: "plugin.grafana.service"
12
+ });
13
+ const DEFAULT_PROXY_PATH = "/grafana/api";
14
+ const isSingleWord = (input) => {
15
+ return input.match(/^[\w-]+$/g) !== null;
16
+ };
17
+ class Client {
18
+ constructor(opts) {
19
+ __publicField(this, "discoveryApi");
20
+ __publicField(this, "fetchApi");
21
+ __publicField(this, "proxyPath");
22
+ __publicField(this, "queryEvaluator");
23
+ var _a;
24
+ this.discoveryApi = opts.discoveryApi;
25
+ this.fetchApi = opts.fetchApi;
26
+ this.proxyPath = (_a = opts.proxyPath) != null ? _a : DEFAULT_PROXY_PATH;
27
+ this.queryEvaluator = new QueryEvaluator();
28
+ }
29
+ async fetch(input, init) {
30
+ const apiUrl = await this.apiUrl();
31
+ const resp = await this.fetchApi.fetch(`${apiUrl}${input}`, init);
32
+ if (!resp.ok) {
33
+ throw new Error(`Request failed with ${resp.status} ${resp.statusText}`);
34
+ }
35
+ return await resp.json();
36
+ }
37
+ async listDashboards(domain, query) {
38
+ if (isSingleWord(query)) {
39
+ return this.dashboardsByTag(domain, query);
40
+ }
41
+ return this.dashboardsForQuery(domain, query);
42
+ }
43
+ async dashboardsForQuery(domain, query) {
44
+ const parsedQuery = this.queryEvaluator.parse(query);
45
+ const response = await this.fetch(`/api/search?type=dash-db`);
46
+ const allDashboards = this.fullyQualifiedDashboardURLs(domain, response);
47
+ return allDashboards.filter((dashboard) => {
48
+ return this.queryEvaluator.evaluate(parsedQuery, dashboard) === true;
49
+ });
50
+ }
51
+ async dashboardsByTag(domain, tag) {
52
+ const response = await this.fetch(
53
+ `/api/search?type=dash-db&tag=${tag}`
54
+ );
55
+ return this.fullyQualifiedDashboardURLs(domain, response);
56
+ }
57
+ fullyQualifiedDashboardURLs(domain, dashboards) {
58
+ return dashboards.map((dashboard) => ({
59
+ ...dashboard,
60
+ url: domain + dashboard.url,
61
+ folderUrl: domain + dashboard.folderUrl
62
+ }));
63
+ }
64
+ async apiUrl() {
65
+ const proxyUrl = await this.discoveryApi.getBaseUrl("proxy");
66
+ return proxyUrl + this.proxyPath;
67
+ }
68
+ }
69
+ class GrafanaApiClient {
70
+ constructor(opts) {
71
+ __publicField(this, "domain");
72
+ __publicField(this, "client");
73
+ this.domain = opts.domain;
74
+ this.client = new Client(opts);
75
+ }
76
+ async listDashboards(query) {
77
+ return this.client.listDashboards(this.domain, query);
78
+ }
79
+ async alertsForSelector(dashboardTag) {
80
+ const response = await this.client.fetch(
81
+ `/api/alerts?dashboardTag=${dashboardTag}`
82
+ );
83
+ return response.map((alert) => ({
84
+ name: alert.name,
85
+ state: alert.state,
86
+ matchingSelector: dashboardTag,
87
+ url: `${this.domain}${alert.url}?panelId=${alert.panelId}&fullscreen&refresh=30s`
88
+ }));
89
+ }
90
+ }
91
+ class UnifiedAlertingGrafanaApiClient {
92
+ constructor(opts) {
93
+ __publicField(this, "domain");
94
+ __publicField(this, "client");
95
+ this.domain = opts.domain;
96
+ this.client = new Client(opts);
97
+ }
98
+ async listDashboards(query) {
99
+ return this.client.listDashboards(this.domain, query);
100
+ }
101
+ async alertsForSelector(selectors) {
102
+ let labelSelectors = [];
103
+ if (typeof selectors === "string") {
104
+ labelSelectors = [selectors];
105
+ } else {
106
+ labelSelectors = selectors;
107
+ }
108
+ const rulesResponse = await this.client.fetch("/api/ruler/grafana/api/v1/rules");
109
+ const rules = Object.values(rulesResponse).flat().map((ruleGroup) => ruleGroup.rules).flat();
110
+ const alertsResponse = await this.client.fetch(
111
+ "/api/prometheus/grafana/api/v1/alerts"
112
+ );
113
+ return labelSelectors.map((selector) => {
114
+ const [label, labelValue] = selector.split("=");
115
+ const matchingRules = rules.filter(
116
+ (rule) => rule.labels && rule.labels[label] === labelValue
117
+ );
118
+ const alertInstances = alertsResponse.data.alerts.filter(
119
+ (alertInstance) => alertInstance.labels[label] === labelValue
120
+ );
121
+ return matchingRules.map((rule) => {
122
+ const matchingAlertInstances = alertInstances.filter(
123
+ (alertInstance) => alertInstance.labels.alertname === rule.grafana_alert.title
124
+ );
125
+ const aggregatedAlertStates = matchingAlertInstances.reduce(
126
+ (previous, alert) => {
127
+ switch (alert.state) {
128
+ case "Normal":
129
+ previous.Normal += 1;
130
+ break;
131
+ case "Pending":
132
+ previous.Pending += 1;
133
+ break;
134
+ case "Alerting":
135
+ previous.Alerting += 1;
136
+ break;
137
+ case "NoData":
138
+ previous.NoData += 1;
139
+ break;
140
+ case "Error":
141
+ previous.Error += 1;
142
+ break;
143
+ default:
144
+ previous.Invalid += 1;
145
+ }
146
+ return previous;
147
+ },
148
+ {
149
+ Normal: 0,
150
+ Pending: 0,
151
+ Alerting: 0,
152
+ NoData: 0,
153
+ Error: 0,
154
+ Invalid: 0
155
+ }
156
+ );
157
+ return {
158
+ name: rule.grafana_alert.title,
159
+ url: `${this.domain}/alerting/grafana/${rule.grafana_alert.uid}/view`,
160
+ matchingSelector: selector,
161
+ state: this.getState(
162
+ aggregatedAlertStates,
163
+ matchingAlertInstances.length
164
+ )
165
+ };
166
+ });
167
+ }).flat();
168
+ }
169
+ getState(states, totalAlerts) {
170
+ if (states.Alerting > 0) {
171
+ return "Alerting";
172
+ } else if (states.Error > 0) {
173
+ return "Error";
174
+ } else if (states.Pending > 0) {
175
+ return "Pending";
176
+ }
177
+ if (states.NoData === totalAlerts) {
178
+ return "NoData";
179
+ } else if (states.Normal === totalAlerts || states.Normal + states.NoData === totalAlerts) {
180
+ return "Normal";
181
+ }
182
+ return "n/a";
183
+ }
184
+ }
185
+
186
+ export { GrafanaApiClient, UnifiedAlertingGrafanaApiClient, grafanaApiRef };
187
+ //# sourceMappingURL=api.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.esm.js","sources":["../src/api.ts"],"sourcesContent":["/*\n * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createApiRef,\n DiscoveryApi,\n FetchApi,\n} from '@backstage/core-plugin-api';\nimport { QueryEvaluator } from './query';\nimport { Alert, Dashboard } from './types';\n\n/**\n * Interface for the Grafana API\n * @public\n */\nexport interface GrafanaApi {\n /**\n * Returns the found dashboards in Grafana with the defined query\n * @param query - The query used to list the dashboards\n */\n listDashboards(query: string): Promise<Dashboard[]>;\n /**\n * Returns a list of alerts found in Grafana that have any of the defined alert selectors\n * @param selectors - One or multiple alert selectors\n */\n alertsForSelector(selectors: string | string[]): Promise<Alert[]>;\n}\n\ninterface AggregatedAlertState {\n Normal: number;\n Pending: number;\n Alerting: number;\n NoData: number;\n Error: number;\n Invalid: number;\n}\n\ntype AlertState =\n | 'Normal'\n | 'Pending'\n | 'Alerting'\n | 'NoData'\n | 'Error'\n | 'n/a';\n\ninterface AlertInstance {\n labels: Record<string, string>;\n state: AlertState;\n}\n\ninterface AlertsData {\n data: { alerts: AlertInstance[] };\n}\n\ninterface AlertRuleGroupConfig {\n name: string;\n rules: AlertRule[];\n}\n\ninterface GrafanaAlert {\n id: number;\n panelId: number;\n name: string;\n state: string;\n url: string;\n}\n\ninterface UnifiedGrafanaAlert {\n uid: string;\n title: string;\n}\n\ninterface AlertRule {\n labels: Record<string, string>;\n grafana_alert: UnifiedGrafanaAlert;\n}\n\n/**\n * The grafana API reference\n * @public\n */\nexport const grafanaApiRef = createApiRef<GrafanaApi>({\n id: 'plugin.grafana.service',\n});\n\nexport type Options = {\n discoveryApi: DiscoveryApi;\n fetchApi: FetchApi;\n\n /**\n * Domain used by users to access Grafana web UI.\n * Example: https://monitoring.my-company.com/\n */\n domain: string;\n\n /**\n * Path to use for requests via the proxy, defaults to /grafana/api\n */\n proxyPath?: string;\n};\n\nconst DEFAULT_PROXY_PATH = '/grafana/api';\n\nconst isSingleWord = (input: string): boolean => {\n return input.match(/^[\\w-]+$/g) !== null;\n};\n\nclass Client {\n private readonly discoveryApi: DiscoveryApi;\n private readonly fetchApi: FetchApi;\n private readonly proxyPath: string;\n private readonly queryEvaluator: QueryEvaluator;\n\n constructor(opts: Options) {\n this.discoveryApi = opts.discoveryApi;\n this.fetchApi = opts.fetchApi;\n this.proxyPath = opts.proxyPath ?? DEFAULT_PROXY_PATH;\n this.queryEvaluator = new QueryEvaluator();\n }\n\n public async fetch<T = any>(input: string, init?: RequestInit): Promise<T> {\n const apiUrl = await this.apiUrl();\n const resp = await this.fetchApi.fetch(`${apiUrl}${input}`, init);\n if (!resp.ok) {\n throw new Error(`Request failed with ${resp.status} ${resp.statusText}`);\n }\n\n return await resp.json();\n }\n\n async listDashboards(domain: string, query: string): Promise<Dashboard[]> {\n if (isSingleWord(query)) {\n return this.dashboardsByTag(domain, query);\n }\n\n return this.dashboardsForQuery(domain, query);\n }\n\n async dashboardsForQuery(\n domain: string,\n query: string,\n ): Promise<Dashboard[]> {\n const parsedQuery = this.queryEvaluator.parse(query);\n const response = await this.fetch<Dashboard[]>(`/api/search?type=dash-db`);\n const allDashboards = this.fullyQualifiedDashboardURLs(domain, response);\n\n return allDashboards.filter(dashboard => {\n return this.queryEvaluator.evaluate(parsedQuery, dashboard) === true;\n });\n }\n\n async dashboardsByTag(domain: string, tag: string): Promise<Dashboard[]> {\n const response = await this.fetch<Dashboard[]>(\n `/api/search?type=dash-db&tag=${tag}`,\n );\n\n return this.fullyQualifiedDashboardURLs(domain, response);\n }\n\n private fullyQualifiedDashboardURLs(\n domain: string,\n dashboards: Dashboard[],\n ): Dashboard[] {\n return dashboards.map(dashboard => ({\n ...dashboard,\n url: domain + dashboard.url,\n folderUrl: domain + dashboard.folderUrl,\n }));\n }\n\n private async apiUrl() {\n const proxyUrl = await this.discoveryApi.getBaseUrl('proxy');\n return proxyUrl + this.proxyPath;\n }\n}\n\nexport class GrafanaApiClient implements GrafanaApi {\n private readonly domain: string;\n private readonly client: Client;\n\n constructor(opts: Options) {\n this.domain = opts.domain;\n this.client = new Client(opts);\n }\n\n async listDashboards(query: string): Promise<Dashboard[]> {\n return this.client.listDashboards(this.domain, query);\n }\n\n async alertsForSelector(dashboardTag: string): Promise<Alert[]> {\n const response = await this.client.fetch<GrafanaAlert[]>(\n `/api/alerts?dashboardTag=${dashboardTag}`,\n );\n\n return response.map(alert => ({\n name: alert.name,\n state: alert.state,\n matchingSelector: dashboardTag,\n url: `${this.domain}${alert.url}?panelId=${alert.panelId}&fullscreen&refresh=30s`,\n }));\n }\n}\n\nexport class UnifiedAlertingGrafanaApiClient implements GrafanaApi {\n private readonly domain: string;\n private readonly client: Client;\n\n constructor(opts: Options) {\n this.domain = opts.domain;\n this.client = new Client(opts);\n }\n\n async listDashboards(query: string): Promise<Dashboard[]> {\n return this.client.listDashboards(this.domain, query);\n }\n\n async alertsForSelector(selectors: string | string[]): Promise<Alert[]> {\n let labelSelectors: string[] = [];\n if (typeof selectors === 'string') {\n labelSelectors = [selectors];\n } else {\n labelSelectors = selectors;\n }\n\n const rulesResponse = await this.client.fetch<\n Record<string, AlertRuleGroupConfig[]>\n >('/api/ruler/grafana/api/v1/rules');\n const rules = Object.values(rulesResponse)\n .flat()\n .map(ruleGroup => ruleGroup.rules)\n .flat();\n const alertsResponse = await this.client.fetch<AlertsData>(\n '/api/prometheus/grafana/api/v1/alerts',\n );\n\n return labelSelectors\n .map(selector => {\n const [label, labelValue] = selector.split('=');\n\n const matchingRules = rules.filter(\n rule => rule.labels && rule.labels[label] === labelValue,\n );\n const alertInstances = alertsResponse.data.alerts.filter(\n alertInstance => alertInstance.labels[label] === labelValue,\n );\n\n return matchingRules.map(rule => {\n const matchingAlertInstances = alertInstances.filter(\n alertInstance =>\n alertInstance.labels.alertname === rule.grafana_alert.title,\n );\n\n const aggregatedAlertStates: AggregatedAlertState =\n matchingAlertInstances.reduce(\n (previous, alert) => {\n switch (alert.state) {\n case 'Normal':\n previous.Normal += 1;\n break;\n case 'Pending':\n previous.Pending += 1;\n break;\n case 'Alerting':\n previous.Alerting += 1;\n break;\n case 'NoData':\n previous.NoData += 1;\n break;\n case 'Error':\n previous.Error += 1;\n break;\n default:\n previous.Invalid += 1;\n }\n\n return previous;\n },\n {\n Normal: 0,\n Pending: 0,\n Alerting: 0,\n NoData: 0,\n Error: 0,\n Invalid: 0,\n },\n );\n\n return {\n name: rule.grafana_alert.title,\n url: `${this.domain}/alerting/grafana/${rule.grafana_alert.uid}/view`,\n matchingSelector: selector,\n state: this.getState(\n aggregatedAlertStates,\n matchingAlertInstances.length,\n ),\n };\n });\n })\n .flat();\n }\n\n private getState(\n states: AggregatedAlertState,\n totalAlerts: number,\n ): AlertState {\n if (states.Alerting > 0) {\n return 'Alerting';\n } else if (states.Error > 0) {\n return 'Error';\n } else if (states.Pending > 0) {\n return 'Pending';\n }\n if (states.NoData === totalAlerts) {\n return 'NoData';\n } else if (\n states.Normal === totalAlerts ||\n states.Normal + states.NoData === totalAlerts\n ) {\n return 'Normal';\n }\n\n return 'n/a';\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AA8FO,MAAM,gBAAgB,YAAyB,CAAA;AAAA,EACpD,EAAI,EAAA,wBAAA;AACN,CAAC,EAAA;AAkBD,MAAM,kBAAqB,GAAA,cAAA,CAAA;AAE3B,MAAM,YAAA,GAAe,CAAC,KAA2B,KAAA;AAC/C,EAAO,OAAA,KAAA,CAAM,KAAM,CAAA,WAAW,CAAM,KAAA,IAAA,CAAA;AACtC,CAAA,CAAA;AAEA,MAAM,MAAO,CAAA;AAAA,EAMX,YAAY,IAAe,EAAA;AAL3B,IAAiB,aAAA,CAAA,IAAA,EAAA,cAAA,CAAA,CAAA;AACjB,IAAiB,aAAA,CAAA,IAAA,EAAA,UAAA,CAAA,CAAA;AACjB,IAAiB,aAAA,CAAA,IAAA,EAAA,WAAA,CAAA,CAAA;AACjB,IAAiB,aAAA,CAAA,IAAA,EAAA,gBAAA,CAAA,CAAA;AA5HnB,IAAA,IAAA,EAAA,CAAA;AA+HI,IAAA,IAAA,CAAK,eAAe,IAAK,CAAA,YAAA,CAAA;AACzB,IAAA,IAAA,CAAK,WAAW,IAAK,CAAA,QAAA,CAAA;AACrB,IAAK,IAAA,CAAA,SAAA,GAAA,CAAY,EAAK,GAAA,IAAA,CAAA,SAAA,KAAL,IAAkB,GAAA,EAAA,GAAA,kBAAA,CAAA;AACnC,IAAK,IAAA,CAAA,cAAA,GAAiB,IAAI,cAAe,EAAA,CAAA;AAAA,GAC3C;AAAA,EAEA,MAAa,KAAe,CAAA,KAAA,EAAe,IAAgC,EAAA;AACzE,IAAM,MAAA,MAAA,GAAS,MAAM,IAAA,CAAK,MAAO,EAAA,CAAA;AACjC,IAAM,MAAA,IAAA,GAA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EAAA;AACjC,MAAO,OAAA,QAAA,CAAA;AAAA,KACT,MAAA,IACE,OAAO,MAAW,KAAA,WAAA,IAClB,OAAO,MAAS,GAAA,MAAA,CAAO,WAAW,WAClC,EAAA;AACA,MAAO,OAAA,QAAA,CAAA;AAAA,KACT;AAEA,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AACF;;;;"}
@@ -0,0 +1,113 @@
1
+ import React from 'react';
2
+ import { Progress, Table, Link, StatusAborted, StatusError, StatusWarning, StatusPending, StatusOK } from '@backstage/core-components';
3
+ import { useEntity, MissingAnnotationEmptyState } from '@backstage/plugin-catalog-react';
4
+ import { useApi, configApiRef } from '@backstage/core-plugin-api';
5
+ import { grafanaApiRef } from '../../api.esm.js';
6
+ import useAsync from 'react-use/lib/useAsync';
7
+ import { Alert } from '@material-ui/lab';
8
+ import { isDashboardSelectorAvailable, GRAFANA_ANNOTATION_TAG_SELECTOR, isAlertSelectorAvailable, GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR, alertSelectorFromEntity, tagSelectorFromEntity } from '../../constants.esm.js';
9
+
10
+ const AlertStatusBadge = ({ alert }) => {
11
+ let statusElmt;
12
+ switch (alert.state) {
13
+ case "ok":
14
+ case "Normal":
15
+ statusElmt = /* @__PURE__ */ React.createElement(StatusOK, null);
16
+ break;
17
+ case "paused":
18
+ case "Pending":
19
+ statusElmt = /* @__PURE__ */ React.createElement(StatusPending, null);
20
+ break;
21
+ case "no_data":
22
+ case "pending":
23
+ case "NoData":
24
+ statusElmt = /* @__PURE__ */ React.createElement(StatusWarning, null);
25
+ break;
26
+ case "alerting":
27
+ case "Alerting":
28
+ case "Error":
29
+ statusElmt = /* @__PURE__ */ React.createElement(StatusError, null);
30
+ break;
31
+ default:
32
+ statusElmt = /* @__PURE__ */ React.createElement(StatusAborted, null);
33
+ }
34
+ return /* @__PURE__ */ React.createElement("div", null, statusElmt);
35
+ };
36
+ const AlertsTable = ({
37
+ alerts,
38
+ opts
39
+ }) => {
40
+ var _a, _b, _c, _d;
41
+ const columns = [
42
+ {
43
+ title: "Name",
44
+ field: "name",
45
+ cellStyle: { width: "90%" },
46
+ render: (row) => /* @__PURE__ */ React.createElement(Link, { to: row.url, target: "_blank", rel: "noopener" }, row.name)
47
+ }
48
+ ];
49
+ if (opts.showState) {
50
+ columns.push({
51
+ title: "State",
52
+ render: (row) => /* @__PURE__ */ React.createElement(AlertStatusBadge, { alert: row })
53
+ });
54
+ }
55
+ return /* @__PURE__ */ React.createElement(
56
+ Table,
57
+ {
58
+ title: opts.title || "Alerts",
59
+ options: {
60
+ paging: (_a = opts.paged) != null ? _a : false,
61
+ pageSize: (_b = opts.pageSize) != null ? _b : 5,
62
+ search: (_c = opts.searchable) != null ? _c : false,
63
+ emptyRowsWhenPaging: false,
64
+ sorting: (_d = opts.sortable) != null ? _d : false,
65
+ draggable: false,
66
+ padding: "dense"
67
+ },
68
+ data: alerts,
69
+ columns
70
+ }
71
+ );
72
+ };
73
+ const Alerts = ({ entity, opts }) => {
74
+ const grafanaApi = useApi(grafanaApiRef);
75
+ const configApi = useApi(configApiRef);
76
+ const unifiedAlertingEnabled = configApi.getOptionalBoolean("grafana.unifiedAlerting") || false;
77
+ const alertSelector = unifiedAlertingEnabled ? alertSelectorFromEntity(entity) : tagSelectorFromEntity(entity);
78
+ const { value, loading, error } = useAsync(
79
+ async () => await grafanaApi.alertsForSelector(alertSelector)
80
+ );
81
+ if (loading) {
82
+ return /* @__PURE__ */ React.createElement(Progress, null);
83
+ } else if (error) {
84
+ return /* @__PURE__ */ React.createElement(Alert, { severity: "error" }, error.message);
85
+ }
86
+ return /* @__PURE__ */ React.createElement(AlertsTable, { alerts: value || [], opts });
87
+ };
88
+ const AlertsCard = (opts) => {
89
+ const { entity } = useEntity();
90
+ const configApi = useApi(configApiRef);
91
+ const unifiedAlertingEnabled = configApi.getOptionalBoolean("grafana.unifiedAlerting") || false;
92
+ if (!unifiedAlertingEnabled && !isDashboardSelectorAvailable(entity)) {
93
+ return /* @__PURE__ */ React.createElement(
94
+ MissingAnnotationEmptyState,
95
+ {
96
+ annotation: GRAFANA_ANNOTATION_TAG_SELECTOR
97
+ }
98
+ );
99
+ }
100
+ if (unifiedAlertingEnabled && !isAlertSelectorAvailable(entity)) {
101
+ return /* @__PURE__ */ React.createElement(
102
+ MissingAnnotationEmptyState,
103
+ {
104
+ annotation: GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR
105
+ }
106
+ );
107
+ }
108
+ const finalOpts = { ...opts, ...{ showState: opts == null ? void 0 : opts.showState } };
109
+ return /* @__PURE__ */ React.createElement(Alerts, { entity, opts: finalOpts });
110
+ };
111
+
112
+ export { AlertsCard, AlertsTable };
113
+ //# sourceMappingURL=AlertsCard.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AlertsCard.esm.js","sources":["../../../src/components/AlertsCard/AlertsCard.tsx"],"sourcesContent":["/*\n * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\nimport {\n Progress,\n TableColumn,\n Table,\n StatusOK,\n StatusPending,\n StatusWarning,\n StatusError,\n StatusAborted,\n Link,\n} from '@backstage/core-components';\nimport { Entity } from '@backstage/catalog-model';\nimport {\n MissingAnnotationEmptyState,\n useEntity,\n} from '@backstage/plugin-catalog-react';\nimport { configApiRef, useApi } from '@backstage/core-plugin-api';\nimport { grafanaApiRef } from '../../api';\nimport useAsync from 'react-use/lib/useAsync';\nimport { Alert } from '@material-ui/lab';\nimport { AlertsCardOpts, Alert as GrafanaAlert } from '../../types';\nimport {\n GRAFANA_ANNOTATION_TAG_SELECTOR,\n GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR,\n isAlertSelectorAvailable,\n isDashboardSelectorAvailable,\n tagSelectorFromEntity,\n alertSelectorFromEntity,\n} from '../../constants';\n\nconst AlertStatusBadge = ({ alert }: { alert: GrafanaAlert }) => {\n let statusElmt: React.ReactElement;\n\n switch (alert.state) {\n case 'ok':\n case 'Normal':\n statusElmt = <StatusOK />;\n break;\n case 'paused':\n case 'Pending':\n statusElmt = <StatusPending />;\n break;\n case 'no_data':\n case 'pending':\n case 'NoData':\n statusElmt = <StatusWarning />;\n break;\n case 'alerting':\n case 'Alerting':\n case 'Error':\n statusElmt = <StatusError />;\n break;\n default:\n statusElmt = <StatusAborted />;\n }\n\n return <div>{statusElmt}</div>;\n};\n\nexport const AlertsTable = ({\n alerts,\n opts,\n}: {\n alerts: GrafanaAlert[];\n opts: AlertsCardOpts;\n}) => {\n const columns: TableColumn<GrafanaAlert>[] = [\n {\n title: 'Name',\n field: 'name',\n cellStyle: { width: '90%' },\n render: (row: GrafanaAlert): React.ReactNode => (\n <Link to={row.url} target=\"_blank\" rel=\"noopener\">\n {row.name}\n </Link>\n ),\n },\n ];\n\n if (opts.showState) {\n columns.push({\n title: 'State',\n render: (row: GrafanaAlert): React.ReactNode => (\n <AlertStatusBadge alert={row} />\n ),\n });\n }\n\n return (\n <Table\n title={opts.title || 'Alerts'}\n options={{\n paging: opts.paged ?? false,\n pageSize: opts.pageSize ?? 5,\n search: opts.searchable ?? false,\n emptyRowsWhenPaging: false,\n sorting: opts.sortable ?? false,\n draggable: false,\n padding: 'dense',\n }}\n data={alerts}\n columns={columns}\n />\n );\n};\n\nconst Alerts = ({ entity, opts }: { entity: Entity; opts: AlertsCardOpts }) => {\n const grafanaApi = useApi(grafanaApiRef);\n const configApi = useApi(configApiRef);\n const unifiedAlertingEnabled =\n configApi.getOptionalBoolean('grafana.unifiedAlerting') || false;\n const alertSelector = unifiedAlertingEnabled\n ? alertSelectorFromEntity(entity)\n : tagSelectorFromEntity(entity);\n\n const { value, loading, error } = useAsync(\n async () => await grafanaApi.alertsForSelector(alertSelector),\n );\n\n if (loading) {\n return <Progress />;\n } else if (error) {\n return <Alert severity=\"error\">{error.message}</Alert>;\n }\n\n return <AlertsTable alerts={value || []} opts={opts} />;\n};\n\nexport const AlertsCard = (opts?: AlertsCardOpts) => {\n const { entity } = useEntity();\n const configApi = useApi(configApiRef);\n const unifiedAlertingEnabled =\n configApi.getOptionalBoolean('grafana.unifiedAlerting') || false;\n\n if (!unifiedAlertingEnabled && !isDashboardSelectorAvailable(entity)) {\n return (\n <MissingAnnotationEmptyState\n annotation={GRAFANA_ANNOTATION_TAG_SELECTOR}\n />\n );\n }\n\n if (unifiedAlertingEnabled && !isAlertSelectorAvailable(entity)) {\n return (\n <MissingAnnotationEmptyState\n annotation={GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR}\n />\n );\n }\n\n const finalOpts = { ...opts, ...{ showState: opts?.showState } };\n\n return <Alerts entity={entity} opts={finalOpts} />;\n};\n"],"names":[],"mappings":";;;;;;;;;AA+CA,MAAM,gBAAmB,GAAA,CAAC,EAAE,KAAA,EAAqC,KAAA;AAC/D,EAAI,IAAA,UAAA,CAAA;AAEJ,EAAA,QAAQ,MAAM,KAAO;AAAA,IACnB,KAAK,IAAA,CAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,UAAA,uCAAc,QAAS,EAAA,IAAA,CAAA,CAAA;AACvB,MAAA,MAAA;AAAA,IACF,KAAK,QAAA,CAAA;AAAA,IACL,KAAK,SAAA;AACH,MAAA,UAAA,uCAAc,aAAc,EAAA,IAAA,CAAA,CAAA;AAC5B,MAAA,MAAA;AAAA,IACF,KAAK,SAAA,CAAA;AAAA,IACL,KAAK,SAAA,CAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,UAAA,uCAAc,aAAc,EAAA,IAAA,CAAA,CAAA;AAC5B,MAAA,MAAA;AAAA,IACF,KAAK,UAAA,CAAA;AAAA,IACL,K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":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,31 @@
1
+ import React from 'react';
2
+ import { useEntity, MissingAnnotationEmptyState } from '@backstage/plugin-catalog-react';
3
+ import { isOverviewDashboardAvailable, GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD, overviewDashboardFromEntity } from '../../constants.esm.js';
4
+
5
+ const DashboardViewer = ({ embedUrl }) => {
6
+ return /* @__PURE__ */ React.createElement(
7
+ "iframe",
8
+ {
9
+ title: embedUrl,
10
+ src: embedUrl,
11
+ width: "100%",
12
+ height: "100%",
13
+ referrerPolicy: "strict-origin-when-cross-origin"
14
+ }
15
+ );
16
+ };
17
+ const EntityDashboardViewer = () => {
18
+ const { entity } = useEntity();
19
+ if (!isOverviewDashboardAvailable(entity)) {
20
+ return /* @__PURE__ */ React.createElement(
21
+ MissingAnnotationEmptyState,
22
+ {
23
+ annotation: GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD
24
+ }
25
+ );
26
+ }
27
+ return /* @__PURE__ */ React.createElement(DashboardViewer, { embedUrl: overviewDashboardFromEntity(entity) });
28
+ };
29
+
30
+ export { DashboardViewer, EntityDashboardViewer };
31
+ //# sourceMappingURL=DashboardViewer.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DashboardViewer.esm.js","sources":["../../../src/components/DashboardViewer/DashboardViewer.tsx"],"sourcesContent":["/*\n * Copyright 2023 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\nimport {\n MissingAnnotationEmptyState,\n useEntity,\n} from '@backstage/plugin-catalog-react';\nimport {\n GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD,\n isOverviewDashboardAvailable,\n overviewDashboardFromEntity,\n} from '../../constants';\n\n/**\n * Component which embeds the defined URL contents\n * @public\n */\nexport const DashboardViewer = ({ embedUrl }: { embedUrl: string }) => {\n return (\n <iframe\n title={embedUrl}\n src={embedUrl}\n width=\"100%\"\n height=\"100%\"\n referrerPolicy=\"strict-origin-when-cross-origin\"\n />\n );\n};\n\n/**\n * Component which embeds the dashboard overview for an entity\n * @public\n */\nexport const EntityDashboardViewer = () => {\n const { entity } = useEntity();\n\n if (!isOverviewDashboardAvailable(entity)) {\n return (\n <MissingAnnotationEmptyState\n annotation={GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD}\n />\n );\n }\n\n return <DashboardViewer embedUrl={overviewDashboardFromEntity(entity)} />;\n};\n"],"names":[],"mappings":";;;;AA+BO,MAAM,eAAkB,GAAA,CAAC,EAAE,QAAA,EAAqC,KAAA;AACrE,EACE,uBAAA,KAAA,CAAA,aAAA;AAAA,IAAC,QAAA;AAAA,IAAA;AAAA,MACC,KAAO,EAAA,QAAA;AAAA,MACP,GAAK,EAAA,QAAA;AAAA,MACL,KAAM,EAAA,MAAA;AAAA,MACN,MAAO,EAAA,MAAA;AAAA,MACP,cAAe,EAAA,iCAAA;AAAA,KAAA;AAAA,GACjB,CAAA;AAEJ,EAAA;AAMO,MAAM,wBAAwB,MAAM;AACzC,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,SAAU,EAAA,CAAA;AAE7B,EAAI,IAAA,CAAC,4BAA6B,CAAA,MAAM,CAAG,EAAA;AACzC,IACE,uBAAA,KAAA,CAAA,aAAA;AAAA,MAAC,2BAAA;AAAA,MAAA;AAAA,QACC,UAAY,EAAA,qCAAA;AAAA,OAAA;AAAA,KACd,CAAA;AAAA,GAEJ;AAEA,EAAA,uBAAQ,KAAA,CAAA,aAAA,CAAA,eAAA,EAAA,EAAgB,QAAU,EAAA,2BAAA,CAA4B,MAAM,CAAG,EAAA,CAAA,CAAA;AACzE;;;;"}
@@ -0,0 +1,2 @@
1
+ export { DashboardViewer, EntityDashboardViewer } from './DashboardViewer.esm.js';
2
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,88 @@
1
+ import React from 'react';
2
+ import { Progress, Table, Link } from '@backstage/core-components';
3
+ import { useEntity, MissingAnnotationEmptyState } from '@backstage/plugin-catalog-react';
4
+ import { useApi } from '@backstage/core-plugin-api';
5
+ import { grafanaApiRef } from '../../api.esm.js';
6
+ import useAsync from 'react-use/lib/useAsync';
7
+ import { Alert } from '@material-ui/lab';
8
+ import { Tooltip } from '@material-ui/core';
9
+ import { isDashboardSelectorAvailable, GRAFANA_ANNOTATION_DASHBOARD_SELECTOR, dashboardSelectorFromEntity } from '../../constants.esm.js';
10
+
11
+ const DashboardsTable = ({
12
+ entity,
13
+ dashboards,
14
+ opts
15
+ }) => {
16
+ var _a, _b, _c, _d;
17
+ const columns = [
18
+ {
19
+ title: "Title",
20
+ field: "title",
21
+ render: (row) => /* @__PURE__ */ React.createElement(Link, { to: row.url, target: "_blank", rel: "noopener" }, row.title)
22
+ },
23
+ {
24
+ title: "Folder",
25
+ field: "folderTitle",
26
+ render: (row) => /* @__PURE__ */ React.createElement(Link, { to: row.folderUrl, target: "_blank", rel: "noopener" }, row.folderTitle)
27
+ }
28
+ ];
29
+ const titleElm = /* @__PURE__ */ React.createElement(
30
+ Tooltip,
31
+ {
32
+ title: `Note: only dashboard with the "${dashboardSelectorFromEntity(
33
+ entity
34
+ )}" selector are displayed.`
35
+ },
36
+ /* @__PURE__ */ React.createElement("span", null, opts.title || "Dashboards")
37
+ );
38
+ return /* @__PURE__ */ React.createElement(
39
+ Table,
40
+ {
41
+ title: titleElm,
42
+ options: {
43
+ paging: (_a = opts.paged) != null ? _a : false,
44
+ pageSize: (_b = opts.pageSize) != null ? _b : 5,
45
+ search: (_c = opts.searchable) != null ? _c : false,
46
+ emptyRowsWhenPaging: false,
47
+ sorting: (_d = opts.sortable) != null ? _d : false,
48
+ draggable: false,
49
+ padding: "dense"
50
+ },
51
+ data: dashboards,
52
+ columns
53
+ }
54
+ );
55
+ };
56
+ const Dashboards = ({
57
+ entity,
58
+ opts
59
+ }) => {
60
+ const grafanaApi = useApi(grafanaApiRef);
61
+ const { value, loading, error } = useAsync(async () => {
62
+ const dashboards = await grafanaApi.listDashboards(
63
+ dashboardSelectorFromEntity(entity)
64
+ );
65
+ if (opts == null ? void 0 : opts.additionalDashboards) {
66
+ dashboards.push(...opts.additionalDashboards(entity));
67
+ }
68
+ return dashboards;
69
+ });
70
+ if (loading) {
71
+ return /* @__PURE__ */ React.createElement(Progress, null);
72
+ } else if (error) {
73
+ return /* @__PURE__ */ React.createElement(Alert, { severity: "error" }, error.message);
74
+ }
75
+ return /* @__PURE__ */ React.createElement(DashboardsTable, { entity, dashboards: value || [], opts });
76
+ };
77
+ const DashboardsCard = (opts) => {
78
+ const { entity } = useEntity();
79
+ return !isDashboardSelectorAvailable(entity) ? /* @__PURE__ */ React.createElement(
80
+ MissingAnnotationEmptyState,
81
+ {
82
+ annotation: GRAFANA_ANNOTATION_DASHBOARD_SELECTOR
83
+ }
84
+ ) : /* @__PURE__ */ React.createElement(Dashboards, { entity, opts: opts || {} });
85
+ };
86
+
87
+ export { DashboardsCard, DashboardsTable };
88
+ //# sourceMappingURL=DashboardsCard.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DashboardsCard.esm.js","sources":["../../../src/components/DashboardsCard/DashboardsCard.tsx"],"sourcesContent":["/*\n * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\nimport { Progress, TableColumn, Table, Link } from '@backstage/core-components';\nimport { Entity } from '@backstage/catalog-model';\nimport {\n MissingAnnotationEmptyState,\n useEntity,\n} from '@backstage/plugin-catalog-react';\nimport { useApi } from '@backstage/core-plugin-api';\nimport { grafanaApiRef } from '../../api';\nimport useAsync from 'react-use/lib/useAsync';\nimport { Alert } from '@material-ui/lab';\nimport { Tooltip } from '@material-ui/core';\nimport { Dashboard, DashboardCardOpts } from '../../types';\nimport {\n dashboardSelectorFromEntity,\n GRAFANA_ANNOTATION_DASHBOARD_SELECTOR,\n isDashboardSelectorAvailable,\n} from '../../constants';\n\nexport const DashboardsTable = ({\n entity,\n dashboards,\n opts,\n}: {\n entity: Entity;\n dashboards: Dashboard[];\n opts: DashboardCardOpts;\n}) => {\n const columns: TableColumn<Dashboard>[] = [\n {\n title: 'Title',\n field: 'title',\n render: (row: Dashboard) => (\n <Link to={row.url} target=\"_blank\" rel=\"noopener\">\n {row.title}\n </Link>\n ),\n },\n {\n title: 'Folder',\n field: 'folderTitle',\n render: (row: Dashboard) => (\n <Link to={row.folderUrl} target=\"_blank\" rel=\"noopener\">\n {row.folderTitle}\n </Link>\n ),\n },\n ];\n\n const titleElm = (\n <Tooltip\n title={`Note: only dashboard with the \"${dashboardSelectorFromEntity(\n entity,\n )}\" selector are displayed.`}\n >\n <span>{opts.title || 'Dashboards'}</span>\n </Tooltip>\n );\n\n return (\n <Table\n title={titleElm}\n options={{\n paging: opts.paged ?? false,\n pageSize: opts.pageSize ?? 5,\n search: opts.searchable ?? false,\n emptyRowsWhenPaging: false,\n sorting: opts.sortable ?? false,\n draggable: false,\n padding: 'dense',\n }}\n data={dashboards}\n columns={columns}\n />\n );\n};\n\nconst Dashboards = ({\n entity,\n opts,\n}: {\n entity: Entity;\n opts: DashboardCardOpts;\n}) => {\n const grafanaApi = useApi(grafanaApiRef);\n const { value, loading, error } = useAsync(async () => {\n const dashboards = await grafanaApi.listDashboards(\n dashboardSelectorFromEntity(entity),\n );\n if (opts?.additionalDashboards) {\n dashboards.push(...opts.additionalDashboards(entity));\n }\n return dashboards;\n });\n\n if (loading) {\n return <Progress />;\n } else if (error) {\n return <Alert severity=\"error\">{error.message}</Alert>;\n }\n\n return (\n <DashboardsTable entity={entity} dashboards={value || []} opts={opts} />\n );\n};\n\nexport const DashboardsCard = (opts?: DashboardCardOpts) => {\n const { entity } = useEntity();\n\n return !isDashboardSelectorAvailable(entity) ? (\n <MissingAnnotationEmptyState\n annotation={GRAFANA_ANNOTATION_DASHBOARD_SELECTOR}\n />\n ) : (\n <Dashboards entity={entity} opts={opts || {}} />\n );\n};\n"],"names":[],"mappings":";;;;;;;;;;AAmCO,MAAM,kBAAkB,CAAC;AAAA,EAC9B,MAAA;AAAA,EACA,UAAA;AAAA,EACA,IAAA;AACF,CAIM,KAAA;AA3CN,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAA;AA4CE,EAAA,MAAM,OAAoC,GAAA;AAAA,IACxC;AAAA,MACE,KAAO,EAAA,OAAA;AAAA,MACP,KAAO,EAAA,OAAA;AAAA,MACP,MAAQ,EAAA,CAAC,GACP,qBAAA,KAAA,CAAA,aAAA,CAAC,IAAK,EAAA,EAAA,EAAA,EAAI,GAAI,CAAA,GAAA,EAAK,MAAO,EAAA,QAAA,EAAS,GAAI,EAAA,UAAA,EAAA,EACpC,IAAI,KACP,CAAA;AAAA,KAEJ;AAAA,IACA;AAAA,MACE,KAAO,EAAA,QAAA;AAAA,MACP,KAAO,EAAA,aAAA;AAAA,MACP,MAAQ,EAAA,CAAC,GACP,qBAAA,KAAA,CAAA,aAAA,CAAC,IAAK,EAAA,EAAA,EAAA,EAAI,GAAI,CAAA,SAAA,EAAW,MAAO,EAAA,QAAA,EAAS,GAAI,EAAA,UAAA,E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EAAS,KAAM,EAAA,GAAI,SAAS,YAAY;AACrD,IAAM,MAAA,UAAA,GAAa,MAAM,UAAW,CAAA,cAAA;AAAA,MAClC,4BAA4B,MAAM,CAAA;AAAA,KACpC,CAAA;AACA,IAAA,IAAI,6BAAM,oBAAsB,EAAA;AAC9B,MAAA,UAAA,CAAW,IAAK,CAAA,GAAG,IAAK,CAAA,oBAAA,CAAqB,MAAM,CAAC,CAAA,CAAA;AAAA,KACtD;AACA,IAAO,OAAA,UAAA,CAAA;AAAA,GACR,CAAA,CAAA;AAED,EAAA,IAAI,OAAS,EAAA;AACX,IAAA,2CAAQ,QAAS,EAAA,IAAA,CAAA,CAAA;AAAA,aACR,KAAO,EAAA;AAChB,IAAA,uBAAQ,KAAA,CAAA,aAAA,CAAA,KAAA,EAAA,EAAM,QAAS,EAAA,OAAA,EAAA,EAAS,MAAM,OAAQ,CAAA,CAAA;AAAA,GAChD;AAEA,EAAA,2CACG,eAAgB,EAAA,EAAA,MAAA,EAAgB,YAAY,KAAS,IAAA,IAAI,IAAY,EAAA,CAAA,CAAA;AAE1E,CAAA,CAAA;AAEa,MAAA,cAAA,GAAiB,CAAC,IAA6B,KAAA;AAC1D,EAAM,MAAA,EAAE,MAAO,EAAA,GAAI,SAAU,EAAA,CAAA;AAE7B,EAAO,OAAA,CAAC,4BAA6B,CAAA,MAAM,CACzC,mBAAA,KAAA,CAAA,aAAA;AAAA,IAAC,2BAAA;AAAA,IAAA;AAAA,MACC,UAAY,EAAA,qCAAA;AAAA,KAAA;AAAA,sBAGb,KAAA,CAAA,aAAA,CAAA,UAAA,EAAA,EAAW,QAAgB,IAAM,EAAA,IAAA,IAAQ,EAAI,EAAA,CAAA,CAAA;AAElD;;;;"}
@@ -0,0 +1,2 @@
1
+ export { DashboardsCard } from './DashboardsCard.esm.js';
2
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,36 @@
1
+ const GRAFANA_ANNOTATION_TAG_SELECTOR = "grafana/tag-selector";
2
+ const GRAFANA_ANNOTATION_DASHBOARD_SELECTOR = "grafana/dashboard-selector";
3
+ const GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR = "grafana/alert-label-selector";
4
+ const GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD = "grafana/overview-dashboard";
5
+ const isDashboardSelectorAvailable = (entity) => {
6
+ var _a, _b;
7
+ return ((_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_DASHBOARD_SELECTOR]) || ((_b = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _b[GRAFANA_ANNOTATION_TAG_SELECTOR]);
8
+ };
9
+ const isAlertSelectorAvailable = (entity) => {
10
+ var _a;
11
+ return Boolean(
12
+ (_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR]
13
+ );
14
+ };
15
+ const isOverviewDashboardAvailable = (entity) => {
16
+ var _a;
17
+ return Boolean(
18
+ (_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD]
19
+ );
20
+ };
21
+ const dashboardSelectorFromEntity = (entity) => {
22
+ var _a, _b, _c, _d;
23
+ return (_d = (_c = (_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_DASHBOARD_SELECTOR]) != null ? _c : (_b = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _b[GRAFANA_ANNOTATION_TAG_SELECTOR]) != null ? _d : "";
24
+ };
25
+ const alertSelectorFromEntity = (entity) => {
26
+ var _a, _b;
27
+ return (_b = (_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR]) != null ? _b : "";
28
+ };
29
+ const overviewDashboardFromEntity = (entity) => {
30
+ var _a, _b;
31
+ return (_b = (_a = entity == null ? void 0 : entity.metadata.annotations) == null ? void 0 : _a[GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD]) != null ? _b : "";
32
+ };
33
+ const tagSelectorFromEntity = dashboardSelectorFromEntity;
34
+
35
+ export { GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR, GRAFANA_ANNOTATION_DASHBOARD_SELECTOR, GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD, GRAFANA_ANNOTATION_TAG_SELECTOR, alertSelectorFromEntity, dashboardSelectorFromEntity, isAlertSelectorAvailable, isDashboardSelectorAvailable, isOverviewDashboardAvailable, overviewDashboardFromEntity, tagSelectorFromEntity };
36
+ //# sourceMappingURL=constants.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.esm.js","sources":["../src/constants.ts"],"sourcesContent":["/*\n * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Entity } from '@backstage/catalog-model';\n\n/**\n * Grafana tag selector annotation\n * @public\n * @deprecated Use GRAFANA_ANNOTATION_DASHBOARD_SELECTOR instead.\n */\nexport const GRAFANA_ANNOTATION_TAG_SELECTOR = 'grafana/tag-selector';\n\n/**\n * Grafana dashboard selector annotation\n * @public\n */\nexport const GRAFANA_ANNOTATION_DASHBOARD_SELECTOR =\n 'grafana/dashboard-selector';\n\n/**\n * Grafana alert selector annotation\n * @public\n */\nexport const GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR =\n 'grafana/alert-label-selector';\n\n/**\n * Grafana dashboard overview annotation\n * @public\n */\nexport const GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD =\n 'grafana/overview-dashboard';\n\n/**\n * Returns if the dashboard selector annotation for an entity is set\n * @public\n */\nexport const isDashboardSelectorAvailable = (entity: Entity) =>\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_DASHBOARD_SELECTOR] ||\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_TAG_SELECTOR];\n\n/**\n * Returns if the alert selector annotation for an entity is set\n * @public\n */\nexport const isAlertSelectorAvailable = (entity: Entity) =>\n Boolean(\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR],\n );\n\n/**\n * Returns if the overview dashboard annotation for an entity is set\n * @public\n */\nexport const isOverviewDashboardAvailable = (entity: Entity) =>\n Boolean(\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD],\n );\n\n/**\n * Returns the dashboard selector annotation for an entity\n * @public\n */\nexport const dashboardSelectorFromEntity = (entity: Entity) =>\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_DASHBOARD_SELECTOR] ??\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_TAG_SELECTOR] ??\n '';\n/**\n * Returns the alert selector annotation for an entity\n * @public\n */\nexport const alertSelectorFromEntity = (entity: Entity) =>\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR] ?? '';\n\n/**\n * Returns the overview dashboard annotation for an entity\n * @public\n */\nexport const overviewDashboardFromEntity = (entity: Entity) =>\n entity?.metadata.annotations?.[GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD] ?? '';\n\n/**\n * Returns the dashboard selector annotation for an entity\n * @public\n * @deprecated Use dashboardSelectorFromEntity instead\n */\nexport const tagSelectorFromEntity = dashboardSelectorFromEntity;\n"],"names":[],"mappings":"AAuBO,MAAM,+BAAkC,GAAA,uBAAA;AAMxC,MAAM,qCACX,GAAA,6BAAA;AAMK,MAAM,uCACX,GAAA,+BAAA;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AAA,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAA,QAAA,CAAS,WAAjB,KAAA,IAAA,GAAA,KAAA,CAAA,GAAA,EAAA,CAA+B,qCAA/B,CAAA,KAAA,IAAA,GAAA,EAAA,GAAA,CACA,sCAAQ,QAAS,CAAA,WAAA,KAAjB,IAA+B,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,+BAAA,CAAA,KAD/B,IAEA,GAAA,EAAA,GAAA,EAAA,CAAA;AAAA,EAAA;AAKW,MAAA,uBAAA,GAA0B,CAAC,MAAgB,KAAA;AApFxD,EAAA,IAAA,EAAA,EAAA,EAAA,CAAA;AAqFE,EAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAQ,QAAS,CAAA,WAAA,KAAjB,IAA+B,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,uCAAA,CAAA,KAA/B,IAA2E,GAAA,EAAA,GAAA,EAAA,CAAA;AAAA,EAAA;AAMhE,MAAA,2BAAA,GAA8B,CAAC,MAAgB,KAAA;AA3F5D,EAAA,IAAA,EAAA,EAAA,EAAA,CAAA;AA4FE,EAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,MAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,MAAA,CAAQ,QAAS,CAAA,WAAA,KAAjB,IAA+B,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,qCAAA,CAAA,KAA/B,IAAyE,GAAA,EAAA,GAAA,EAAA,CAAA;AAAA,EAAA;AAOpE,MAAM,qBAAwB,GAAA;;;;"}
@@ -0,0 +1,203 @@
1
+ /// <reference types="react" />
2
+ import * as react from 'react';
3
+ import react__default from 'react';
4
+ import { Entity } from '@backstage/catalog-model';
5
+ import * as _backstage_core_plugin_api from '@backstage/core-plugin-api';
6
+
7
+ /**
8
+ * Component which embeds the defined URL contents
9
+ * @public
10
+ */
11
+ declare const DashboardViewer: ({ embedUrl }: {
12
+ embedUrl: string;
13
+ }) => react__default.JSX.Element;
14
+ /**
15
+ * Component which embeds the dashboard overview for an entity
16
+ * @public
17
+ */
18
+ declare const EntityDashboardViewer: () => react__default.JSX.Element;
19
+
20
+ /**
21
+ * Grafana daashboard parameters
22
+ * @public
23
+ */
24
+ interface Dashboard {
25
+ /**
26
+ * The dashboard title
27
+ * @public
28
+ */
29
+ title: string;
30
+ /**
31
+ * The endpoint to the dashboard
32
+ * @public
33
+ */
34
+ url: string;
35
+ /**
36
+ * The folder title, if any
37
+ * @public
38
+ */
39
+ folderTitle: string;
40
+ /**
41
+ * The endpoint to the folder
42
+ * @public
43
+ */
44
+ folderUrl: string;
45
+ /**
46
+ * A list of tags assigned to the dashboard
47
+ * @public
48
+ */
49
+ tags: string[];
50
+ }
51
+ /**
52
+ * Grafana alert parameters
53
+ * @public
54
+ */
55
+ interface Alert {
56
+ /**
57
+ * The alert name
58
+ * @public
59
+ */
60
+ name: string;
61
+ /**
62
+ * The alert state
63
+ * @public
64
+ */
65
+ state: string;
66
+ /**
67
+ * The matching selector for the alert
68
+ * @public
69
+ */
70
+ matchingSelector: string;
71
+ /**
72
+ * The endpoint to the alert
73
+ * @public
74
+ */
75
+ url: string;
76
+ }
77
+ /**
78
+ * Parameters used to display the alert card
79
+ * @public
80
+ */
81
+ type AlertsCardOpts = {
82
+ paged?: boolean;
83
+ searchable?: boolean;
84
+ pageSize?: number;
85
+ sortable?: boolean;
86
+ title?: string;
87
+ showState?: boolean;
88
+ };
89
+ /**
90
+ * Parameters used to display the dashboard card
91
+ * @public
92
+ */
93
+ type DashboardCardOpts = {
94
+ paged?: boolean;
95
+ searchable?: boolean;
96
+ pageSize?: number;
97
+ sortable?: boolean;
98
+ title?: string;
99
+ additionalDashboards?: (entity: Entity) => Dashboard[];
100
+ };
101
+
102
+ /**
103
+ * The grafana plugin.
104
+ * @public
105
+ */
106
+ declare const grafanaPlugin: _backstage_core_plugin_api.BackstagePlugin<{}, {}, {}>;
107
+ /**
108
+ * Component which displays the grafana dashboards found for an entity
109
+ * @public
110
+ */
111
+ declare const EntityGrafanaDashboardsCard: (opts?: DashboardCardOpts | undefined) => react.JSX.Element;
112
+ /**
113
+ * Component which displays the grafana alerts found for an entity
114
+ * @public
115
+ */
116
+ declare const EntityGrafanaAlertsCard: (opts?: AlertsCardOpts | undefined) => react.JSX.Element;
117
+ /**
118
+ * Component which displays the defined grafana dashboard for an entity
119
+ * @public
120
+ */
121
+ declare const EntityOverviewDashboardViewer: () => react.JSX.Element;
122
+
123
+ /**
124
+ * Grafana tag selector annotation
125
+ * @public
126
+ * @deprecated Use GRAFANA_ANNOTATION_DASHBOARD_SELECTOR instead.
127
+ */
128
+ declare const GRAFANA_ANNOTATION_TAG_SELECTOR = "grafana/tag-selector";
129
+ /**
130
+ * Grafana dashboard selector annotation
131
+ * @public
132
+ */
133
+ declare const GRAFANA_ANNOTATION_DASHBOARD_SELECTOR = "grafana/dashboard-selector";
134
+ /**
135
+ * Grafana alert selector annotation
136
+ * @public
137
+ */
138
+ declare const GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR = "grafana/alert-label-selector";
139
+ /**
140
+ * Grafana dashboard overview annotation
141
+ * @public
142
+ */
143
+ declare const GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD = "grafana/overview-dashboard";
144
+ /**
145
+ * Returns if the dashboard selector annotation for an entity is set
146
+ * @public
147
+ */
148
+ declare const isDashboardSelectorAvailable: (entity: Entity) => string | undefined;
149
+ /**
150
+ * Returns if the alert selector annotation for an entity is set
151
+ * @public
152
+ */
153
+ declare const isAlertSelectorAvailable: (entity: Entity) => boolean;
154
+ /**
155
+ * Returns if the overview dashboard annotation for an entity is set
156
+ * @public
157
+ */
158
+ declare const isOverviewDashboardAvailable: (entity: Entity) => boolean;
159
+ /**
160
+ * Returns the dashboard selector annotation for an entity
161
+ * @public
162
+ */
163
+ declare const dashboardSelectorFromEntity: (entity: Entity) => string;
164
+ /**
165
+ * Returns the alert selector annotation for an entity
166
+ * @public
167
+ */
168
+ declare const alertSelectorFromEntity: (entity: Entity) => string;
169
+ /**
170
+ * Returns the overview dashboard annotation for an entity
171
+ * @public
172
+ */
173
+ declare const overviewDashboardFromEntity: (entity: Entity) => string;
174
+ /**
175
+ * Returns the dashboard selector annotation for an entity
176
+ * @public
177
+ * @deprecated Use dashboardSelectorFromEntity instead
178
+ */
179
+ declare const tagSelectorFromEntity: (entity: Entity) => string;
180
+
181
+ /**
182
+ * Interface for the Grafana API
183
+ * @public
184
+ */
185
+ interface GrafanaApi {
186
+ /**
187
+ * Returns the found dashboards in Grafana with the defined query
188
+ * @param query - The query used to list the dashboards
189
+ */
190
+ listDashboards(query: string): Promise<Dashboard[]>;
191
+ /**
192
+ * Returns a list of alerts found in Grafana that have any of the defined alert selectors
193
+ * @param selectors - One or multiple alert selectors
194
+ */
195
+ alertsForSelector(selectors: string | string[]): Promise<Alert[]>;
196
+ }
197
+ /**
198
+ * The grafana API reference
199
+ * @public
200
+ */
201
+ declare const grafanaApiRef: _backstage_core_plugin_api.ApiRef<GrafanaApi>;
202
+
203
+ export { type Alert, type AlertsCardOpts, type Dashboard, type DashboardCardOpts, DashboardViewer, EntityDashboardViewer, EntityGrafanaAlertsCard, EntityGrafanaDashboardsCard, EntityOverviewDashboardViewer, GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR, GRAFANA_ANNOTATION_DASHBOARD_SELECTOR, GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD, GRAFANA_ANNOTATION_TAG_SELECTOR, type GrafanaApi, alertSelectorFromEntity, dashboardSelectorFromEntity, grafanaApiRef, grafanaPlugin, isAlertSelectorAvailable, isDashboardSelectorAvailable, isOverviewDashboardAvailable, overviewDashboardFromEntity, tagSelectorFromEntity };
@@ -0,0 +1,5 @@
1
+ export { DashboardViewer, EntityDashboardViewer } from './components/DashboardViewer/DashboardViewer.esm.js';
2
+ export { EntityGrafanaAlertsCard, EntityGrafanaDashboardsCard, EntityOverviewDashboardViewer, grafanaPlugin } from './plugin.esm.js';
3
+ export { GRAFANA_ANNOTATION_ALERT_LABEL_SELECTOR, GRAFANA_ANNOTATION_DASHBOARD_SELECTOR, GRAFANA_ANNOTATION_OVERVIEW_DASHBOARD, GRAFANA_ANNOTATION_TAG_SELECTOR, alertSelectorFromEntity, dashboardSelectorFromEntity, isAlertSelectorAvailable, isDashboardSelectorAvailable, isOverviewDashboardAvailable, overviewDashboardFromEntity, tagSelectorFromEntity } from './constants.esm.js';
4
+ export { grafanaApiRef } from './api.esm.js';
5
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
@@ -0,0 +1,62 @@
1
+ import { createPlugin, createApiFactory, discoveryApiRef, fetchApiRef, configApiRef, createComponentExtension } from '@backstage/core-plugin-api';
2
+ import { grafanaApiRef, GrafanaApiClient, UnifiedAlertingGrafanaApiClient } from './api.esm.js';
3
+
4
+ const grafanaPlugin = createPlugin({
5
+ id: "grafana",
6
+ apis: [
7
+ createApiFactory({
8
+ api: grafanaApiRef,
9
+ deps: {
10
+ discoveryApi: discoveryApiRef,
11
+ fetchApi: fetchApiRef,
12
+ configApi: configApiRef
13
+ },
14
+ factory: ({ discoveryApi, fetchApi, configApi }) => {
15
+ const unifiedAlertingEnabled = configApi.getOptionalBoolean("grafana.unifiedAlerting") || false;
16
+ if (!unifiedAlertingEnabled) {
17
+ return new GrafanaApiClient({
18
+ discoveryApi,
19
+ fetchApi,
20
+ domain: configApi.getString("grafana.domain"),
21
+ proxyPath: configApi.getOptionalString("grafana.proxyPath")
22
+ });
23
+ }
24
+ return new UnifiedAlertingGrafanaApiClient({
25
+ discoveryApi,
26
+ fetchApi,
27
+ domain: configApi.getString("grafana.domain"),
28
+ proxyPath: configApi.getOptionalString("grafana.proxyPath")
29
+ });
30
+ }
31
+ })
32
+ ]
33
+ });
34
+ const EntityGrafanaDashboardsCard = grafanaPlugin.provide(
35
+ createComponentExtension({
36
+ name: "EntityGrafanaDashboardsCard",
37
+ component: {
38
+ lazy: () => import('./components/DashboardsCard/index.esm.js').then((m) => m.DashboardsCard)
39
+ }
40
+ })
41
+ );
42
+ const EntityGrafanaAlertsCard = grafanaPlugin.provide(
43
+ createComponentExtension({
44
+ name: "EntityGrafanaAlertsCard",
45
+ component: {
46
+ lazy: () => import('./components/AlertsCard/index.esm.js').then((m) => m.AlertsCard)
47
+ }
48
+ })
49
+ );
50
+ const EntityOverviewDashboardViewer = grafanaPlugin.provide(
51
+ createComponentExtension({
52
+ name: "EntityOverviewDashboardViewer",
53
+ component: {
54
+ lazy: () => import('./components/DashboardViewer/index.esm.js').then(
55
+ (m) => m.EntityDashboardViewer
56
+ )
57
+ }
58
+ })
59
+ );
60
+
61
+ export { EntityGrafanaAlertsCard, EntityGrafanaDashboardsCard, EntityOverviewDashboardViewer, grafanaPlugin };
62
+ //# sourceMappingURL=plugin.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.esm.js","sources":["../src/plugin.ts"],"sourcesContent":["/*\n * Copyright 2021 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n configApiRef,\n createApiFactory,\n createComponentExtension,\n createPlugin,\n discoveryApiRef,\n fetchApiRef,\n} from '@backstage/core-plugin-api';\nimport {\n UnifiedAlertingGrafanaApiClient,\n grafanaApiRef,\n GrafanaApiClient,\n} from './api';\n\n/**\n * The grafana plugin.\n * @public\n */\nexport const grafanaPlugin = createPlugin({\n id: 'grafana',\n apis: [\n createApiFactory({\n api: grafanaApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n fetchApi: fetchApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, fetchApi, configApi }) => {\n const unifiedAlertingEnabled =\n configApi.getOptionalBoolean('grafana.unifiedAlerting') || false;\n\n if (!unifiedAlertingEnabled) {\n return new GrafanaApiClient({\n discoveryApi,\n fetchApi,\n domain: configApi.getString('grafana.domain'),\n proxyPath: configApi.getOptionalString('grafana.proxyPath'),\n });\n }\n\n return new UnifiedAlertingGrafanaApiClient({\n discoveryApi,\n fetchApi,\n domain: configApi.getString('grafana.domain'),\n proxyPath: configApi.getOptionalString('grafana.proxyPath'),\n });\n },\n }),\n ],\n});\n\n/**\n * Component which displays the grafana dashboards found for an entity\n * @public\n */\nexport const EntityGrafanaDashboardsCard = grafanaPlugin.provide(\n createComponentExtension({\n name: 'EntityGrafanaDashboardsCard',\n component: {\n lazy: () =>\n import('./components/DashboardsCard').then(m => m.DashboardsCard),\n },\n }),\n);\n\n/**\n * Component which displays the grafana alerts found for an entity\n * @public\n */\nexport const EntityGrafanaAlertsCard = grafanaPlugin.provide(\n createComponentExtension({\n name: 'EntityGrafanaAlertsCard',\n component: {\n lazy: () => import('./components/AlertsCard').then(m => m.AlertsCard),\n },\n }),\n);\n\n/**\n * Component which displays the defined grafana dashboard for an entity\n * @public\n */\nexport const EntityOverviewDashboardViewer = grafanaPlugin.provide(\n createComponentExtension({\n name: 'EntityOverviewDashboardViewer',\n component: {\n lazy: () =>\n import('./components/DashboardViewer').then(\n m => m.EntityDashboardViewer,\n ),\n },\n }),\n);\n"],"names":[],"mappings":";;;AAkCO,MAAM,gBAAgB,YAAa,CAAA;AAAA,EACxC,EAAI,EAAA,SAAA;AAAA,EACJ,IAAM,EAAA;AAAA,IACJ,gBAAiB,CAAA;AAAA,MACf,GAAK,EAAA,aAAA;AAAA,MACL,IAAM,EAAA;AAAA,QACJ,YAAc,EAAA,eAAA;AAAA,QACd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,EAAE,UAAU,CAAA;AAAA,KACtE;AAAA,GACD,CAAA;AACH,EAAA;AAMO,MAAM,gCAAgC,aAAc,CAAA,OAAA;AAAA,EACzD,wBAAyB,CAAA;AAAA,IACvB,IAAM,EAAA,+BAAA;AAAA,IACN,SAAW,EAAA;AAAA,MACT,IAAM,EAAA,MACJ,OAAO,2CAA8B,CAAE,CAAA,IAAA;AAAA,QACrC,OAAK,CAAE,CAAA,qBAAA;AAAA,OACT;AAAA,KACJ;AAAA,GACD,CAAA;AACH;;;;"}
@@ -0,0 +1,71 @@
1
+ import jsep from 'jsep';
2
+
3
+ const includes = (haystack, needle) => {
4
+ if (!Array.isArray(haystack)) {
5
+ throw Error(`@> operator can only be used on an array`);
6
+ }
7
+ return haystack.includes(needle);
8
+ };
9
+ class QueryEvaluator {
10
+ constructor() {
11
+ jsep.addBinaryOp("@>", 6);
12
+ }
13
+ parse(query) {
14
+ return jsep(query);
15
+ }
16
+ evaluate(root, context) {
17
+ switch (root.type) {
18
+ case "UnaryExpression":
19
+ return this.evaluateUnaryExpression(
20
+ root,
21
+ context
22
+ );
23
+ case "BinaryExpression":
24
+ return this.evaluateBinaryExpression(
25
+ root,
26
+ context
27
+ );
28
+ case "Identifier":
29
+ if (!context.hasOwnProperty(root.name)) {
30
+ throw Error(
31
+ `identifier ${root.name} does not exist`
32
+ );
33
+ }
34
+ return context[root.name];
35
+ case "Literal":
36
+ return root.value;
37
+ default:
38
+ throw Error(`unknown node type ${root.type}`);
39
+ }
40
+ }
41
+ evaluateUnaryExpression(root, context) {
42
+ switch (root.operator) {
43
+ case "!":
44
+ return !this.evaluate(root.argument, context);
45
+ default:
46
+ throw Error(`unknown unary operator ${root.operator}`);
47
+ }
48
+ }
49
+ evaluateBinaryExpression(root, context) {
50
+ switch (root.operator) {
51
+ case "&&":
52
+ return this.evaluate(root.left, context) && this.evaluate(root.right, context);
53
+ case "||":
54
+ return this.evaluate(root.left, context) || this.evaluate(root.right, context);
55
+ case "==":
56
+ return this.evaluate(root.left, context) === this.evaluate(root.right, context);
57
+ case "!=":
58
+ return this.evaluate(root.left, context) !== this.evaluate(root.right, context);
59
+ case "@>":
60
+ return includes(
61
+ this.evaluate(root.left, context),
62
+ this.evaluate(root.right, context)
63
+ );
64
+ default:
65
+ throw Error(`unknown binary operator ${root.operator}`);
66
+ }
67
+ }
68
+ }
69
+
70
+ export { QueryEvaluator };
71
+ //# sourceMappingURL=QueryEvaluator.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"QueryEvaluator.esm.js","sources":["../../src/query/QueryEvaluator.ts"],"sourcesContent":["/*\n * Copyright 2023 Kévin Gomez <contact@kevingomez.fr>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport jsep from 'jsep';\n\nexport type EvaluationContext = Record<string, any>;\n\nconst includes = (haystack: any, needle: any): boolean => {\n if (!Array.isArray(haystack)) {\n throw Error(`@> operator can only be used on an array`);\n }\n\n return (haystack as any[]).includes(needle);\n};\n\nexport class QueryEvaluator {\n constructor() {\n // [A] @> B, is B in A\n jsep.addBinaryOp('@>', 6);\n }\n\n parse(query: string): jsep.Expression {\n return jsep(query);\n }\n\n evaluate(root: jsep.Expression, context: EvaluationContext): any {\n switch (root.type) {\n case 'UnaryExpression':\n return this.evaluateUnaryExpression(\n root as jsep.UnaryExpression,\n context,\n );\n case 'BinaryExpression':\n return this.evaluateBinaryExpression(\n root as jsep.BinaryExpression,\n context,\n );\n case 'Identifier':\n if (!context.hasOwnProperty((root as jsep.Identifier).name)) {\n throw Error(\n `identifier ${(root as jsep.Identifier).name} does not exist`,\n );\n }\n\n return context[(root as jsep.Identifier).name];\n case 'Literal':\n return (root as jsep.Literal).value;\n default:\n throw Error(`unknown node type ${root.type}`);\n }\n }\n\n private evaluateUnaryExpression(\n root: jsep.UnaryExpression,\n context: EvaluationContext,\n ): any {\n switch (root.operator) {\n case '!':\n return !this.evaluate(root.argument, context);\n default:\n throw Error(`unknown unary operator ${root.operator}`);\n }\n }\n\n private evaluateBinaryExpression(\n root: jsep.BinaryExpression,\n context: EvaluationContext,\n ): any {\n switch (root.operator) {\n case '&&':\n return (\n this.evaluate(root.left, context) &&\n this.evaluate(root.right, context)\n );\n case '||':\n return (\n this.evaluate(root.left, context) ||\n this.evaluate(root.right, context)\n );\n case '==':\n return (\n this.evaluate(root.left, context) ===\n this.evaluate(root.right, context)\n );\n case '!=':\n return (\n this.evaluate(root.left, context) !==\n this.evaluate(root.right, context)\n );\n case '@>':\n return includes(\n this.evaluate(root.left, context),\n this.evaluate(root.right, context),\n );\n default:\n throw Error(`unknown binary operator ${root.operator}`);\n }\n }\n}\n"],"names":[],"mappings":";;AAoBA,MAAM,QAAA,GAAW,CAAC,QAAA,EAAe,MAAyB,KAAA;AACxD,EAAA,IAAI,CAAC,KAAA,CAAM,OAAQ,CAAA,QAAQ,CAAG,EAAA;AAC5B,IAAA,MAAM,MAAM,CAA0C,wCAAA,CAAA,CAAA,CAAA;AAAA,GACxD;AAEA,EAAQ,OAAA,QAAA,CAAmB,SAAS,MAAM,CAAA,CAAA;AAC5C,CAAA,CAAA;AAEO,MAAM,cAAe,CAAA;AAAA,EAC1B,WAAc,GAAA;AAEZ,IAAK,IAAA,CAAA,WAAA,CAAY,MAAM,CAAC,CAAA,CAAA;AAAA,GAC1B;AAAA,EAEA,MAAM,KAAgC,EAAA;AACpC,IAAA,OAAO,KAAK,KAAK,CAAA,CAAA;AAAA,GACnB;AAAA,EAEA,QAAA,CAAS,MAAuB,OAAiC,EAAA;AAC/D,IAAA,QAAQ,KAAK,IAAM;AAAA,MACjB,KAAK,iBAAA;AACH,QAAA,OAAO,IAA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AAA,CAAK,QAAS,CAAA,IAAA,CAAK,IAAM,EAAA,OAAO,KAChC,IAAK,CAAA,QAAA,CAAS,IAAK,CAAA,KAAA,EAAO,OAAO,CAAA,CAAA;AAAA,MAErC,KAAK,IAAA;AACH,QACE,OAAA,IAAA,CAAK,QAAS,CAAA,IAAA,CAAK,IAAM,EAAA,OAAO,MAChC,IAAK,CAAA,QAAA,CAAS,IAAK,CAAA,KAAA,EAAO,OAAO,CAAA,CAAA;AAAA,MAErC,KAAK,IAAA;AACH,QACE,OAAA,IAAA,CAAK,QAAS,CAAA,IAAA,CAAK,IAAM,EAAA,OAAO,MAChC,IAAK,CAAA,QAAA,CAAS,IAAK,CAAA,KAAA,EAAO,OAAO,CAAA,CAAA;AAAA,MAErC,KAAK,IAAA;AACH,QAAO,OAAA,QAAA;AAAA,UACL,IAAK,CAAA,QAAA,CAAS,IAAK,CAAA,IAAA,EAAM,OAAO,CAAA;AAAA,UAChC,IAAK,CAAA,QAAA,CAAS,IAAK,CAAA,KAAA,EAAO,OAAO,CAAA;AAAA,SACnC,CAAA;AAAA,MACF;AACE,QAAA,MAAM,KAAM,CAAA,CAAA,wBAAA,EAA2B,IAAK,CAAA,QAAQ,CAAE,CAAA,CAAA,CAAA;AAAA,KAC1D;AAAA,GACF;AACF;;;;"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@backstage-community/plugin-grafana",
3
+ "version": "0.1.0",
4
+ "description": "A Backstage backend plugin that integrates towards Grafana",
5
+ "main": "dist/index.esm.js",
6
+ "types": "dist/index.d.ts",
7
+ "license": "Apache-2.0",
8
+ "publishConfig": {
9
+ "access": "public",
10
+ "main": "dist/index.esm.js",
11
+ "types": "dist/index.d.ts"
12
+ },
13
+ "keywords": [
14
+ "backstage",
15
+ "grafana"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/backstage/community-plugins",
20
+ "directory": "workspaces/grafana/plugins/grafana"
21
+ },
22
+ "backstage": {
23
+ "role": "frontend-plugin"
24
+ },
25
+ "sideEffects": false,
26
+ "scripts": {
27
+ "start": "backstage-cli package start",
28
+ "build": "backstage-cli package build",
29
+ "lint": "backstage-cli package lint",
30
+ "test": "backstage-cli package test",
31
+ "clean": "backstage-cli package clean",
32
+ "prepack": "backstage-cli package prepack",
33
+ "postpack": "backstage-cli package postpack"
34
+ },
35
+ "dependencies": {
36
+ "@backstage/catalog-model": "^1.5.0",
37
+ "@backstage/core-components": "^0.14.7",
38
+ "@backstage/core-plugin-api": "^1.9.2",
39
+ "@backstage/plugin-catalog-react": "^1.12.0",
40
+ "@material-ui/core": "^4.12.2",
41
+ "@material-ui/lab": "4.0.0-alpha.61",
42
+ "cross-fetch": "^4.0.0",
43
+ "jsep": "^1.3.8",
44
+ "react-use": "^17.2.4"
45
+ },
46
+ "peerDependencies": {
47
+ "react": "^16.13.1 || ^17.0.0 || ^18.0.0",
48
+ "react-dom": "^16.13.1 || ^17.0.0 || ^18.0.0",
49
+ "react-router-dom": "6.0.0-beta.0 || ^6.3.0"
50
+ },
51
+ "devDependencies": {
52
+ "@backstage/cli": "^0.26.5",
53
+ "@backstage/core-app-api": "^1.12.5",
54
+ "@backstage/dev-utils": "^1.0.32",
55
+ "@backstage/test-utils": "^1.5.5",
56
+ "@testing-library/dom": "^10.0.0",
57
+ "@testing-library/jest-dom": "^6.0.0",
58
+ "@testing-library/react": "^15.0.0",
59
+ "@testing-library/user-event": "^14.0.0",
60
+ "msw": "^1.0.0",
61
+ "react": "^16.13.1 || ^17.0.0 || ^18.0.0",
62
+ "react-dom": "^16.13.1 || ^17.0.0 || ^18.0.0",
63
+ "react-router-dom": "6.0.0-beta.0 || ^6.3.0"
64
+ },
65
+ "files": [
66
+ "dist",
67
+ "config.d.ts"
68
+ ],
69
+ "configSchema": "config.d.ts",
70
+ "module": "./dist/index.esm.js"
71
+ }