diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4cac8f6dd81..7843dca6c87 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -425,6 +425,7 @@ i18next.config.ts @grafana/grafana-frontend-platform /public/locales/enterprise/i18next.config.ts @grafana/grafana-frontend-platform /public/app/core/internationalization/ @grafana/grafana-frontend-platform /e2e/ @grafana/grafana-frontend-platform +/e2e-playwright/alerting-suite/ @grafana/alerting-frontend /e2e-playwright/cloud-plugins-suite/ @grafana/partner-datasources /e2e-playwright/dashboard-new-layouts/ @grafana/dashboards-squad /e2e-playwright/dashboard-cujs/ @grafana/dashboards-squad diff --git a/.github/actions/change-detection/action.yml b/.github/actions/change-detection/action.yml index 863cab646b9..2b8484d7cf6 100644 --- a/.github/actions/change-detection/action.yml +++ b/.github/actions/change-detection/action.yml @@ -99,6 +99,7 @@ runs: - '${{ inputs.self }}' e2e: - 'e2e/**' + - 'e2e-playwright/**' - '.github/actions/setup-enterprise/**' - '.github/actions/checkout/**' - 'emails/**' diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json index 7c7c479199d..62648d7a4aa 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json @@ -71,12 +71,11 @@ "id": 1, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": false, - "rounded": true, - "spotlight": false, "gradient": false }, "orientation": "auto", @@ -150,12 +149,11 @@ "id": 4, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": true, - "rounded": true, - "spotlight": false, "gradient": false }, "orientation": "auto", @@ -229,12 +227,11 @@ "id": 3, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": false, "gradient": false }, "orientation": "auto", @@ -271,85 +268,6 @@ "title": "Center and bar glow", "type": "radialbar" }, - { - "datasource": { - "type": "grafana-testdata-datasource" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "max": 100, - "min": 0, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": 0 - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 6, - "w": 4, - "x": 12, - "y": 1 - }, - "id": 5, - "maxDataPoints": 20, - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "rounded": true, - "spotlight": true, - "gradient": false - }, - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "pluginVersion": "13.0.0-pre", - "targets": [ - { - "alias": "1", - "datasource": { - "type": "grafana-testdata-datasource" - }, - "max": 100, - "min": 1, - "noise": 22, - "refId": "A", - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - ], - "title": "Spotlight", - "type": "radialbar" - }, { "datasource": { "type": "grafana-testdata-datasource" @@ -391,10 +309,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -470,10 +387,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": false, - "spotlight": true, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -549,10 +465,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": false, - "spotlight": true, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -641,10 +556,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -720,10 +634,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -799,10 +712,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -878,10 +790,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -974,10 +885,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1053,10 +963,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1132,10 +1041,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1211,10 +1119,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1290,10 +1197,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1386,10 +1292,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1469,10 +1374,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1552,10 +1456,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1641,13 +1544,13 @@ "options": { "barWidth": 12, "barWidthFactor": 0.4, + "barShape": "rounded", "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1662,8 +1565,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1730,10 +1632,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1748,8 +1649,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1830,10 +1730,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1848,8 +1747,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1917,9 +1815,6 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "sparkline": false, - "spotlight": true, "gradient": true }, "glow": "both", @@ -1934,10 +1829,10 @@ "segmentCount": 12, "segmentSpacing": 0.3, "shape": "circle", + "barShape": "rounded", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2004,10 +1899,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2022,8 +1916,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2090,10 +1983,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "rounded": true, - "spotlight": true, "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2108,8 +2000,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json index a3de6df336a..dda0fbcd432 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json @@ -955,8 +955,6 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false }, "orientation": "auto", diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json index 2eeb3040e6d..e04d448a5b8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json @@ -77,13 +77,12 @@ "id": 1, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -156,13 +155,12 @@ "id": 4, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -235,13 +233,12 @@ "id": 3, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -277,85 +274,6 @@ "title": "Center and bar glow", "type": "radialbar" }, - { - "datasource": { - "type": "grafana-testdata-datasource" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "max": 100, - "min": 0, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": 0 - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 6, - "w": 4, - "x": 12, - "y": 1 - }, - "id": 5, - "maxDataPoints": 20, - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true - }, - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "pluginVersion": "13.0.0-pre", - "targets": [ - { - "alias": "1", - "datasource": { - "type": "grafana-testdata-datasource" - }, - "max": 100, - "min": 1, - "noise": 22, - "refId": "A", - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - ], - "title": "Spotlight", - "type": "radialbar" - }, { "datasource": { "type": "grafana-testdata-datasource" @@ -393,13 +311,12 @@ "id": 8, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -472,13 +389,12 @@ "id": 22, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -551,13 +467,12 @@ "id": 23, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -643,13 +558,12 @@ "id": 18, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.1, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -722,13 +636,12 @@ "id": 19, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.32, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -801,13 +714,12 @@ "id": 20, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.57, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -880,13 +792,12 @@ "id": 21, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.8, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -976,13 +887,12 @@ "id": 25, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1055,13 +965,12 @@ "id": 26, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1134,13 +1043,12 @@ "id": 29, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1213,13 +1121,12 @@ "id": 30, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1292,13 +1199,12 @@ "id": 28, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1388,13 +1294,12 @@ "id": 32, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1471,13 +1376,12 @@ "id": 34, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1554,13 +1458,12 @@ "id": 33, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1645,15 +1548,15 @@ "id": 9, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1668,8 +1571,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1731,14 +1633,13 @@ "id": 11, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1754,8 +1655,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1831,14 +1731,13 @@ "id": 13, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1854,8 +1753,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1918,15 +1816,13 @@ "id": 14, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "sparkline": false, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1942,8 +1838,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2005,14 +1900,13 @@ "id": 15, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.84, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -2028,8 +1922,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2091,14 +1984,13 @@ "id": 16, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.66, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -2114,8 +2006,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2160,4 +2051,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json index 4aecf4e0d9c..0e6e3e13da5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json @@ -73,13 +73,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -165,14 +164,13 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -188,8 +186,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "fieldConfig": { "defaults": { @@ -262,14 +259,13 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -285,8 +281,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -360,15 +355,13 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "sparkline": false, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -384,8 +377,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -459,14 +451,13 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.84, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -482,8 +473,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -556,14 +546,13 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.66, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -579,8 +568,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -653,13 +641,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.1, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -745,13 +732,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.32, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -837,13 +823,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.57, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -929,13 +914,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.8, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1021,13 +1005,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1113,13 +1096,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1201,13 +1183,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1293,13 +1274,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1385,13 +1365,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1477,13 +1456,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1573,13 +1551,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1661,13 +1638,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1753,13 +1729,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1849,13 +1824,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1945,13 +1919,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -2045,105 +2018,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false - }, - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "fieldConfig": { - "defaults": { - "min": 0, - "max": 100, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "value": 0, - "color": "green" - }, - { - "value": 80, - "color": "red" - } - ] - }, - "color": { - "mode": "thresholds" - } - }, - "overrides": [] - } - } - } - } - }, - "panel-5": { - "kind": "Panel", - "spec": { - "id": 5, - "title": "Spotlight", - "description": "", - "links": [], - "data": { - "kind": "QueryGroup", - "spec": { - "queries": [ - { - "kind": "PanelQuery", - "spec": { - "query": { - "kind": "grafana-testdata-datasource", - "spec": { - "alias": "1", - "max": 100, - "min": 1, - "noise": 22, - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - }, - "refId": "A", - "hidden": false - } - } - ], - "transformations": [], - "queryOptions": { - "maxDataPoints": 20 - } - } - }, - "vizConfig": { - "kind": "radialbar", - "spec": { - "pluginVersion": "13.0.0-pre", - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -2229,13 +2109,12 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -2321,15 +2200,15 @@ "spec": { "pluginVersion": "13.0.0-pre", "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2344,8 +2223,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -2429,19 +2307,6 @@ } } }, - { - "kind": "GridLayoutItem", - "spec": { - "x": 12, - "y": 0, - "width": 4, - "height": 6, - "element": { - "kind": "ElementReference", - "name": "panel-5" - } - } - }, { "kind": "GridLayoutItem", "spec": { @@ -2826,4 +2691,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json index 6b567f19b5e..ad2b8ca0385 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json @@ -77,13 +77,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -172,14 +171,13 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -195,8 +193,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "fieldConfig": { "defaults": { @@ -272,14 +269,13 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -295,8 +291,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -373,15 +368,13 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "sparkline": false, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -397,8 +390,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -475,14 +467,13 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.84, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -498,8 +489,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -575,14 +565,13 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.66, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -598,8 +587,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -675,13 +663,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.1, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -770,13 +757,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.32, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -865,13 +851,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.57, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -960,13 +945,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.8, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1055,13 +1039,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1150,13 +1133,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1241,13 +1223,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1336,13 +1317,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1431,13 +1411,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1526,13 +1505,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1625,13 +1603,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1716,13 +1693,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1811,13 +1787,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1910,13 +1885,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -2009,13 +1983,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -2112,108 +2085,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false - }, - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "fieldConfig": { - "defaults": { - "min": 0, - "max": 100, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "value": 0, - "color": "green" - }, - { - "value": 80, - "color": "red" - } - ] - }, - "color": { - "mode": "thresholds" - } - }, - "overrides": [] - } - } - } - } - }, - "panel-5": { - "kind": "Panel", - "spec": { - "id": 5, - "title": "Spotlight", - "description": "", - "links": [], - "data": { - "kind": "QueryGroup", - "spec": { - "queries": [ - { - "kind": "PanelQuery", - "spec": { - "query": { - "kind": "DataQuery", - "group": "grafana-testdata-datasource", - "version": "v0", - "spec": { - "alias": "1", - "max": 100, - "min": 1, - "noise": 22, - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - }, - "refId": "A", - "hidden": false - } - } - ], - "transformations": [], - "queryOptions": { - "maxDataPoints": 20 - } - } - }, - "vizConfig": { - "kind": "VizConfig", - "group": "radialbar", - "version": "13.0.0-pre", - "spec": { - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -2302,13 +2179,12 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -2397,15 +2273,15 @@ "version": "13.0.0-pre", "spec": { "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2420,8 +2296,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "fieldConfig": { "defaults": { @@ -2505,19 +2380,6 @@ } } }, - { - "kind": "GridLayoutItem", - "spec": { - "x": 12, - "y": 0, - "width": 4, - "height": 6, - "element": { - "kind": "ElementReference", - "name": "panel-5" - } - } - }, { "kind": "GridLayoutItem", "spec": { @@ -2902,4 +2764,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json index 959f0193ad6..1d9f7e56513 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json @@ -961,9 +961,7 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1175,4 +1173,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json index 66b29e88d13..7b3f601b5cf 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json @@ -864,9 +864,7 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1620,4 +1618,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json index b870d0a91ad..534e7a1600c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json @@ -901,9 +901,7 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1672,4 +1670,4 @@ "storedVersion": "v0alpha1" } } -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json index a89d8744f39..cb130445efc 100644 --- a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json +++ b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json @@ -75,10 +75,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -154,10 +153,9 @@ "effects": { "barGlow": false, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -233,10 +231,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -305,85 +302,6 @@ "x": 12, "y": 1 }, - "id": 5, - "maxDataPoints": 20, - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true - }, - "orientation": "auto", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "pluginVersion": "13.0.0-pre", - "targets": [ - { - "alias": "1", - "datasource": { - "type": "grafana-testdata-datasource" - }, - "max": 100, - "min": 1, - "noise": 22, - "refId": "A", - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - ], - "title": "Spotlight", - "type": "radialbar" - }, - { - "datasource": { - "type": "grafana-testdata-datasource" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "max": 100, - "min": 0, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": 0 - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 6, - "w": 4, - "x": 16, - "y": 1 - }, "id": 8, "maxDataPoints": 20, "options": { @@ -391,10 +309,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -460,8 +377,8 @@ "gridPos": { "h": 6, "w": 4, - "x": 0, - "y": 7 + "x": 16, + "y": 1 }, "id": 22, "maxDataPoints": 20, @@ -470,10 +387,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -539,8 +455,8 @@ "gridPos": { "h": 6, "w": 4, - "x": 4, - "y": 7 + "x": 20, + "y": 1 }, "id": 23, "maxDataPoints": 20, @@ -549,10 +465,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -593,7 +508,7 @@ "h": 1, "w": 24, "x": 0, - "y": 13 + "y": 7 }, "id": 17, "panels": [], @@ -630,9 +545,9 @@ }, "gridPos": { "h": 6, - "w": 5, + "w": 4, "x": 0, - "y": 14 + "y": 8 }, "id": 18, "maxDataPoints": 20, @@ -641,10 +556,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -709,9 +623,9 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 5, - "y": 14 + "w": 4, + "x": 4, + "y": 8 }, "id": 19, "maxDataPoints": 20, @@ -720,10 +634,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -788,9 +701,9 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 10, - "y": 14 + "w": 4, + "x": 8, + "y": 8 }, "id": 20, "maxDataPoints": 20, @@ -799,10 +712,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -867,9 +779,9 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 15, - "y": 14 + "w": 4, + "x": 12, + "y": 8 }, "id": 21, "maxDataPoints": 20, @@ -878,10 +790,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, + "barShape": "rounded", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -922,7 +833,7 @@ "h": 1, "w": 24, "x": 0, - "y": 20 + "y": 14 }, "id": 24, "panels": [], @@ -963,9 +874,9 @@ }, "gridPos": { "h": 6, - "w": 6, + "w": 4, "x": 0, - "y": 21 + "y": 15 }, "id": 25, "maxDataPoints": 20, @@ -974,10 +885,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1042,9 +952,9 @@ }, "gridPos": { "h": 6, - "w": 6, - "x": 6, - "y": 21 + "w": 4, + "x": 4, + "y": 15 }, "id": 26, "maxDataPoints": 20, @@ -1053,10 +963,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1121,9 +1030,9 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 12, - "y": 21 + "w": 4, + "x": 8, + "y": 15 }, "id": 29, "maxDataPoints": 20, @@ -1132,10 +1041,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1199,10 +1107,10 @@ "overrides": [] }, "gridPos": { - "h": 7, - "w": 6, - "x": 0, - "y": 27 + "h": 6, + "w": 4, + "x": 12, + "y": 15 }, "id": 30, "maxDataPoints": 20, @@ -1211,10 +1119,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1278,10 +1185,10 @@ "overrides": [] }, "gridPos": { - "h": 7, - "w": 6, - "x": 6, - "y": 27 + "h": 6, + "w": 4, + "x": 16, + "y": 15 }, "id": 28, "maxDataPoints": 20, @@ -1290,10 +1197,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1330,7 +1236,7 @@ "h": 1, "w": 24, "x": 0, - "y": 34 + "y": 21 }, "id": 31, "panels": [], @@ -1377,7 +1283,7 @@ "h": 10, "w": 7, "x": 0, - "y": 35 + "y": 22 }, "id": 32, "maxDataPoints": 20, @@ -1386,10 +1292,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1460,7 +1365,7 @@ "h": 10, "w": 7, "x": 7, - "y": 35 + "y": 22 }, "id": 34, "maxDataPoints": 20, @@ -1469,10 +1374,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1543,7 +1447,7 @@ "h": 10, "w": 6, "x": 14, - "y": 35 + "y": 22 }, "id": 33, "maxDataPoints": 20, @@ -1552,10 +1456,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1592,7 +1495,7 @@ "h": 1, "w": 24, "x": 0, - "y": 45 + "y": 32 }, "id": 6, "panels": [], @@ -1633,20 +1536,20 @@ "h": 6, "w": 24, "x": 0, - "y": 46 + "y": 33 }, "id": 9, "maxDataPoints": 20, "options": { "barWidth": 12, "barWidthFactor": 0.4, + "barShape": "rounded", "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1661,8 +1564,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1717,7 +1619,7 @@ "h": 6, "w": 24, "x": 0, - "y": 52 + "y": 39 }, "id": 11, "maxDataPoints": 20, @@ -1727,10 +1629,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1745,8 +1646,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1773,7 +1673,7 @@ "h": 1, "w": 24, "x": 0, - "y": 58 + "y": 45 }, "id": 12, "panels": [], @@ -1815,7 +1715,7 @@ "h": 7, "w": 4, "x": 0, - "y": 59 + "y": 46 }, "id": 13, "maxDataPoints": 20, @@ -1825,10 +1725,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1843,8 +1742,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1900,7 +1798,7 @@ "h": 7, "w": 5, "x": 4, - "y": 59 + "y": 46 }, "id": 14, "maxDataPoints": 20, @@ -1910,10 +1808,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1928,8 +1825,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1984,7 +1880,7 @@ "h": 7, "w": 5, "x": 9, - "y": 59 + "y": 46 }, "id": 15, "maxDataPoints": 20, @@ -1994,10 +1890,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2012,8 +1907,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2068,7 +1962,7 @@ "h": 7, "w": 6, "x": 14, - "y": 59 + "y": 46 }, "id": 16, "maxDataPoints": 20, @@ -2078,10 +1972,9 @@ "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "barShape": "rounded", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -2096,8 +1989,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2124,7 +2016,7 @@ "h": 1, "w": 24, "x": 0, - "y": 66 + "y": 53 }, "id": 35, "panels": [], @@ -2155,10 +2047,10 @@ "overrides": [] }, "gridPos": { - "h": 8, - "w": 6, + "h": 5, + "w": 12, "x": 0, - "y": 67 + "y": 54 }, "id": 36, "options": { @@ -2166,10 +2058,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2223,10 +2114,10 @@ "overrides": [] }, "gridPos": { - "h": 8, - "w": 6, - "x": 6, - "y": 67 + "h": 5, + "w": 12, + "x": 12, + "y": 54 }, "id": 37, "options": { @@ -2234,10 +2125,9 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, + "barShape": "flat", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2279,4 +2169,4 @@ "title": "Panel tests - Gauge (new)", "uid": "panel-tests-gauge-new", "weekStart": "" -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json index 4a5ac97a6b5..dda0fbcd432 100644 --- a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json +++ b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json @@ -955,9 +955,7 @@ "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1162,4 +1160,4 @@ "title": "Panel tests - Old gauge to new", "uid": "panel-tests-old-gauge-to-new", "weekStart": "" -} \ No newline at end of file +} diff --git a/apps/provisioning/pkg/auth/access_checker.go b/apps/provisioning/pkg/auth/access_checker.go new file mode 100644 index 00000000000..841c5421f2a --- /dev/null +++ b/apps/provisioning/pkg/auth/access_checker.go @@ -0,0 +1,22 @@ +package auth + +import ( + "context" + + authlib "github.com/grafana/authlib/types" + "github.com/grafana/grafana/pkg/apimachinery/identity" +) + +//go:generate mockery --name AccessChecker --structname MockAccessChecker --inpackage --filename access_checker_mock.go --with-expecter + +// AccessChecker provides access control checks with optional role-based fallback. +type AccessChecker interface { + // Check performs an access check and returns nil if allowed, or an appropriate + // API error if denied. If req.Namespace is empty, it will be filled from the + // identity's namespace. + Check(ctx context.Context, req authlib.CheckRequest, folder string) error + + // WithFallbackRole returns an AccessChecker configured with the specified fallback role. + // Whether the fallback is actually applied depends on the implementation. + WithFallbackRole(role identity.RoleType) AccessChecker +} diff --git a/apps/provisioning/pkg/auth/access_checker_mock.go b/apps/provisioning/pkg/auth/access_checker_mock.go new file mode 100644 index 00000000000..d0f1cddd7fc --- /dev/null +++ b/apps/provisioning/pkg/auth/access_checker_mock.go @@ -0,0 +1,135 @@ +// Code generated by mockery v2.53.4. DO NOT EDIT. + +package auth + +import ( + context "context" + + identity "github.com/grafana/grafana/pkg/apimachinery/identity" + mock "github.com/stretchr/testify/mock" + + types "github.com/grafana/authlib/types" +) + +// MockAccessChecker is an autogenerated mock type for the AccessChecker type +type MockAccessChecker struct { + mock.Mock +} + +type MockAccessChecker_Expecter struct { + mock *mock.Mock +} + +func (_m *MockAccessChecker) EXPECT() *MockAccessChecker_Expecter { + return &MockAccessChecker_Expecter{mock: &_m.Mock} +} + +// Check provides a mock function with given fields: ctx, req, folder +func (_m *MockAccessChecker) Check(ctx context.Context, req types.CheckRequest, folder string) error { + ret := _m.Called(ctx, req, folder) + + if len(ret) == 0 { + panic("no return value specified for Check") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, types.CheckRequest, string) error); ok { + r0 = rf(ctx, req, folder) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// MockAccessChecker_Check_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Check' +type MockAccessChecker_Check_Call struct { + *mock.Call +} + +// Check is a helper method to define mock.On call +// - ctx context.Context +// - req types.CheckRequest +// - folder string +func (_e *MockAccessChecker_Expecter) Check(ctx interface{}, req interface{}, folder interface{}) *MockAccessChecker_Check_Call { + return &MockAccessChecker_Check_Call{Call: _e.mock.On("Check", ctx, req, folder)} +} + +func (_c *MockAccessChecker_Check_Call) Run(run func(ctx context.Context, req types.CheckRequest, folder string)) *MockAccessChecker_Check_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context), args[1].(types.CheckRequest), args[2].(string)) + }) + return _c +} + +func (_c *MockAccessChecker_Check_Call) Return(_a0 error) *MockAccessChecker_Check_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockAccessChecker_Check_Call) RunAndReturn(run func(context.Context, types.CheckRequest, string) error) *MockAccessChecker_Check_Call { + _c.Call.Return(run) + return _c +} + +// WithFallbackRole provides a mock function with given fields: role +func (_m *MockAccessChecker) WithFallbackRole(role identity.RoleType) AccessChecker { + ret := _m.Called(role) + + if len(ret) == 0 { + panic("no return value specified for WithFallbackRole") + } + + var r0 AccessChecker + if rf, ok := ret.Get(0).(func(identity.RoleType) AccessChecker); ok { + r0 = rf(role) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(AccessChecker) + } + } + + return r0 +} + +// MockAccessChecker_WithFallbackRole_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WithFallbackRole' +type MockAccessChecker_WithFallbackRole_Call struct { + *mock.Call +} + +// WithFallbackRole is a helper method to define mock.On call +// - role identity.RoleType +func (_e *MockAccessChecker_Expecter) WithFallbackRole(role interface{}) *MockAccessChecker_WithFallbackRole_Call { + return &MockAccessChecker_WithFallbackRole_Call{Call: _e.mock.On("WithFallbackRole", role)} +} + +func (_c *MockAccessChecker_WithFallbackRole_Call) Run(run func(role identity.RoleType)) *MockAccessChecker_WithFallbackRole_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(identity.RoleType)) + }) + return _c +} + +func (_c *MockAccessChecker_WithFallbackRole_Call) Return(_a0 AccessChecker) *MockAccessChecker_WithFallbackRole_Call { + _c.Call.Return(_a0) + return _c +} + +func (_c *MockAccessChecker_WithFallbackRole_Call) RunAndReturn(run func(identity.RoleType) AccessChecker) *MockAccessChecker_WithFallbackRole_Call { + _c.Call.Return(run) + return _c +} + +// NewMockAccessChecker creates a new instance of MockAccessChecker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockAccessChecker(t interface { + mock.TestingT + Cleanup(func()) +}) *MockAccessChecker { + mock := &MockAccessChecker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/apps/provisioning/pkg/auth/round_tripper.go b/apps/provisioning/pkg/auth/round_tripper.go index 0d2f1cb4ac4..f5da0d778f0 100644 --- a/apps/provisioning/pkg/auth/round_tripper.go +++ b/apps/provisioning/pkg/auth/round_tripper.go @@ -1,3 +1,4 @@ +// Package auth provides authentication utilities for the provisioning API. package auth import ( @@ -6,7 +7,6 @@ import ( "net/http" "github.com/grafana/authlib/authn" - "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" utilnet "k8s.io/apimachinery/pkg/util/net" ) @@ -15,29 +15,61 @@ type tokenExchanger interface { Exchange(ctx context.Context, req authn.TokenExchangeRequest) (*authn.TokenExchangeResponse, error) } -// RoundTripper injects an exchanged access token for the provisioning API into outgoing requests. -type RoundTripper struct { - client tokenExchanger - transport http.RoundTripper - audience string +// RoundTripperOption configures optional behavior for the RoundTripper. +type RoundTripperOption func(*RoundTripper) + +// ExtraAudience appends an additional audience to the token exchange request. +// +// This is primarily used by operators connecting to the multitenant aggregator, +// where the token must include both the target API server's audience (e.g., dashboards, +// folders) and the provisioning group audience. The provisioning group audience is +// required so that the token passes the enforceManagerProperties check, which prevents +// unauthorized updates to provisioned resources. +// +// Example: +// +// authrt.NewRoundTripper(client, rt, "dashboards.grafana.app", authrt.ExtraAudience("provisioning.grafana.app")) +func ExtraAudience(audience string) RoundTripperOption { + return func(rt *RoundTripper) { + rt.extraAudience = audience + } } -// NewRoundTripper constructs a RoundTripper that exchanges the provided token per request -// and forwards the request to the provided base transport. -func NewRoundTripper(tokenExchangeClient tokenExchanger, base http.RoundTripper, audience string) *RoundTripper { - return &RoundTripper{ +// RoundTripper is an http.RoundTripper that performs token exchange before each request. +// It exchanges the service's credentials for an access token scoped to the configured +// audience(s), then injects that token into the outgoing request's X-Access-Token header. +type RoundTripper struct { + client tokenExchanger + transport http.RoundTripper + audience string + extraAudience string +} + +// NewRoundTripper creates a RoundTripper that exchanges tokens for each outgoing request. +// +// Parameters: +// - tokenExchangeClient: the client used to exchange credentials for access tokens +// - base: the underlying transport to delegate requests to after token injection +// - audience: the primary audience for the token (typically the target API server's group) +// - opts: optional configuration (e.g., ExtraAudience to include additional audiences) +func NewRoundTripper(tokenExchangeClient tokenExchanger, base http.RoundTripper, audience string, opts ...RoundTripperOption) *RoundTripper { + rt := &RoundTripper{ client: tokenExchangeClient, transport: base, audience: audience, } + for _, opt := range opts { + opt(rt) + } + return rt } +// RoundTrip exchanges credentials for an access token and injects it into the request. +// The token is scoped to all configured audiences and the wildcard namespace ("*"). func (t *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - // when we want to write resources with the provisioning API, the audience needs to include provisioning - // so that it passes the check in enforceManagerProperties, which prevents others from updating provisioned resources audiences := []string{t.audience} - if t.audience != v0alpha1.GROUP { - audiences = append(audiences, v0alpha1.GROUP) + if t.extraAudience != "" && t.extraAudience != t.audience { + audiences = append(audiences, t.extraAudience) } tokenResponse, err := t.client.Exchange(req.Context(), authn.TokenExchangeRequest{ diff --git a/apps/provisioning/pkg/auth/round_tripper_test.go b/apps/provisioning/pkg/auth/round_tripper_test.go index e3ae4b7b3d4..c1b2b81e17f 100644 --- a/apps/provisioning/pkg/auth/round_tripper_test.go +++ b/apps/provisioning/pkg/auth/round_tripper_test.go @@ -71,16 +71,29 @@ func TestRoundTripper_AudiencesAndNamespace(t *testing.T) { tests := []struct { name string audience string + extraAudience string wantAudiences []string }{ { - name: "adds group when custom audience", + name: "uses only provided audience by default", audience: "example-audience", + wantAudiences: []string{"example-audience"}, + }, + { + name: "uses only group audience by default", + audience: v0alpha1.GROUP, + wantAudiences: []string{v0alpha1.GROUP}, + }, + { + name: "extra audience adds provisioning group", + audience: "example-audience", + extraAudience: v0alpha1.GROUP, wantAudiences: []string{"example-audience", v0alpha1.GROUP}, }, { - name: "no duplicate when group audience", + name: "extra audience no duplicate when same as primary", audience: v0alpha1.GROUP, + extraAudience: v0alpha1.GROUP, wantAudiences: []string{v0alpha1.GROUP}, }, } @@ -88,11 +101,15 @@ func TestRoundTripper_AudiencesAndNamespace(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fx := &fakeExchanger{resp: &authn.TokenExchangeResponse{Token: "abc123"}} + var opts []RoundTripperOption + if tt.extraAudience != "" { + opts = append(opts, ExtraAudience(tt.extraAudience)) + } tr := NewRoundTripper(fx, roundTripperFunc(func(_ *http.Request) (*http.Response, error) { rr := httptest.NewRecorder() rr.WriteHeader(http.StatusOK) return rr.Result(), nil - }), tt.audience) + }), tt.audience, opts...) req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example", nil) resp, err := tr.RoundTrip(req) diff --git a/apps/provisioning/pkg/auth/session_access_checker.go b/apps/provisioning/pkg/auth/session_access_checker.go new file mode 100644 index 00000000000..1bc6a1b7218 --- /dev/null +++ b/apps/provisioning/pkg/auth/session_access_checker.go @@ -0,0 +1,153 @@ +package auth + +import ( + "context" + "fmt" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime/schema" + + authlib "github.com/grafana/authlib/types" + "github.com/grafana/grafana-app-sdk/logging" + "github.com/grafana/grafana/pkg/apimachinery/identity" +) + +// sessionAccessChecker implements AccessChecker using Grafana session identity. +type sessionAccessChecker struct { + inner authlib.AccessChecker + fallbackRole identity.RoleType +} + +// NewSessionAccessChecker creates an AccessChecker that gets identity from Grafana +// sessions via GetRequester(ctx). Supports optional role-based fallback via +// WithFallbackRole for backwards compatibility. +func NewSessionAccessChecker(inner authlib.AccessChecker) AccessChecker { + return &sessionAccessChecker{ + inner: inner, + fallbackRole: "", + } +} + +// WithFallbackRole returns a new AccessChecker with the specified fallback role. +func (c *sessionAccessChecker) WithFallbackRole(role identity.RoleType) AccessChecker { + return &sessionAccessChecker{ + inner: c.inner, + fallbackRole: role, + } +} + +// Check performs an access check with optional role-based fallback. +// Returns nil if access is allowed, or an appropriate API error if denied. +func (c *sessionAccessChecker) Check(ctx context.Context, req authlib.CheckRequest, folder string) error { + logger := logging.FromContext(ctx).With("logger", "sessionAccessChecker") + + // Get identity from Grafana session + requester, err := identity.GetRequester(ctx) + if err != nil { + logger.Debug("failed to get requester", + "resource", req.Resource, + "verb", req.Verb, + "error", err.Error(), + ) + return apierrors.NewUnauthorized(fmt.Sprintf("failed to get requester: %v", err)) + } + + logger.Debug("checking access", + "identityType", requester.GetIdentityType(), + "orgRole", requester.GetOrgRole(), + "namespace", requester.GetNamespace(), + "resource", req.Resource, + "verb", req.Verb, + "group", req.Group, + "name", req.Name, + "folder", folder, + "fallbackRole", c.fallbackRole, + ) + + // Fill in namespace from identity if not provided + if req.Namespace == "" { + req.Namespace = requester.GetNamespace() + } + + // Perform the access check + rsp, err := c.inner.Check(ctx, requester, req, folder) + + // Build the GroupResource for error messages + gr := schema.GroupResource{Group: req.Group, Resource: req.Resource} + + // No fallback configured, return result directly + if c.fallbackRole == "" { + if err != nil { + logger.Debug("access check error (no fallback)", + "resource", req.Resource, + "verb", req.Verb, + "error", err.Error(), + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("%s.%s is forbidden: %w", req.Resource, req.Group, err)) + } + if !rsp.Allowed { + logger.Debug("access check denied (no fallback)", + "resource", req.Resource, + "verb", req.Verb, + "group", req.Group, + "allowed", rsp.Allowed, + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("permission denied")) + } + logger.Debug("access allowed", + "resource", req.Resource, + "verb", req.Verb, + ) + return nil + } + + // Fallback is configured - apply fallback logic + if err != nil { + if requester.GetOrgRole().Includes(c.fallbackRole) { + logger.Debug("access allowed via role fallback (after error)", + "resource", req.Resource, + "verb", req.Verb, + "fallbackRole", c.fallbackRole, + "orgRole", requester.GetOrgRole(), + ) + return nil // Fallback succeeded + } + logger.Debug("access check error (fallback failed)", + "resource", req.Resource, + "verb", req.Verb, + "error", err.Error(), + "fallbackRole", c.fallbackRole, + "orgRole", requester.GetOrgRole(), + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("%s.%s is forbidden: %w", req.Resource, req.Group, err)) + } + + if rsp.Allowed { + logger.Debug("access allowed", + "resource", req.Resource, + "verb", req.Verb, + ) + return nil + } + + // Fall back to role for backwards compatibility + if requester.GetOrgRole().Includes(c.fallbackRole) { + logger.Debug("access allowed via role fallback", + "resource", req.Resource, + "verb", req.Verb, + "fallbackRole", c.fallbackRole, + "orgRole", requester.GetOrgRole(), + ) + return nil // Fallback succeeded + } + + logger.Debug("access denied (fallback role not met)", + "resource", req.Resource, + "verb", req.Verb, + "group", req.Group, + "fallbackRole", c.fallbackRole, + "orgRole", requester.GetOrgRole(), + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("%s role is required", strings.ToLower(string(c.fallbackRole)))) +} diff --git a/apps/provisioning/pkg/auth/session_access_checker_test.go b/apps/provisioning/pkg/auth/session_access_checker_test.go new file mode 100644 index 00000000000..1e99a6e46db --- /dev/null +++ b/apps/provisioning/pkg/auth/session_access_checker_test.go @@ -0,0 +1,244 @@ +package auth + +import ( + "context" + "errors" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + + authlib "github.com/grafana/authlib/types" + "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/services/user" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// mockRequester implements identity.Requester for testing. +type mockRequester struct { + identity.Requester + orgRole identity.RoleType + identityType authlib.IdentityType + namespace string +} + +func (m *mockRequester) GetOrgRole() identity.RoleType { + return m.orgRole +} + +func (m *mockRequester) GetIdentityType() authlib.IdentityType { + return m.identityType +} + +func (m *mockRequester) GetNamespace() string { + return m.namespace +} + +func TestSessionAccessChecker_Check(t *testing.T) { + ctx := context.Background() + req := authlib.CheckRequest{ + Verb: "get", + Group: "provisioning.grafana.app", + Resource: "repositories", + Name: "test-repo", + Namespace: "default", + } + + tests := []struct { + name string + fallbackRole identity.RoleType + innerResponse authlib.CheckResponse + innerErr error + requester *mockRequester + expectAllow bool + }{ + { + name: "allowed by checker", + fallbackRole: identity.RoleAdmin, + innerResponse: authlib.CheckResponse{Allowed: true}, + requester: &mockRequester{orgRole: identity.RoleViewer, identityType: authlib.TypeUser}, + expectAllow: true, + }, + { + name: "denied by checker, fallback to admin role succeeds", + fallbackRole: identity.RoleAdmin, + innerResponse: authlib.CheckResponse{Allowed: false}, + requester: &mockRequester{orgRole: identity.RoleAdmin, identityType: authlib.TypeUser}, + expectAllow: true, + }, + { + name: "denied by checker, fallback to admin role fails for viewer", + fallbackRole: identity.RoleAdmin, + innerResponse: authlib.CheckResponse{Allowed: false}, + requester: &mockRequester{orgRole: identity.RoleViewer, identityType: authlib.TypeUser}, + expectAllow: false, + }, + { + name: "error from checker, fallback to admin role succeeds", + fallbackRole: identity.RoleAdmin, + innerErr: errors.New("access check failed"), + requester: &mockRequester{orgRole: identity.RoleAdmin, identityType: authlib.TypeUser}, + expectAllow: true, + }, + { + name: "error from checker, fallback fails for viewer", + fallbackRole: identity.RoleAdmin, + innerErr: errors.New("access check failed"), + requester: &mockRequester{orgRole: identity.RoleViewer, identityType: authlib.TypeUser}, + expectAllow: false, + }, + { + name: "denied, editor fallback succeeds for editor", + fallbackRole: identity.RoleEditor, + innerResponse: authlib.CheckResponse{Allowed: false}, + requester: &mockRequester{orgRole: identity.RoleEditor, identityType: authlib.TypeUser}, + expectAllow: true, + }, + { + name: "denied, editor fallback fails for viewer", + fallbackRole: identity.RoleEditor, + innerResponse: authlib.CheckResponse{Allowed: false}, + requester: &mockRequester{orgRole: identity.RoleViewer, identityType: authlib.TypeUser}, + expectAllow: false, + }, + { + name: "no fallback configured, denied stays denied", + fallbackRole: "", // no fallback + innerResponse: authlib.CheckResponse{Allowed: false}, + requester: &mockRequester{orgRole: identity.RoleAdmin, identityType: authlib.TypeUser}, + expectAllow: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: tt.innerResponse, + err: tt.innerErr, + } + + checker := NewSessionAccessChecker(mock) + if tt.fallbackRole != "" { + checker = checker.WithFallbackRole(tt.fallbackRole) + } + + // Add requester to context + testCtx := identity.WithRequester(ctx, tt.requester) + + err := checker.Check(testCtx, req, "") + + if tt.expectAllow { + require.NoError(t, err) + } else { + require.Error(t, err) + assert.True(t, apierrors.IsForbidden(err), "expected Forbidden error, got: %v", err) + } + }) + } +} + +func TestSessionAccessChecker_NoRequester(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: true}, + } + + checker := NewSessionAccessChecker(mock) + err := checker.Check(context.Background(), authlib.CheckRequest{}, "") + + require.Error(t, err) + assert.True(t, apierrors.IsUnauthorized(err), "expected Unauthorized error") +} + +func TestSessionAccessChecker_WithFallbackRole_ImmutableOriginal(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: false}, + } + + original := NewSessionAccessChecker(mock) + withAdmin := original.WithFallbackRole(identity.RoleAdmin) + withEditor := original.WithFallbackRole(identity.RoleEditor) + + ctx := identity.WithRequester(context.Background(), &mockRequester{ + orgRole: identity.RoleEditor, + identityType: authlib.TypeUser, + }) + + req := authlib.CheckRequest{} + + // Original should deny (no fallback) + err := original.Check(ctx, req, "") + require.Error(t, err, "original should deny without fallback") + + // WithAdmin should deny for editor + err = withAdmin.Check(ctx, req, "") + require.Error(t, err, "admin fallback should deny for editor") + + // WithEditor should allow for editor + err = withEditor.Check(ctx, req, "") + require.NoError(t, err, "editor fallback should allow for editor") +} + +func TestSessionAccessChecker_WithFallbackRole_ChainedCalls(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: false}, + } + + // Ensure chained WithFallbackRole calls work correctly + checker := NewSessionAccessChecker(mock). + WithFallbackRole(identity.RoleAdmin). + WithFallbackRole(identity.RoleEditor) // This should override admin + + ctx := identity.WithRequester(context.Background(), &mockRequester{ + orgRole: identity.RoleEditor, + identityType: authlib.TypeUser, + }) + + err := checker.Check(ctx, authlib.CheckRequest{}, "") + require.NoError(t, err, "last fallback (editor) should be used") +} + +func TestSessionAccessChecker_RealSignedInUser(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: false}, + } + + checker := NewSessionAccessChecker(mock).WithFallbackRole(identity.RoleAdmin) + + // Use a real SignedInUser + signedInUser := &user.SignedInUser{ + UserID: 1, + OrgID: 1, + OrgRole: identity.RoleAdmin, + } + + ctx := identity.WithRequester(context.Background(), signedInUser) + + err := checker.Check(ctx, authlib.CheckRequest{}, "") + require.NoError(t, err, "admin user should be allowed via fallback") +} + +func TestSessionAccessChecker_FillsNamespace(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: true}, + } + + checker := NewSessionAccessChecker(mock) + + ctx := identity.WithRequester(context.Background(), &mockRequester{ + orgRole: identity.RoleAdmin, + identityType: authlib.TypeUser, + namespace: "org-123", + }) + + // Request without namespace + req := authlib.CheckRequest{ + Verb: "get", + Group: "provisioning.grafana.app", + Resource: "repositories", + Name: "test-repo", + // Namespace intentionally empty + } + + err := checker.Check(ctx, req, "") + require.NoError(t, err) +} diff --git a/apps/provisioning/pkg/auth/token_access_checker.go b/apps/provisioning/pkg/auth/token_access_checker.go new file mode 100644 index 00000000000..8df833d7a34 --- /dev/null +++ b/apps/provisioning/pkg/auth/token_access_checker.go @@ -0,0 +1,92 @@ +package auth + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime/schema" + + authlib "github.com/grafana/authlib/types" + "github.com/grafana/grafana-app-sdk/logging" + "github.com/grafana/grafana/pkg/apimachinery/identity" +) + +// tokenAccessChecker implements AccessChecker using access tokens from context. +type tokenAccessChecker struct { + inner authlib.AccessChecker +} + +// NewTokenAccessChecker creates an AccessChecker that gets identity from access tokens +// via AuthInfoFrom(ctx). Role-based fallback is not supported. +func NewTokenAccessChecker(inner authlib.AccessChecker) AccessChecker { + return &tokenAccessChecker{inner: inner} +} + +// WithFallbackRole returns the same checker since fallback is not supported. +func (c *tokenAccessChecker) WithFallbackRole(_ identity.RoleType) AccessChecker { + return c +} + +// Check performs an access check using AuthInfo from context. +// Returns nil if access is allowed, or an appropriate API error if denied. +func (c *tokenAccessChecker) Check(ctx context.Context, req authlib.CheckRequest, folder string) error { + logger := logging.FromContext(ctx).With("logger", "tokenAccessChecker") + + // Get identity from access token in context + id, ok := authlib.AuthInfoFrom(ctx) + if !ok { + logger.Debug("no auth info in context", + "resource", req.Resource, + "verb", req.Verb, + "namespace", req.Namespace, + ) + return apierrors.NewUnauthorized("no auth info in context") + } + + logger.Debug("checking access", + "identityType", id.GetIdentityType(), + "namespace", id.GetNamespace(), + "resource", req.Resource, + "verb", req.Verb, + "group", req.Group, + "name", req.Name, + "folder", folder, + ) + + // Fill in namespace from identity if not provided + if req.Namespace == "" { + req.Namespace = id.GetNamespace() + } + + // Perform the access check + rsp, err := c.inner.Check(ctx, id, req, folder) + + // Build the GroupResource for error messages + gr := schema.GroupResource{Group: req.Group, Resource: req.Resource} + + if err != nil { + logger.Debug("access check error", + "resource", req.Resource, + "verb", req.Verb, + "error", err.Error(), + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("%s.%s is forbidden: %w", req.Resource, req.Group, err)) + } + if !rsp.Allowed { + logger.Debug("access check denied", + "resource", req.Resource, + "verb", req.Verb, + "group", req.Group, + "identityType", id.GetIdentityType(), + "allowed", rsp.Allowed, + ) + return apierrors.NewForbidden(gr, req.Name, fmt.Errorf("permission denied")) + } + + logger.Debug("access allowed", + "resource", req.Resource, + "verb", req.Verb, + ) + return nil +} diff --git a/apps/provisioning/pkg/auth/token_access_checker_test.go b/apps/provisioning/pkg/auth/token_access_checker_test.go new file mode 100644 index 00000000000..bce0d3a77a0 --- /dev/null +++ b/apps/provisioning/pkg/auth/token_access_checker_test.go @@ -0,0 +1,137 @@ +package auth + +import ( + "context" + "errors" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + + authlib "github.com/grafana/authlib/types" + "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestTokenAccessChecker_Check(t *testing.T) { + req := authlib.CheckRequest{ + Verb: "get", + Group: "provisioning.grafana.app", + Resource: "repositories", + Name: "test-repo", + Namespace: "default", + } + + tests := []struct { + name string + innerResponse authlib.CheckResponse + innerErr error + authInfo *identity.StaticRequester + expectAllow bool + }{ + { + name: "allowed by checker", + innerResponse: authlib.CheckResponse{Allowed: true}, + authInfo: &identity.StaticRequester{Type: authlib.TypeUser}, + expectAllow: true, + }, + { + name: "denied by checker", + innerResponse: authlib.CheckResponse{Allowed: false}, + authInfo: &identity.StaticRequester{Type: authlib.TypeUser}, + expectAllow: false, + }, + { + name: "error from checker", + innerErr: errors.New("access check failed"), + authInfo: &identity.StaticRequester{Type: authlib.TypeUser}, + expectAllow: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: tt.innerResponse, + err: tt.innerErr, + } + + checker := NewTokenAccessChecker(mock) + + // Add auth info to context + testCtx := authlib.WithAuthInfo(context.Background(), tt.authInfo) + + err := checker.Check(testCtx, req, "") + + if tt.expectAllow { + require.NoError(t, err) + } else { + require.Error(t, err) + assert.True(t, apierrors.IsForbidden(err), "expected Forbidden error, got: %v", err) + } + }) + } +} + +func TestTokenAccessChecker_NoAuthInfo(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: true}, + } + + checker := NewTokenAccessChecker(mock) + err := checker.Check(context.Background(), authlib.CheckRequest{}, "") + + require.Error(t, err) + assert.True(t, apierrors.IsUnauthorized(err), "expected Unauthorized error") +} + +func TestTokenAccessChecker_WithFallbackRole_IsNoOp(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: false}, + } + + checker := NewTokenAccessChecker(mock) + checkerWithFallback := checker.WithFallbackRole(identity.RoleAdmin) + + // They should be the same instance + assert.Same(t, checker, checkerWithFallback, "WithFallbackRole should return same instance") +} + +func TestTokenAccessChecker_FillsNamespace(t *testing.T) { + mock := &mockInnerAccessChecker{ + response: authlib.CheckResponse{Allowed: true}, + } + + checker := NewTokenAccessChecker(mock) + + ctx := authlib.WithAuthInfo(context.Background(), &identity.StaticRequester{ + Type: authlib.TypeUser, + Namespace: "org-123", + }) + + // Request without namespace + req := authlib.CheckRequest{ + Verb: "get", + Group: "provisioning.grafana.app", + Resource: "repositories", + Name: "test-repo", + // Namespace intentionally empty + } + + err := checker.Check(ctx, req, "") + require.NoError(t, err) +} + +// mockInnerAccessChecker implements authlib.AccessChecker for testing. +type mockInnerAccessChecker struct { + response authlib.CheckResponse + err error +} + +func (m *mockInnerAccessChecker) Check(_ context.Context, _ authlib.AuthInfo, _ authlib.CheckRequest, _ string) (authlib.CheckResponse, error) { + return m.response, m.err +} + +func (m *mockInnerAccessChecker) Compile(_ context.Context, _ authlib.AuthInfo, _ authlib.ListRequest) (authlib.ItemChecker, authlib.Zookie, error) { + return nil, nil, nil +} diff --git a/apps/provisioning/pkg/repository/tester.go b/apps/provisioning/pkg/repository/tester.go index 6bd65443d92..14290d0514b 100644 --- a/apps/provisioning/pkg/repository/tester.go +++ b/apps/provisioning/pkg/repository/tester.go @@ -23,7 +23,13 @@ func NewSimpleRepositoryTester(validator RepositoryValidator) SimpleRepositoryTe // TestRepository validates the repository and then runs a health check func (t *SimpleRepositoryTester) TestRepository(ctx context.Context, repo Repository) (*provisioning.TestResults, error) { - errors := t.validator.ValidateRepository(repo) + // Determine if this is a CREATE or UPDATE operation + // If the repository has been observed by the controller (ObservedGeneration > 0), + // it's an existing repository and we should treat it as UPDATE + cfg := repo.Config() + isCreate := cfg.Status.ObservedGeneration == 0 + + errors := t.validator.ValidateRepository(repo, isCreate) if len(errors) > 0 { rsp := &provisioning.TestResults{ Code: http.StatusUnprocessableEntity, // Invalid diff --git a/apps/provisioning/pkg/repository/validator.go b/apps/provisioning/pkg/repository/validator.go index 73198f0d7ee..46ba81f8cbd 100644 --- a/apps/provisioning/pkg/repository/validator.go +++ b/apps/provisioning/pkg/repository/validator.go @@ -32,7 +32,9 @@ func NewValidator(minSyncInterval time.Duration, allowedTargets []provisioning.S } // ValidateRepository solely does configuration checks on the repository object. It does not run a health check or compare against existing repositories. -func (v *RepositoryValidator) ValidateRepository(repo Repository) field.ErrorList { +// isCreate indicates whether this is a CREATE operation (true) or UPDATE operation (false). +// When isCreate is false, allowedTargets validation is skipped to allow existing repositories to continue working. +func (v *RepositoryValidator) ValidateRepository(repo Repository, isCreate bool) field.ErrorList { list := repo.Validate() cfg := repo.Config() @@ -44,7 +46,7 @@ func (v *RepositoryValidator) ValidateRepository(repo Repository) field.ErrorLis if cfg.Spec.Sync.Target == "" { list = append(list, field.Required(field.NewPath("spec", "sync", "target"), "The target type is required when sync is enabled")) - } else if !slices.Contains(v.allowedTargets, cfg.Spec.Sync.Target) { + } else if isCreate && !slices.Contains(v.allowedTargets, cfg.Spec.Sync.Target) { list = append(list, field.Invalid( field.NewPath("spec", "target"), diff --git a/apps/provisioning/pkg/repository/validator_test.go b/apps/provisioning/pkg/repository/validator_test.go index cb8b726a9bf..75980733e17 100644 --- a/apps/provisioning/pkg/repository/validator_test.go +++ b/apps/provisioning/pkg/repository/validator_test.go @@ -303,7 +303,8 @@ func TestValidateRepository(t *testing.T) { validator := NewValidator(10*time.Second, []provisioning.SyncTargetType{provisioning.SyncTargetTypeFolder}, false) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - errors := validator.ValidateRepository(tt.repository) + // Tests validate new configurations, so always pass isCreate=true + errors := validator.ValidateRepository(tt.repository, true) require.Len(t, errors, tt.expectedErrs) if tt.validateError != nil { tt.validateError(t, errors) diff --git a/conf/defaults.ini b/conf/defaults.ini index 8ee03e6a34c..28cd0420eb2 100644 --- a/conf/defaults.ini +++ b/conf/defaults.ini @@ -2264,7 +2264,7 @@ fail_tests_on_console = true # List of targets that can be controlled by a repository, separated by |. # Instance means the whole grafana instance will be controlled by a repository. # Folder limits it to a folder within the grafana instance. -allowed_targets = instance|folder +allowed_targets = folder # Whether image rendering is allowed for dashboard previews. # Requires image rendering service to be configured. diff --git a/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json b/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json index b3c47c9aa7a..65cc0b0a5ae 100644 --- a/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json +++ b/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json @@ -71,13 +71,12 @@ "id": 1, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -148,13 +147,12 @@ "id": 4, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": false, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -225,13 +223,12 @@ "id": 3, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -299,93 +296,15 @@ "x": 12, "y": 1 }, - "id": 5, - "maxDataPoints": 20, - "options": { - "barWidthFactor": 0.4, - "effects": { - "barGlow": true, - "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true - }, - "orientation": "auto", - "reduceOptions": { - "calcs": ["lastNotNull"], - "fields": "", - "values": false - }, - "segmentCount": 1, - "segmentSpacing": 0.3, - "shape": "circle", - "showThresholdLabels": false, - "showThresholdMarkers": false, - "sparkline": false - }, - "pluginVersion": "13.0.0-pre", - "targets": [ - { - "alias": "1", - "datasource": { - "type": "grafana-testdata-datasource" - }, - "max": 100, - "min": 1, - "noise": 22, - "refId": "A", - "scenarioId": "random_walk", - "spread": 22, - "startValue": 1 - } - ], - "title": "Spotlight", - "type": "radialbar" - }, - { - "datasource": { - "type": "grafana-testdata-datasource" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "max": 100, - "min": 0, - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": 0 - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 6, - "w": 4, - "x": 16, - "y": 1 - }, "id": 8, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -450,19 +369,18 @@ "gridPos": { "h": 6, "w": 4, - "x": 0, - "y": 7 + "x": 16, + "y": 1 }, "id": 22, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -527,19 +445,18 @@ "gridPos": { "h": 6, "w": 4, - "x": 4, - "y": 7 + "x": 20, + "y": 1 }, "id": 23, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": false, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -579,7 +496,7 @@ "h": 1, "w": 24, "x": 0, - "y": 13 + "y": 7 }, "id": 17, "panels": [], @@ -616,20 +533,19 @@ }, "gridPos": { "h": 6, - "w": 5, + "w": 4, "x": 0, - "y": 14 + "y": 8 }, "id": 18, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.1, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -693,20 +609,19 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 5, - "y": 14 + "w": 4, + "x": 4, + "y": 8 }, "id": 19, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.32, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -770,20 +685,19 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 10, - "y": 14 + "w": 4, + "x": 8, + "y": 8 }, "id": 20, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.57, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -847,20 +761,19 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 15, - "y": 14 + "w": 4, + "x": 12, + "y": 8 }, "id": 21, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidthFactor": 0.8, "effects": { "barGlow": true, "centerGlow": true, - "gradient": false, - "rounded": true, - "spotlight": true + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -900,7 +813,7 @@ "h": 1, "w": 24, "x": 0, - "y": 20 + "y": 14 }, "id": 24, "panels": [], @@ -941,20 +854,19 @@ }, "gridPos": { "h": 6, - "w": 6, + "w": 4, "x": 0, - "y": 21 + "y": 15 }, "id": 25, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1018,20 +930,19 @@ }, "gridPos": { "h": 6, - "w": 6, - "x": 6, - "y": 21 + "w": 4, + "x": 4, + "y": 15 }, "id": 26, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1095,20 +1006,19 @@ }, "gridPos": { "h": 6, - "w": 5, - "x": 12, - "y": 21 + "w": 4, + "x": 8, + "y": 15 }, "id": 29, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1171,21 +1081,20 @@ "overrides": [] }, "gridPos": { - "h": 7, - "w": 6, - "x": 0, - "y": 27 + "h": 6, + "w": 4, + "x": 12, + "y": 15 }, "id": 30, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1248,21 +1157,20 @@ "overrides": [] }, "gridPos": { - "h": 7, - "w": 6, - "x": 6, - "y": 27 + "h": 6, + "w": 4, + "x": 16, + "y": 15 }, "id": 28, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.72, "effects": { "barGlow": false, "centerGlow": false, - "gradient": false, - "rounded": false, - "spotlight": false + "gradient": false }, "orientation": "auto", "reduceOptions": { @@ -1298,7 +1206,7 @@ "h": 1, "w": 24, "x": 0, - "y": 34 + "y": 21 }, "id": 31, "panels": [], @@ -1345,18 +1253,17 @@ "h": 10, "w": 7, "x": 0, - "y": 35 + "y": 22 }, "id": 32, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1426,18 +1333,17 @@ "h": 10, "w": 7, "x": 7, - "y": 35 + "y": 22 }, "id": 34, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1507,18 +1413,17 @@ "h": 10, "w": 6, "x": 14, - "y": 35 + "y": 22 }, "id": 33, "maxDataPoints": 20, "options": { + "barShape": "flat", "barWidthFactor": 0.9, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -1554,7 +1459,7 @@ "h": 1, "w": 24, "x": 0, - "y": 45 + "y": 32 }, "id": 6, "panels": [], @@ -1595,20 +1500,20 @@ "h": 6, "w": 24, "x": 0, - "y": 46 + "y": 33 }, "id": 9, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, + "endpointMarker": "glow", "glow": "both", "orientation": "auto", "reduceOptions": { @@ -1621,8 +1526,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1677,19 +1581,18 @@ "h": 6, "w": 24, "x": 0, - "y": 52 + "y": 39 }, "id": 11, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.4, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1703,8 +1606,7 @@ "shape": "gauge", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": true, - "spotlight": true + "sparkline": true }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1731,7 +1633,7 @@ "h": 1, "w": 24, "x": 0, - "y": 58 + "y": 45 }, "id": 12, "panels": [], @@ -1773,19 +1675,18 @@ "h": 7, "w": 4, "x": 0, - "y": 59 + "y": 46 }, "id": 13, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1799,8 +1700,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1856,19 +1756,18 @@ "h": 7, "w": 5, "x": 4, - "y": 59 + "y": 46 }, "id": 14, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.49, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1882,8 +1781,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -1938,19 +1836,18 @@ "h": 7, "w": 5, "x": 9, - "y": 59 + "y": 46 }, "id": 15, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.84, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -1964,8 +1861,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2020,19 +1916,18 @@ "h": 7, "w": 6, "x": 14, - "y": 59 + "y": 46 }, "id": 16, "maxDataPoints": 20, "options": { + "barShape": "rounded", "barWidth": 12, "barWidthFactor": 0.66, "effects": { "barGlow": true, "centerGlow": true, - "gradient": true, - "rounded": true, - "spotlight": true + "gradient": true }, "glow": "both", "orientation": "auto", @@ -2046,8 +1941,7 @@ "shape": "circle", "showThresholdLabels": false, "showThresholdMarkers": false, - "sparkline": false, - "spotlight": true + "sparkline": false }, "pluginVersion": "13.0.0-pre", "targets": [ @@ -2074,7 +1968,7 @@ "h": 1, "w": 24, "x": 0, - "y": 66 + "y": 53 }, "id": 35, "panels": [], @@ -2105,20 +1999,19 @@ "overrides": [] }, "gridPos": { - "h": 8, - "w": 6, + "h": 5, + "w": 12, "x": 0, - "y": 67 + "y": 54 }, "id": 36, "options": { + "barShape": "flat", "barWidthFactor": 0.5, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -2171,20 +2064,19 @@ "overrides": [] }, "gridPos": { - "h": 8, - "w": 6, - "x": 6, - "y": 67 + "h": 5, + "w": 12, + "x": 12, + "y": 54 }, "id": 37, "options": { + "barShape": "flat", "barWidthFactor": 0.5, "effects": { "barGlow": false, "centerGlow": false, - "gradient": true, - "rounded": false, - "spotlight": false + "gradient": true }, "orientation": "auto", "reduceOptions": { @@ -2224,5 +2116,6 @@ "timezone": "browser", "title": "Panel tests - Gauge (new)", "uid": "panel-tests-gauge-new", - "version": 9 + "version": 22, + "weekStart": "" } diff --git a/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json b/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json index b071ddff802..bee1ece914e 100644 --- a/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json +++ b/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json @@ -956,8 +956,6 @@ "effects": { "barGlow": false, "centerGlow": false, - "rounded": false, - "spotlight": false, "gradient": false } } diff --git a/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md b/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md index d071ccca0de..ca71a0c0d9c 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md @@ -128,35 +128,48 @@ The set up process verifies the path and provides an error message if a problem #### Synchronization limitations -Full instance sync is not available in Grafana Cloud. +{{< admonition type="caution" >}} -In Grafana OSS/Enterprise: +Full instance sync is not available in Grafana Cloud and is experimental and unsupported in Grafana OSS/Enterprise. + +{{< /admonition >}} + +To have access to full instance sync you must explicitly enable the option. + +The following applies: -- If you try to perform a full instance sync with resources that contain alerts or panels, the connection will be blocked. - You won't be able to create new alerts or library panels after setup is completed. - If you opted for full instance sync and want to use alerts and library panels, you'll have to delete the provisioned repository and connect again with folder sync. #### Set up synchronization -Choose to either sync your entire organization resources with external storage, or to sync certain resources to a new Grafana folder (with up to 10 connections). +You can sync external resources into a new folder without affecting the rest of your instance. -- Choose **Sync all resources with external storage** if you want to sync and manage your entire Grafana instance through external storage. With this option, all of your dashboards are synced to that one repository. You can only have one provisioned connection with this selection, and you won't have the option of setting up additional repositories to connect to. +To set up synchronization: -- Choose **Sync external storage to new Grafana folder** to sync external resources into a new folder without affecting the rest of your instance. You can repeat this process for up to 10 connections. +1. Select which resources you want to sync. -Next, enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI. +1. Enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI. -Click **Synchronize** to continue. +1. Click **Synchronize** to continue. + +1. You can repeat this process for up to 10 connections. + +{{< admonition type="note" >}} + +Optionally, you can export any unmanaged resources into the provisioned folder. See how in [Synchronize with external storage](#synchronize-with-external-storage). + +{{< /admonition >}} ### Synchronize with external storage -After this one time step, all future updates are automatically saved to the local file path and provisioned back to the instance. +In this step you proceed to synchronize the resources selected in the previous step. Optionally, you can check the **Migrate existing resources** box to migrate your unmanaged dashboards to the provisioned folder. -During the initial synchronization, your dashboards will be temporarily unavailable. No data or configurations will be lost. +Select **Begin synchronization** to start the process. After this one time step, all future updates are automatically saved to the local file path and provisioned back to the instance. + +Note that during the initial synchronization, your dashboards will be temporarily unavailable. No data or configurations will be lost. How long the process takes depends upon the number of resources involved. -Select **Begin synchronization** to start the process. - ### Choose additional settings If you wish, you can make any files synchronized as as **Read only** so no changes can be made to the resources through Grafana. diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md index cd07c532dae..b43c279fb44 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md @@ -132,17 +132,35 @@ To connect your GitHub repository: ### Choose what to synchronize -In this step, you can decide which elements to synchronize. The available options depend on the status of your Grafana instance: - -- If the instance contains resources in an incompatible data format, you'll have to migrate all the data using instance sync. Folder sync won't be supported. -- If there's already another connection using folder sync, instance sync won't be offered. +You can sync external resources into a new folder without affecting the rest of your instance. To set up synchronization: -- Choose **Sync all resources with external storage** if you want to sync and manage your entire Grafana instance through external storage. With this option, all of your dashboards are synced to that one repository. You can only have one provisioned connection with this selection, and you won't have the option of setting up additional repositories to connect to. -- Choose **Sync external storage to new Grafana folder** to sync external resources into a new folder without affecting the rest of your instance. You can repeat this process for up to 10 connections. +1. Select which resources you want to sync. -Next, enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI. Click **Synchronize** to continue. +1. Enter a **Display name** for the repository connection. Resources stored in this connection appear under the chosen display name in the Grafana UI. + +1. Click **Synchronize** to continue. + +1. You can repeat this process for up to 10 connections. + +{{< admonition type="note" >}} + +Optionally, you can export any unmanaged resources into the provisioned folder. See how in [Synchronize with external storage](#synchronize-with-external-storage). + +{{< /admonition >}} + +#### Full instance sync + +Full instance sync is not available in Grafana Cloud and is experimental and unsupported in Grafana OSS/Enterprise. + +To have access to this option you must enable experimental instance sync on purpose. + +### Synchronize with external storage + +After this one time step, all future updates are automatically saved to the Git repository and provisioned back to the instance. + +Check the **Migrate existing resources** box to migrate your unmanaged dashboards to the provisioned folder. ### Choose additional settings diff --git a/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md b/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md index 9e32ce32e8a..903df6303a6 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md @@ -47,7 +47,7 @@ Using Git Sync, you can: {{< admonition type="caution" >}} -Git Sync only works with specific folders for the moment. Full-instance sync is not currently supported. +Full instance sync is not available in Grafana Cloud and is experimental and unsupported in Grafana OSS/Enterprise. {{< /admonition >}} @@ -84,7 +84,7 @@ Refer to [Requirements](https://grafana.com/docs/grafana//obser - You can only sync dashboards and folders. Refer to [Supported resources](#supported-resources) for more information. - If you're using Git Sync in Grafana OSS and Grafana Enterprise, some resources might be in an incompatible data format and won't be synced. -- Full-instance sync is not available in Grafana Cloud and has limitations in Grafana OSS and Grafana Enterprise. Refer to [Choose what to synchronize](../git-sync-setup/#choose-what-to-synchronize) for more details. +- Full-instance sync is not available in Grafana Cloud and is experimental in Grafana OSS and Grafana Enterprise. Refer to [Choose what to synchronize](../git-sync-setup/#choose-what-to-synchronize) for more details. - When migrating to full instance sync, during the synchronization process your resources will be temporarily unavailable. No one will be able to create, edit, or delete resources during this process. - If you want to manage existing resources with Git Sync, you need to save them as JSON files and commit them to the synced repository. Open a PR to import, copy, move, or save a dashboard. - Restoring resources from the UI is currently not possible. As an alternative, you can restore dashboards directly in your GitHub repository by raising a PR, and they will be updated in Grafana. diff --git a/docs/sources/datasources/_index.md b/docs/sources/datasources/_index.md index e7da61ea2f5..28d46c9c600 100644 --- a/docs/sources/datasources/_index.md +++ b/docs/sources/datasources/_index.md @@ -112,6 +112,12 @@ For example, this video demonstrates the visual Prometheus query builder: For general information about querying in Grafana, and common options and user interface elements across all query editors, refer to [Query and transform data](ref:query-transform-data). +## Build a dashboard from the data source + +After you've configured a data source, you can start creating a dashboard directly from it, by clicking the **Build a dashboard** button. + +For more information, refer to [Begin dashboard creation from data source configuration](https://grafana.com/docs/grafana//visualizations/dashboards/build-dashboards/create-dashboard/#begin-dashboard-creation-from-connections). + ## Special data sources Grafana includes three special data sources: diff --git a/docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md b/docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md index b80fa49f815..16c97f6d10a 100644 --- a/docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md +++ b/docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md @@ -31,7 +31,6 @@ Most [generally available](https://grafana.com/docs/release-life-cycle/#general- | `logsContextDatasourceUi` | Allow datasource to provide custom UI for context view | Yes | | `lokiQuerySplitting` | Split large interval queries into subqueries with smaller time intervals | Yes | | `influxdbBackendMigration` | Query InfluxDB InfluxQL without the proxy | Yes | -| `unifiedRequestLog` | Writes error logs to the request logger | Yes | | `logsExploreTableVisualisation` | A table visualisation for logs in Explore | Yes | | `awsDatasourcesTempCredentials` | Support temporary security credentials in AWS plugins for Grafana Cloud customers | Yes | | `awsAsyncQueryCaching` | Enable caching for async queries for Redshift and Athena. Requires that the datasource has caching and async query support enabled | Yes | diff --git a/docs/sources/visualizations/dashboards/build-dashboards/create-dashboard/index.md b/docs/sources/visualizations/dashboards/build-dashboards/create-dashboard/index.md index 3d5e765e0cd..10196a40811 100644 --- a/docs/sources/visualizations/dashboards/build-dashboards/create-dashboard/index.md +++ b/docs/sources/visualizations/dashboards/build-dashboards/create-dashboard/index.md @@ -99,7 +99,7 @@ Dashboards and panels allow you to show your data in visual form. Each panel nee - Understand the query language of the target data source. - Ensure that data source for which you are writing a query has been added. For more information about adding a data source, refer to [Add a data source](ref:add-a-data-source) if you need instructions. -**To create a dashboard**: +To create a dashboard, follow these steps: {{< shared id="create-dashboard" >}} @@ -171,6 +171,28 @@ Dashboards and panels allow you to show your data in visual form. Each panel nee Now, when you want to make more changes to the saved dashboard, click **Edit** in the top-right corner. +### Begin dashboard creation from data source configuration + +You can start the process of creating a dashboard directly from a data source rather than from the **Dashboards** page. + +To begin building a dashboard directly from a data source, follow these steps: + +1. Navigate to **Connections > Data sources**. +1. On the row of the data source for which you want to build a dashboard, click **Build a dashboard**. + + The empty dashboard page opens. + +1. Do one of the following: + - Click **+Add visualization** to configure all the elements of the new dashboard. + - Select one of the suggested dashboards by clicking its **Use dashboard** button. This can be helpful when you're not sure how to most effectively visualize your data. + The suggested dashboards are specific to your data source type (for example, Prometheus, Loki, or Elasticsearch). If there are more than three dashboard suggestions, you can click **View all** to see the rest of them. + + ![Empty dashboard with add visualization and suggested dashboard options](/media/docs/grafana/dashboards/screenshot-suggested-dashboards-v12.3.png) + + {{< docs/public-preview product="Suggested dashboards" >}} + +1. Complete the rest of the dashboard configuration. For more detailed steps, refer to [Create a dashboard](#create-a-dashboard), beginning at step five. + ## Copy a dashboard To copy a dashboard, follow these steps: diff --git a/e2e-playwright/alerting-suite/saved-searches.spec.ts b/e2e-playwright/alerting-suite/saved-searches.spec.ts new file mode 100644 index 00000000000..28de805a5a1 --- /dev/null +++ b/e2e-playwright/alerting-suite/saved-searches.spec.ts @@ -0,0 +1,271 @@ +import { Page } from '@playwright/test'; + +import { test, expect } from '@grafana/plugin-e2e'; + +/** + * UI selectors for Saved Searches e2e tests. + * Each selector is a function that takes the page and returns a locator. + */ +const ui = { + // Main elements + savedSearchesButton: (page: Page) => page.getByRole('button', { name: /saved searches/i }), + dropdown: (page: Page) => page.getByRole('dialog', { name: /saved searches/i }), + searchInput: (page: Page) => page.getByTestId('search-query-input'), + + // Save functionality + saveButton: (page: Page) => page.getByRole('button', { name: /save current search/i }), + saveConfirmButton: (page: Page) => page.getByRole('button', { name: /^save$/i }), + saveNameInput: (page: Page) => page.getByPlaceholder(/enter a name/i), + + // Action menu + actionsButton: (page: Page) => page.getByRole('button', { name: /actions/i }), + renameMenuItem: (page: Page) => page.getByText(/rename/i), + deleteMenuItem: (page: Page) => page.getByText(/^delete$/i), + setAsDefaultMenuItem: (page: Page) => page.getByText(/set as default/i), + deleteConfirmButton: (page: Page) => page.getByRole('button', { name: /^delete$/i }), + + // Indicators + emptyState: (page: Page) => page.getByText(/no saved searches/i), + defaultIcon: (page: Page) => page.locator('[title="Default search"]'), + duplicateError: (page: Page) => page.getByText(/already exists/i), +}; + +/** + * Helper to clear saved searches storage. + * UserStorage uses localStorage as fallback, so we clear both potential keys. + */ +async function clearSavedSearches(page: Page) { + await page.evaluate(() => { + // Clear localStorage keys that might contain saved searches + // UserStorage stores under 'grafana.userstorage.alerting' pattern + const keysToRemove = Object.keys(localStorage).filter( + (key) => key.includes('alerting') && (key.includes('savedSearches') || key.includes('userstorage')) + ); + keysToRemove.forEach((key) => localStorage.removeItem(key)); + + // Also clear session storage visited flag + const sessionKeysToRemove = Object.keys(sessionStorage).filter((key) => key.includes('alerting')); + sessionKeysToRemove.forEach((key) => sessionStorage.removeItem(key)); + }); +} + +test.describe( + 'Alert Rules - Saved Searches', + { + tag: ['@alerting'], + }, + () => { + test.beforeEach(async ({ page }) => { + // Clear any saved searches from previous tests before navigating + await page.goto('/alerting/list'); + await clearSavedSearches(page); + await page.reload(); + }); + + test.afterEach(async ({ page }) => { + // Clean up saved searches after each test + await clearSavedSearches(page); + }); + + test('should display Saved searches button', async ({ page }) => { + await expect(ui.savedSearchesButton(page)).toBeVisible(); + }); + + test('should open dropdown when clicking Saved searches button', async ({ page }) => { + await ui.savedSearchesButton(page).click(); + + await expect(ui.dropdown(page)).toBeVisible(); + }); + + test('should show empty state when no saved searches exist', async ({ page }) => { + // Storage is cleared in beforeEach, so we should see empty state + await ui.savedSearchesButton(page).click(); + + await expect(ui.emptyState(page)).toBeVisible(); + }); + + test('should enable Save current search button when search query is entered', async ({ page }) => { + // Enter a search query + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + // Open saved searches + await ui.savedSearchesButton(page).click(); + + await expect(ui.saveButton(page)).toBeEnabled(); + }); + + test('should disable Save current search button when search query is empty', async ({ page }) => { + await ui.savedSearchesButton(page).click(); + + await expect(ui.saveButton(page)).toBeDisabled(); + }); + + test('should save a new search', async ({ page }) => { + // Enter a search query + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + // Open saved searches + await ui.savedSearchesButton(page).click(); + + // Click save button + await ui.saveButton(page).click(); + + // Enter name and save + await ui.saveNameInput(page).fill('My Firing Rules'); + await ui.saveConfirmButton(page).click(); + + // Verify the saved search appears in the list + await expect(page.getByText('My Firing Rules')).toBeVisible(); + }); + + test('should show validation error for duplicate name', async ({ page }) => { + // First save a search + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + await ui.saveButton(page).click(); + + await ui.saveNameInput(page).fill('Duplicate Test'); + await ui.saveConfirmButton(page).click(); + + // Try to save another with the same name + await ui.saveButton(page).click(); + await ui.saveNameInput(page).fill('Duplicate Test'); + await ui.saveConfirmButton(page).click(); + + // Verify validation error + await expect(ui.duplicateError(page)).toBeVisible(); + }); + + test('should apply a saved search', async ({ page }) => { + // Create a saved search first + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + await ui.saveButton(page).click(); + + await ui.saveNameInput(page).fill('Apply Test'); + await ui.saveConfirmButton(page).click(); + + // Clear the search + await ui.searchInput(page).clear(); + await ui.searchInput(page).press('Enter'); + + // Apply the saved search + await ui.savedSearchesButton(page).click(); + await page.getByRole('button', { name: /apply search.*apply test/i }).click(); + + // Verify the search input is updated + await expect(ui.searchInput(page)).toHaveValue('state:firing'); + }); + + test('should rename a saved search', async ({ page }) => { + // Create a saved search + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + await ui.saveButton(page).click(); + + await ui.saveNameInput(page).fill('Original Name'); + await ui.saveConfirmButton(page).click(); + + // Open action menu and click rename + await ui.actionsButton(page).click(); + await ui.renameMenuItem(page).click(); + + // Enter new name + const renameInput = page.getByDisplayValue('Original Name'); + await renameInput.clear(); + await renameInput.fill('Renamed Search'); + await page.keyboard.press('Enter'); + + // Verify the name was updated + await expect(page.getByText('Renamed Search')).toBeVisible(); + await expect(page.getByText('Original Name')).not.toBeVisible(); + }); + + test('should delete a saved search', async ({ page }) => { + // Create a saved search + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + await ui.saveButton(page).click(); + + await ui.saveNameInput(page).fill('To Delete'); + await ui.saveConfirmButton(page).click(); + + // Verify it was saved + await expect(page.getByText('To Delete')).toBeVisible(); + + // Open action menu and click delete + await ui.actionsButton(page).click(); + await ui.deleteMenuItem(page).click(); + + // Confirm delete + await ui.deleteConfirmButton(page).click(); + + // Verify it was deleted + await expect(page.getByText('To Delete')).not.toBeVisible(); + }); + + test('should set a search as default', async ({ page }) => { + // Create a saved search + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + await ui.saveButton(page).click(); + + await ui.saveNameInput(page).fill('Default Test'); + await ui.saveConfirmButton(page).click(); + + // Set as default + await ui.actionsButton(page).click(); + await ui.setAsDefaultMenuItem(page).click(); + + // Verify the star icon appears (indicating default) + await expect(ui.defaultIcon(page)).toBeVisible(); + }); + + test('should close dropdown when pressing Escape', async ({ page }) => { + await ui.savedSearchesButton(page).click(); + + await expect(ui.dropdown(page)).toBeVisible(); + + await page.keyboard.press('Escape'); + + await expect(ui.dropdown(page)).not.toBeVisible(); + }); + + test('should cancel save mode when pressing Escape', async ({ page }) => { + // Enter a search query + await ui.searchInput(page).fill('state:firing'); + await ui.searchInput(page).press('Enter'); + + await ui.savedSearchesButton(page).click(); + + // Start save mode + await ui.saveButton(page).click(); + + await expect(ui.saveNameInput(page)).toBeVisible(); + + // Press Escape to cancel + await page.keyboard.press('Escape'); + + // Verify we're back to list mode + await expect(ui.saveNameInput(page)).not.toBeVisible(); + await expect(ui.saveButton(page)).toBeVisible(); + }); + } +); diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 1d0d5a2684c..597f2b94a1a 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1911,11 +1911,6 @@ "count": 1 } }, - "public/app/features/dashboard-scene/settings/JsonModelEditView.tsx": { - "react/no-unescaped-entities": { - "count": 2 - } - }, "public/app/features/dashboard-scene/settings/variables/VariableEditableElement.tsx": { "react-hooks/rules-of-hooks": { "count": 4 @@ -2868,11 +2863,6 @@ "count": 1 } }, - "public/app/features/plugins/admin/components/PluginDetailsPage.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - } - }, "public/app/features/plugins/admin/helpers.ts": { "no-restricted-syntax": { "count": 2 diff --git a/packages/grafana-data/src/types/featureToggles.gen.ts b/packages/grafana-data/src/types/featureToggles.gen.ts index 199be6d9c3f..981b10dfb1c 100644 --- a/packages/grafana-data/src/types/featureToggles.gen.ts +++ b/packages/grafana-data/src/types/featureToggles.gen.ts @@ -126,11 +126,6 @@ export interface FeatureToggles { */ disableSSEDataplane?: boolean; /** - * Writes error logs to the request logger - * @default true - */ - unifiedRequestLog?: boolean; - /** * Uses JWT-based auth for rendering instead of relying on remote cache */ renderAuthJWT?: boolean; @@ -540,6 +535,10 @@ export interface FeatureToggles { */ alertingListViewV2?: boolean; /** + * Enables saved searches for alert rules list + */ + alertingSavedSearches?: boolean; + /** * Disables the ability to send alerts to an external Alertmanager datasource. */ alertingDisableSendAlertsExternal?: boolean; @@ -1198,6 +1197,11 @@ export interface FeatureToggles { */ onlyStoreActionSets?: boolean; /** + * Show insights for plugins in the plugin details page + * @default false + */ + pluginInsights?: boolean; + /** * Enables a new panel time settings drawer */ panelTimeSettings?: boolean; diff --git a/packages/grafana-schema/src/raw/composable/newgauge/panelcfg/x/NewGaugePanelCfg_types.gen.ts b/packages/grafana-schema/src/raw/composable/newgauge/panelcfg/x/NewGaugePanelCfg_types.gen.ts index aedc041cf71..7c29eb7b463 100644 --- a/packages/grafana-schema/src/raw/composable/newgauge/panelcfg/x/NewGaugePanelCfg_types.gen.ts +++ b/packages/grafana-schema/src/raw/composable/newgauge/panelcfg/x/NewGaugePanelCfg_types.gen.ts @@ -16,21 +16,19 @@ export interface GaugePanelEffects { barGlow?: boolean; centerGlow?: boolean; gradient?: boolean; - rounded?: boolean; - spotlight?: boolean; } export const defaultGaugePanelEffects: Partial = { barGlow: false, centerGlow: false, gradient: true, - rounded: false, - spotlight: false, }; export interface Options extends common.SingleStatBaseOptions { + barShape: ('flat' | 'rounded'); barWidthFactor: number; effects: GaugePanelEffects; + endpointMarker?: ('point' | 'glow' | 'none'); segmentCount: number; segmentSpacing: number; shape: ('circle' | 'gauge'); @@ -40,8 +38,10 @@ export interface Options extends common.SingleStatBaseOptions { } export const defaultOptions: Partial = { + barShape: 'flat', barWidthFactor: 0.5, effects: {}, + endpointMarker: 'point', segmentCount: 1, segmentSpacing: 0.3, shape: 'gauge', diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialArcPath.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialArcPath.tsx index f54f3cd6f22..f59614acd53 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialArcPath.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialArcPath.tsx @@ -1,52 +1,149 @@ -import { GaugeDimensions, toRad } from './utils'; +import { useId, memo, HTMLAttributes, ReactNode } from 'react'; -export interface RadialArcPathProps { - startAngle: number; - dimensions: GaugeDimensions; - color: string; - glowFilter?: string; +import { FieldDisplay } from '@grafana/data'; + +import { getBarEndcapColors, getGradientCss, getEndpointMarkerColors } from './colors'; +import { RadialShape, RadialGaugeDimensions, GradientStop } from './types'; +import { drawRadialArcPath, toRad } from './utils'; + +export interface RadialArcPathPropsBase { arcLengthDeg: number; + barEndcaps?: boolean; + dimensions: RadialGaugeDimensions; + fieldDisplay: FieldDisplay; roundedBars?: boolean; + shape: RadialShape; + endpointMarker?: 'point' | 'glow'; + startAngle: number; + glowFilter?: string; + endpointMarkerGlowFilter?: string; } -export function RadialArcPath({ - startAngle: angle, - dimensions, - color, - glowFilter, - arcLengthDeg, - roundedBars, -}: RadialArcPathProps) { - const { radius, centerX, centerY, barWidth } = dimensions; +interface RadialArcPathPropsWithColor extends RadialArcPathPropsBase { + color: string; +} - if (arcLengthDeg === 360) { - // For some reason a 100% full arc cannot be rendered - arcLengthDeg = 359.99; +interface RadialArcPathPropsWithGradient extends RadialArcPathPropsBase { + gradient: GradientStop[]; +} + +type RadialArcPathProps = RadialArcPathPropsWithColor | RadialArcPathPropsWithGradient; + +const ENDPOINT_MARKER_MIN_ANGLE = 10; +const DOT_OPACITY = 0.5; +const DOT_RADIUS_FACTOR = 0.4; +const MAX_DOT_RADIUS = 8; + +export const RadialArcPath = memo( + ({ + arcLengthDeg, + dimensions, + fieldDisplay, + roundedBars, + shape, + endpointMarker, + barEndcaps, + startAngle: angle, + glowFilter, + endpointMarkerGlowFilter, + ...rest + }: RadialArcPathProps) => { + const id = useId(); + + const bgDivStyle: HTMLAttributes['style'] = { width: '100%', height: '100%' }; + if ('color' in rest) { + bgDivStyle.backgroundColor = rest.color; + } else { + bgDivStyle.backgroundImage = getGradientCss(rest.gradient, shape); + } + + const { radius, centerX, centerY, barWidth } = dimensions; + + const path = drawRadialArcPath(angle, arcLengthDeg, dimensions, roundedBars); + + const startRadians = toRad(angle); + const endRadians = toRad(angle + arcLengthDeg); + + const xStart = centerX + radius * Math.cos(startRadians); + const yStart = centerY + radius * Math.sin(startRadians); + const xEnd = centerX + radius * Math.cos(endRadians); + const yEnd = centerY + radius * Math.sin(endRadians); + + const dotRadius = + endpointMarker === 'point' ? Math.min((barWidth / 2) * DOT_RADIUS_FACTOR, MAX_DOT_RADIUS) : barWidth / 2; + + let barEndcapColors: [string, string] | undefined; + let endpointMarks: ReactNode = null; + if ('gradient' in rest) { + if (endpointMarker && (rest.gradient?.length ?? 0) > 0) { + switch (endpointMarker) { + case 'point': + const [pointColorStart, pointColorEnd] = getEndpointMarkerColors( + rest.gradient!, + fieldDisplay.display.percent + ); + endpointMarks = ( + <> + {arcLengthDeg > ENDPOINT_MARKER_MIN_ANGLE && ( + + )} + + + ); + break; + case 'glow': + const offsetAngle = toRad(ENDPOINT_MARKER_MIN_ANGLE); + const xStartMark = centerX + radius * Math.cos(endRadians + offsetAngle); + const yStartMark = centerY + radius * Math.sin(endRadians + offsetAngle); + endpointMarks = + arcLengthDeg > ENDPOINT_MARKER_MIN_ANGLE ? ( + + ) : null; + break; + default: + break; + } + } + + if (barEndcaps) { + barEndcapColors = getBarEndcapColors(rest.gradient, fieldDisplay.display.percent); + } + } + + return ( + <> + {/* FIXME: optimize this by only using clippath + foreign obj for gradients */} + + + + + + +
+ + {barEndcapColors?.[0] && } + {barEndcapColors?.[1] && ( + + )} + + + {endpointMarks} + + ); } +); - const startRadians = toRad(angle); - const endRadians = toRad(angle + arcLengthDeg); - - let x1 = centerX + radius * Math.cos(startRadians); - let y1 = centerY + radius * Math.sin(startRadians); - let x2 = centerX + radius * Math.cos(endRadians); - let y2 = centerY + radius * Math.sin(endRadians); - - const largeArc = arcLengthDeg > 180 ? 1 : 0; - - const path = ['M', x1, y1, 'A', radius, radius, 0, largeArc, 1, x2, y2].join(' '); - - return ( - - ); -} +RadialArcPath.displayName = 'RadialArcPath'; diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialBar.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialBar.tsx index 2bacc3af3e8..719ec52c625 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialBar.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialBar.tsx @@ -1,97 +1,64 @@ -import { GrafanaTheme2 } from '@grafana/data'; +import { FALLBACK_COLOR, FieldDisplay } from '@grafana/data'; import { useTheme2 } from '../../themes/ThemeContext'; import { RadialArcPath } from './RadialArcPath'; -import { RadialColorDefs } from './RadialColorDefs'; -import { GaugeDimensions, toRad } from './utils'; +import { RadialShape, RadialGaugeDimensions, GradientStop } from './types'; export interface RadialBarProps { - dimensions: GaugeDimensions; - colorDefs: RadialColorDefs; - angleRange: number; angle: number; - startAngle: number; + angleRange: number; + dimensions: RadialGaugeDimensions; + fieldDisplay: FieldDisplay; + gradient?: GradientStop[]; roundedBars?: boolean; - spotlightStroke: string; + endpointMarker?: 'point' | 'glow'; + shape: RadialShape; + startAngle: number; glowFilter?: string; + endpointMarkerGlowFilter?: string; } export function RadialBar({ - dimensions, - colorDefs, - angleRange, angle, - startAngle, + angleRange, + dimensions, + fieldDisplay, + gradient, roundedBars, - spotlightStroke, + endpointMarker, + shape, + startAngle, glowFilter, + endpointMarkerGlowFilter, }: RadialBarProps) { const theme = useTheme2(); - + const colorProps = gradient ? { gradient } : { color: fieldDisplay.display.color ?? FALLBACK_COLOR }; return ( <> - - {/** Track */} - - {/** The colored bar */} - - {spotlightStroke && angle > 8 && ( - - )} - - {colorDefs.getDefs()} + {/** Track */} + + {/** The colored bar */} + ); } - -interface SpotlightEffectProps { - dimensions: GaugeDimensions; - angle: number; - glowFilter?: string; - spotlightStroke: string; - theme: GrafanaTheme2; - roundedBars?: boolean; -} - -function SpotlightSquareEffect({ dimensions, angle, glowFilter, spotlightStroke, roundedBars }: SpotlightEffectProps) { - const { radius, centerX, centerY, barWidth } = dimensions; - - const angleRadian = toRad(angle); - const x1 = centerX + radius * Math.cos(angleRadian - 0.2); - const y1 = centerY + radius * Math.sin(angleRadian - 0.2); - const x2 = centerX + radius * Math.cos(angleRadian); - const y2 = centerY + radius * Math.sin(angleRadian); - - const path = ['M', x1, y1, 'A', radius, radius, 0, 0, 1, x2, y2].join(' '); - - return ( - - ); -} diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialBarSegmented.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialBarSegmented.tsx index dbc93d2da7f..b51cb4ce2f1 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialBarSegmented.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialBarSegmented.tsx @@ -1,126 +1,74 @@ -import { FieldDisplay } from '@grafana/data'; +import { memo } from 'react'; + +import { FALLBACK_COLOR, FieldDisplay } from '@grafana/data'; import { useTheme2 } from '../../themes/ThemeContext'; import { RadialArcPath } from './RadialArcPath'; -import { RadialColorDefs } from './RadialColorDefs'; -import { GaugeDimensions } from './utils'; +import { RadialShape, RadialGaugeDimensions, GradientStop } from './types'; +import { + getAngleBetweenSegments, + getFieldConfigMinMax, + getFieldDisplayProcessor, + getOptimalSegmentCount, +} from './utils'; export interface RadialBarSegmentedProps { fieldDisplay: FieldDisplay; - dimensions: GaugeDimensions; - colorDefs: RadialColorDefs; + dimensions: RadialGaugeDimensions; angleRange: number; startAngle: number; glowFilter?: string; segmentCount: number; segmentSpacing: number; + shape: RadialShape; + gradient?: GradientStop[]; } -export function RadialBarSegmented({ - fieldDisplay, - dimensions, - startAngle, - angleRange, - glowFilter, - segmentCount, - segmentSpacing, - colorDefs, -}: RadialBarSegmentedProps) { - const segments: React.ReactNode[] = []; - const theme = useTheme2(); - const segmentCountAdjusted = getOptimalSegmentCount(dimensions, segmentSpacing, segmentCount, angleRange); - const min = fieldDisplay.field.min ?? 0; - const max = fieldDisplay.field.max ?? 100; - const value = fieldDisplay.display.numeric; - const angleBetweenSegments = getAngleBetweenSegments(segmentSpacing, segmentCount, angleRange); - const segmentArcLengthDeg = angleRange / segmentCountAdjusted - angleBetweenSegments; +export const RadialBarSegmented = memo( + ({ + fieldDisplay, + dimensions, + startAngle, + angleRange, + glowFilter, + gradient, + segmentCount, + segmentSpacing, + shape, + }: RadialBarSegmentedProps) => { + const theme = useTheme2(); + const segments: React.ReactNode[] = []; + const segmentCountAdjusted = getOptimalSegmentCount(dimensions, segmentSpacing, segmentCount, angleRange); + const [min, max] = getFieldConfigMinMax(fieldDisplay); + const value = fieldDisplay.display.numeric; + const angleBetweenSegments = getAngleBetweenSegments(segmentSpacing, segmentCount, angleRange); + const segmentArcLengthDeg = angleRange / segmentCountAdjusted - angleBetweenSegments; + const displayProcessor = getFieldDisplayProcessor(fieldDisplay); - for (let i = 0; i < segmentCountAdjusted; i++) { - const angleValue = min + ((max - min) / segmentCountAdjusted) * i; - const angleColor = colorDefs.getSegmentColor(angleValue); - const segmentAngle = startAngle + (angleRange / segmentCountAdjusted) * i + 0.01; - const segmentColor = angleValue >= value ? theme.colors.action.hover : angleColor; + for (let i = 0; i < segmentCountAdjusted; i++) { + const angleValue = min + ((max - min) / segmentCountAdjusted) * i; + const segmentAngle = startAngle + (angleRange / segmentCountAdjusted) * i + 0.01; + const segmentColor = + angleValue >= value ? theme.colors.border.medium : (displayProcessor(angleValue).color ?? FALLBACK_COLOR); + const colorProps = angleValue < value && gradient ? { gradient } : { color: segmentColor }; - segments.push( - - ); + segments.push( + + ); + } + + return {segments}; } +); - return ( - <> - {segments} - {colorDefs.getDefs()} - - ); -} - -export function getAngleBetweenSegments(segmentSpacing: number, segmentCount: number, range: number) { - // Max spacing is 8 degrees between segments - // Changing this constant could be considered a breaking change - const maxAngleBetweenSegments = Math.max(range / 1.5 / segmentCount, 2); - return segmentSpacing * maxAngleBetweenSegments; -} - -function getOptimalSegmentCount( - dimensions: GaugeDimensions, - segmentSpacing: number, - segmentCount: number, - range: number -) { - const angleBetweenSegments = getAngleBetweenSegments(segmentSpacing, segmentCount, range); - - const innerRadius = dimensions.radius - dimensions.barWidth / 2; - const circumference = Math.PI * innerRadius * 2 * (range / 360); - const maxSegments = Math.floor(circumference / (angleBetweenSegments + 3)); - - return Math.min(maxSegments, segmentCount); -} - -// export function RadialSegmentLine({ -// gaugeId, -// center, -// angle, -// size, -// color, -// barWidth, -// roundedBars, -// glow, -// margin, -// segmentWidth, -// }: RadialSegmentProps) { -// const arcSize = size - barWidth; -// const radius = arcSize / 2 - margin; - -// const angleRad = (Math.PI * (angle - 90)) / 180; -// const lineLength = radius - barWidth; - -// const x1 = center + radius * Math.cos(angleRad); -// const y1 = center + radius * Math.sin(angleRad); -// const x2 = center + lineLength * Math.cos(angleRad); -// const y2 = center + lineLength * Math.sin(angleRad); - -// return ( -// -// ); -// } +RadialBarSegmented.displayName = 'RadialBarSegmented'; diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialColorDefs.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialColorDefs.tsx deleted file mode 100644 index 6bcf4876880..00000000000 --- a/packages/grafana-ui/src/components/RadialGauge/RadialColorDefs.tsx +++ /dev/null @@ -1,141 +0,0 @@ -import tinycolor from 'tinycolor2'; - -import { DisplayProcessor, FALLBACK_COLOR, FieldDisplay, getFieldColorMode, GrafanaTheme2 } from '@grafana/data'; - -import { RadialGradientMode, RadialShape } from './RadialGauge'; -import { GaugeDimensions } from './utils'; - -export interface RadialColorDefsOptions { - gradient: RadialGradientMode; - fieldDisplay: FieldDisplay; - theme: GrafanaTheme2; - dimensions: GaugeDimensions; - shape: RadialShape; - gaugeId: string; - displayProcessor: DisplayProcessor; -} - -export class RadialColorDefs { - private colorToIds: Record = {}; - private defs: React.ReactNode[] = []; - - constructor(private options: RadialColorDefsOptions) {} - - getSegmentColor(forValue: number): string { - const { displayProcessor } = this.options; - const baseColor = displayProcessor(forValue).color ?? FALLBACK_COLOR; - - return this.getColor(baseColor, true); - } - - getColor(baseColor: string, forSegment?: boolean): string { - const { gradient, dimensions, gaugeId, fieldDisplay, shape, theme } = this.options; - - const id = `value-color-${baseColor}-${gaugeId}`; - - if (this.colorToIds[id]) { - return this.colorToIds[id]; - } - - // If no gradient, just return the base color - if (gradient === 'none') { - this.colorToIds[id] = baseColor; - return baseColor; - } - - const returnColor = (this.colorToIds[id] = `url(#${id})`); - const colorModeId = fieldDisplay.field.color?.mode; - const colorMode = getFieldColorMode(colorModeId); - const valuePercent = fieldDisplay.display.percent ?? 0; - - // Handle continusous color modes first - // If it's a segment color we don't want to do continuous gradients - if (colorMode.isContinuous && colorMode.getColors && !forSegment) { - const colors = colorMode.getColors(theme); - const count = colors.length; - - this.defs.push( - - {colors.map((stopColor, i) => ( - - ))} - - ); - - return returnColor; - } - - // For value based colors we want to stay more true to the specific color - // So a radial gradient that adds a bit of light and shade works best - if (colorMode.isByValue) { - const color1 = tinycolor(baseColor).darken(5); - - this.defs.push( - - - - - - ); - - return returnColor; - } - - // For fixed / palette based color scales we can create a more fun - // hue and light based linear gradient that we rotate/move with the value - - const x2 = shape === 'circle' ? 0 : dimensions.centerX + dimensions.radius; - const y2 = shape === 'circle' ? dimensions.centerY + dimensions.radius : 0; - const color1 = tinycolor(baseColor).spin(-20).darken(5); - const color2 = tinycolor(baseColor).saturate(20).spin(20).brighten(10); - - // this makes it so the gradient is always brightest at the current value - const transform = - shape === 'circle' - ? `rotate(${360 * valuePercent - 180} ${dimensions.centerX} ${dimensions.centerY})` - : `translate(-${dimensions.radius * 2 * (1 - valuePercent)}, 0)`; - - this.defs.push( - - {theme.isDark ? ( - <> - - - - ) : ( - <> - - - - )} - - ); - - return returnColor; - } - - getMainBarColor(): string { - return this.getColor(this.options.fieldDisplay.display.color ?? FALLBACK_COLOR); - } - - getDefs(): React.ReactNode[] { - return this.defs; - } -} diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.story.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.story.tsx index c098beda886..b0574ef3f87 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.story.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.story.tsx @@ -13,7 +13,8 @@ import { FieldColorModeId } from '@grafana/schema'; import { useTheme2 } from '../../themes/ThemeContext'; import { Stack } from '../Layout/Stack/Stack'; -import { RadialGauge, RadialGaugeProps, RadialGradientMode, RadialShape, RadialTextMode } from './RadialGauge'; +import { RadialGauge, RadialGaugeProps } from './RadialGauge'; +import { RadialShape, RadialTextMode } from './types'; interface StoryProps extends RadialGaugeProps { value: number; @@ -31,10 +32,27 @@ const meta: Meta = { controls: { exclude: ['theme', 'values', 'vizCount'], }, + a11y: { + config: { + rules: [ + { + id: 'scrollable-region-focusable', + selector: 'body', + enabled: false, + }, + // NOTE: this is necessary due to a false positive with the filered svg glow in one of the examples. + // The color-contrast in this component should be accessible! + { + id: 'color-contrast', + selector: 'text', + enabled: false, + }, + ], + }, + }, }, args: { barWidthFactor: 0.2, - spotlight: false, glowBar: false, glowCenter: false, sparkline: false, @@ -42,7 +60,7 @@ const meta: Meta = { width: 200, height: 200, shape: 'circle', - gradient: 'none', + gradient: false, seriesCount: 1, segmentCount: 0, segmentSpacing: 0.2, @@ -56,14 +74,14 @@ const meta: Meta = { width: { control: { type: 'range', min: 50, max: 600 } }, height: { control: { type: 'range', min: 50, max: 600 } }, value: { control: { type: 'range', min: 0, max: 110 } }, - spotlight: { control: 'boolean' }, roundedBars: { control: 'boolean' }, sparkline: { control: 'boolean' }, thresholdsBar: { control: 'boolean' }, - gradient: { control: { type: 'radio' } }, + gradient: { control: { type: 'boolean' } }, seriesCount: { control: { type: 'range', min: 1, max: 20 } }, segmentCount: { control: { type: 'range', min: 0, max: 100 } }, segmentSpacing: { control: { type: 'range', min: 0, max: 1, step: 0.01 } }, + endpointMarker: { control: { type: 'select' }, options: ['none', 'point', 'glow'] }, colorScheme: { control: { type: 'select' }, options: [ @@ -102,57 +120,17 @@ export const Examples: StoryFn = (args) => {
Bar width
- - - - + + + +
Effects
- - - - + + + +
Shape: Gauge & color scale
@@ -160,14 +138,14 @@ export const Examples: StoryFn = (args) => { value={40} shape="gauge" width={250} - gradient="auto" + gradient colorScheme={FieldColorModeId.ContinuousGrYlRd} glowCenter={true} barWidthFactor={0.6} /> = (args) => { value={args.value ?? 70} color="blue" shape="gauge" - gradient="auto" + gradient sparkline={true} - spotlight glowBar={true} glowCenter={true} barWidthFactor={0.2} @@ -194,9 +171,8 @@ export const Examples: StoryFn = (args) => { value={args.value ?? 30} color="green" shape="gauge" - gradient="auto" + gradient sparkline={true} - spotlight glowBar={true} glowCenter={true} barWidthFactor={0.8} @@ -206,9 +182,8 @@ export const Examples: StoryFn = (args) => { color="red" shape="gauge" width={250} - gradient="auto" + gradient sparkline={true} - spotlight glowBar={true} glowCenter={true} barWidthFactor={0.2} @@ -218,9 +193,8 @@ export const Examples: StoryFn = (args) => { color="red" width={250} shape="gauge" - gradient="auto" + gradient sparkline={true} - spotlight glowBar={true} glowCenter={true} barWidthFactor={0.8} @@ -231,7 +205,7 @@ export const Examples: StoryFn = (args) => { = (args) => { = (args) => { = (args) => { = (args) => { value={args.value ?? 80} width={250} colorScheme={FieldColorModeId.ContinuousGrYlRd} - spotlight shape="gauge" - gradient="auto" + gradient glowBar={true} glowCenter={true} segmentCount={40} @@ -285,10 +257,9 @@ export const Examples: StoryFn = (args) => { @@ -296,7 +267,7 @@ export const Examples: StoryFn = (args) => { value={args.value ?? 70} width={250} colorScheme={FieldColorModeId.Thresholds} - gradient="auto" + gradient glowCenter={true} thresholdsBar={true} roundedBars={false} @@ -307,7 +278,7 @@ export const Examples: StoryFn = (args) => { value={args.value ?? 70} width={250} colorScheme={FieldColorModeId.Thresholds} - gradient="auto" + gradient glowCenter={true} thresholdsBar={true} roundedBars={false} @@ -347,14 +318,12 @@ export const Temp: StoryFn = (args) => { shape="gauge" roundedBars={false} barWidthFactor={0.8} - spotlight /> ); }; interface ExampleProps { - gradient?: RadialGradientMode; color?: string; seriesName?: string; value?: number; @@ -363,7 +332,7 @@ interface ExampleProps { max?: number; width?: number; height?: number; - spotlight?: boolean; + gradient?: boolean; glowBar?: boolean; glowCenter?: boolean; barWidthFactor?: number; @@ -376,12 +345,12 @@ interface ExampleProps { roundedBars?: boolean; thresholdsBar?: boolean; colorScheme?: FieldColorModeId; + endpointMarker?: RadialGaugeProps['endpointMarker']; decimals?: number; showScaleLabels?: boolean; } export function RadialGaugeExample({ - gradient = 'none', color, seriesName = 'Server A', value = 70, @@ -390,7 +359,7 @@ export function RadialGaugeExample({ max = 100, width = 200, height = 200, - spotlight = false, + gradient = false, glowBar = false, glowCenter = false, barWidthFactor = 0.4, @@ -403,6 +372,7 @@ export function RadialGaugeExample({ roundedBars = false, thresholdsBar = false, colorScheme = FieldColorModeId.Thresholds, + endpointMarker = 'glow', decimals = 0, showScaleLabels, }: ExampleProps) { @@ -480,7 +450,6 @@ export function RadialGaugeExample({ barWidthFactor={barWidthFactor} gradient={gradient} shape={shape} - spotlight={spotlight} glowBar={glowBar} glowCenter={glowCenter} textMode={textMode} @@ -490,6 +459,7 @@ export function RadialGaugeExample({ roundedBars={roundedBars} thresholdsBar={thresholdsBar} showScaleLabels={showScaleLabels} + endpointMarker={endpointMarker} /> ); } diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.test.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.test.tsx index e2fed36ec3f..783e3b764da 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.test.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.test.tsx @@ -1,13 +1,28 @@ import { render, screen } from '@testing-library/react'; +import { ComponentProps } from 'react'; import { RadialGaugeExample } from './RadialGauge.story'; describe('RadialGauge', () => { - it('should render', () => { - render(); - - expect(screen.getByRole('img')).toBeInTheDocument(); - }); + it.each([ + { description: 'default', props: {} }, + { description: 'gauge shape', props: { shape: 'gauge' } }, + { description: 'with gradient', props: { gradient: true } }, + { description: 'with glow bar', props: { glowBar: true } }, + { description: 'with glow center', props: { glowCenter: true } }, + { description: 'with segments', props: { segmentCount: 5 } }, + { description: 'with rounded bars', props: { roundedBars: true } }, + { description: 'with endpoint marker glow', props: { roundedBars: true, endpointMarker: 'glow' } }, + { description: 'with endpoint marker point', props: { roundedBars: true, endpointMarker: 'point' } }, + { description: 'with thresholds bar', props: { thresholdsBar: true } }, + { description: 'with sparkline', props: { sparkline: true } }, + ] satisfies Array<{ description: string; props?: ComponentProps }>)( + 'should render $description without throwing', + ({ props }) => { + render(); + expect(screen.getByRole('img')).toBeInTheDocument(); + } + ); it('should render threshold labels', () => { render(); diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx index fadabf8ec72..1251a364230 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx @@ -1,14 +1,7 @@ import { css, cx } from '@emotion/css'; -import { isNumber } from 'lodash'; import { useId } from 'react'; -import { - DisplayValueAlignmentFactors, - FieldDisplay, - getDisplayProcessor, - GrafanaTheme2, - TimeRange, -} from '@grafana/data'; +import { DisplayValueAlignmentFactors, FALLBACK_COLOR, FieldDisplay, GrafanaTheme2, TimeRange } from '@grafana/data'; import { t } from '@grafana/i18n'; import { useStyles2, useTheme2 } from '../../themes/ThemeContext'; @@ -16,12 +9,13 @@ import { getFormattedThresholds } from '../Gauge/utils'; import { RadialBar } from './RadialBar'; import { RadialBarSegmented } from './RadialBarSegmented'; -import { RadialColorDefs } from './RadialColorDefs'; import { RadialScaleLabels } from './RadialScaleLabels'; import { RadialSparkline } from './RadialSparkline'; import { RadialText } from './RadialText'; import { ThresholdsBar } from './ThresholdsBar'; +import { buildGradientColors } from './colors'; import { GlowGradient, MiddleCircleGlow, SpotlightGradient } from './effects'; +import { RadialShape, RadialTextMode } from './types'; import { calculateDimensions, getValueAngleForValue } from './utils'; export interface RadialGaugeProps { @@ -32,7 +26,7 @@ export interface RadialGaugeProps { * Circle or gauge (partial circle) */ shape?: RadialShape; - gradient?: RadialGradientMode; + gradient?: boolean; /** * Bar width is always relative to size of the gauge. * But this gives you control over the width relative to size. @@ -40,12 +34,14 @@ export interface RadialGaugeProps { * Defaults to 0.4 **/ barWidthFactor?: number; - /** Adds a white spotlight for the end position */ - spotlight?: boolean; glowBar?: boolean; glowCenter?: boolean; roundedBars?: boolean; thresholdsBar?: boolean; + /** + * Specify if an endpoint marker should be shown at the end of the bar + */ + endpointMarker?: 'point' | 'glow'; /** * Number of segments depends on size of gauge but this * factor 1-10 gives you relative control @@ -75,10 +71,6 @@ export interface RadialGaugeProps { timeRange?: TimeRange; } -export type RadialGradientMode = 'none' | 'auto'; -export type RadialTextMode = 'auto' | 'value_and_name' | 'value' | 'name' | 'none'; -export type RadialShape = 'circle' | 'gauge'; - /** * https://developers.grafana.com/ui/latest/index.html?path=/docs/plugins-radialgauge--docs */ @@ -87,9 +79,8 @@ export function RadialGauge(props: RadialGaugeProps) { width = 256, height = 256, shape = 'circle', - gradient = 'none', + gradient = false, barWidthFactor = 0.4, - spotlight = false, glowBar = false, glowCenter = false, textMode = 'auto', @@ -99,6 +90,7 @@ export function RadialGauge(props: RadialGaugeProps) { roundedBars = true, thresholdsBar = false, showScaleLabels = false, + endpointMarker, onClick, values, } = props; @@ -121,7 +113,8 @@ export function RadialGauge(props: RadialGaugeProps) { for (let barIndex = 0; barIndex < values.length; barIndex++) { const displayValue = values[barIndex]; const { angle, angleRange } = getValueAngleForValue(displayValue, startAngle, endAngle); - const color = displayValue.display.color ?? 'gray'; + const gradientStops = buildGradientColors(gradient, theme, displayValue); + const color = displayValue.display.color ?? FALLBACK_COLOR; const dimensions = calculateDimensions( width, height, @@ -134,20 +127,12 @@ export function RadialGauge(props: RadialGaugeProps) { showScaleLabels ); - const displayProcessor = getFieldDisplayProcessor(displayValue); + // FIXME: I want to move the ids for these filters into a context which the children + // can reference via a hook, rather than passing them down as props const spotlightGradientId = `spotlight-${barIndex}-${gaugeId}`; const glowFilterId = `glow-${gaugeId}`; - const colorDefs = new RadialColorDefs({ - gradient, - fieldDisplay: displayValue, - theme, - dimensions, - shape, - gaugeId, - displayProcessor, - }); - if (spotlight && theme.isDark) { + if (endpointMarker === 'glow') { defs.push( ); } else { @@ -179,13 +165,16 @@ export function RadialGauge(props: RadialGaugeProps) { ); } @@ -245,7 +234,8 @@ export function RadialGauge(props: RadialGaugeProps) { angleRange={angleRange} roundedBars={roundedBars} glowFilter={`url(#${glowFilterId})`} - colorDefs={colorDefs} + shape={shape} + gradient={gradientStops} /> ); } @@ -291,17 +281,6 @@ export function RadialGauge(props: RadialGaugeProps) { ); } -function getFieldDisplayProcessor(displayValue: FieldDisplay) { - if (displayValue.view && isNumber(displayValue.colIndex)) { - const dp = displayValue.view.getFieldDisplayProcessor(displayValue.colIndex); - if (dp) { - return dp; - } - } - - return getDisplayProcessor(); -} - function getStyles(theme: GrafanaTheme2) { return { vizWrapper: css({ diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialScaleLabels.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialScaleLabels.tsx index 994b3b35eac..6588150602a 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialScaleLabels.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialScaleLabels.tsx @@ -1,87 +1,84 @@ +import { memo } from 'react'; + import { FieldDisplay, GrafanaTheme2, Threshold } from '@grafana/data'; import { t } from '@grafana/i18n'; import { measureText } from '../../utils/measureText'; -import { GaugeDimensions, toCartesian } from './utils'; +import { RadialGaugeDimensions } from './types'; +import { getFieldConfigMinMax, toCartesian } from './utils'; interface RadialScaleLabelsProps { fieldDisplay: FieldDisplay; theme: GrafanaTheme2; thresholds: Threshold[]; - dimensions: GaugeDimensions; + dimensions: RadialGaugeDimensions; startAngle: number; endAngle: number; angleRange: number; } -export function RadialScaleLabels({ - fieldDisplay, - thresholds, - theme, - dimensions, - startAngle, - endAngle, - angleRange, -}: RadialScaleLabelsProps) { - const { centerX, centerY, scaleLabelsFontSize, scaleLabelsRadius } = dimensions; +const LINE_HEIGHT_FACTOR = 1.2; - const fieldConfig = fieldDisplay.field; - const min = fieldConfig.min ?? 0; - const max = fieldConfig.max ?? 100; +export const RadialScaleLabels = memo( + ({ fieldDisplay, thresholds, theme, dimensions, startAngle, endAngle, angleRange }: RadialScaleLabelsProps) => { + const { centerX, centerY, scaleLabelsFontSize, scaleLabelsRadius } = dimensions; + const [min, max] = getFieldConfigMinMax(fieldDisplay); - const fontSize = scaleLabelsFontSize; - const textLineHeight = scaleLabelsFontSize * 1.2; - const radius = scaleLabelsRadius - textLineHeight; + const fontSize = scaleLabelsFontSize; + const textLineHeight = scaleLabelsFontSize * LINE_HEIGHT_FACTOR; + const radius = scaleLabelsRadius - textLineHeight; - function getTextPosition(text: string, value: number, index: number) { - const isLast = index === thresholds.length - 1; - const isFirst = index === 0; + function getTextPosition(text: string, value: number, index: number) { + const isLast = index === thresholds.length - 1; + const isFirst = index === 0; - let valueDeg = ((value - min) / (max - min)) * angleRange; - let finalAngle = startAngle + valueDeg; + let valueDeg = ((value - min) / (max - min)) * angleRange; + let finalAngle = startAngle + valueDeg; - // Now adjust the final angle based on the label text width and the labels position on the arc - let measure = measureText(text, fontSize, theme.typography.fontWeightMedium); - let textWidthAngle = (measure.width / (2 * Math.PI * radius)) * angleRange; + // Now adjust the final angle based on the label text width and the labels position on the arc + let measure = measureText(text, fontSize, theme.typography.fontWeightMedium); + let textWidthAngle = (measure.width / (2 * Math.PI * radius)) * angleRange; - // the centering is different for gauge or circle shapes for some reason - finalAngle -= endAngle < 180 ? textWidthAngle : textWidthAngle / 2; + // the centering is different for gauge or circle shapes for some reason + finalAngle -= endAngle < 180 ? textWidthAngle : textWidthAngle / 2; - // For circle gauges we need to shift the first label more - if (isFirst) { - finalAngle += textWidthAngle; + // For circle gauges we need to shift the first label more + if (isFirst) { + finalAngle += textWidthAngle; + } + + // For circle gauges we need to shift the last label more + if (isLast && endAngle === 360) { + finalAngle -= textWidthAngle; + } + + const position = toCartesian(centerX, centerY, radius, finalAngle); + + return { ...position, transform: `rotate(${finalAngle}, ${position.x}, ${position.y})` }; } - // For circle gauges we need to shift the last label more - if (isLast && endAngle === 360) { - finalAngle -= textWidthAngle; - } - - const position = toCartesian(centerX, centerY, radius, finalAngle); - - return { ...position, transform: `rotate(${finalAngle}, ${position.x}, ${position.y})` }; + return ( + + {thresholds.map((threshold, index) => { + const labelPos = getTextPosition(String(threshold.value), threshold.value, index); + return ( + + {threshold.value} + + ); + })} + + ); } +); - return ( - - {thresholds.map((threshold, index) => { - const labelPos = getTextPosition(String(threshold.value), threshold.value, index); - - return ( - - {threshold.value} - - ); - })} - - ); -} +RadialScaleLabels.displayName = 'RadialScaleLabels'; diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx index acb255a3f3e..2d6c45a14bf 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx @@ -1,49 +1,76 @@ +import { memo, useMemo } from 'react'; + import { FieldDisplay, GrafanaTheme2, FieldConfig } from '@grafana/data'; import { GraphFieldConfig, GraphGradientMode, LineInterpolation } from '@grafana/schema'; import { Sparkline } from '../Sparkline/Sparkline'; -import { RadialShape, RadialTextMode } from './RadialGauge'; -import { GaugeDimensions } from './utils'; +import { RadialShape, RadialTextMode, RadialGaugeDimensions } from './types'; interface RadialSparklineProps { - sparkline: FieldDisplay['sparkline']; - dimensions: GaugeDimensions; - theme: GrafanaTheme2; color?: string; - shape?: RadialShape; + dimensions: RadialGaugeDimensions; + shape: RadialShape; + sparkline: FieldDisplay['sparkline']; textMode: Exclude; + theme: GrafanaTheme2; } -export function RadialSparkline({ sparkline, dimensions, theme, color, shape, textMode }: RadialSparklineProps) { - const { radius, barWidth } = dimensions; - if (!sparkline) { - return null; +const SPARKLINE_HEIGHT_DIVISOR = 4; +const SPARKLINE_HEIGHT_DIVISOR_NAME_AND_VALUE = 4; +const SPARKLINE_WIDTH_FACTOR_ARC = 1.4; +const SPARKLINE_WIDTH_FACTOR_CIRCLE = 1.6; +const SPARKLINE_TOP_OFFSET_DIVISOR_CIRCLE = 4; +const SPARKLINE_TOP_OFFSET_DIVISOR_CIRCLE_NAME_AND_VALUE = 3.3; +const SPARKLINE_SPACING = 8; + +export function getSparklineDimensions( + radius: number, + barWidth: number, + showNameAndValue: boolean, + shape: RadialShape +): { width: number; height: number } { + const height = radius / (showNameAndValue ? SPARKLINE_HEIGHT_DIVISOR_NAME_AND_VALUE : SPARKLINE_HEIGHT_DIVISOR); + const width = radius * (shape === 'gauge' ? SPARKLINE_WIDTH_FACTOR_ARC : SPARKLINE_WIDTH_FACTOR_CIRCLE) - barWidth; + return { width, height }; +} + +export const RadialSparkline = memo( + ({ sparkline, dimensions, theme, color, shape, textMode }: RadialSparklineProps) => { + const { radius, barWidth } = dimensions; + + const showNameAndValue = textMode === 'value_and_name'; + const { width, height } = getSparklineDimensions(radius, barWidth, showNameAndValue, shape); + const topPos = + shape === 'gauge' + ? dimensions.gaugeBottomY - height - SPARKLINE_SPACING + : `calc(50% + ${radius / (showNameAndValue ? SPARKLINE_TOP_OFFSET_DIVISOR_CIRCLE_NAME_AND_VALUE : SPARKLINE_TOP_OFFSET_DIVISOR_CIRCLE)}px)`; + + const config: FieldConfig = useMemo( + () => ({ + color: { + mode: 'fixed', + fixedColor: color ?? 'blue', + }, + custom: { + gradientMode: GraphGradientMode.Opacity, + fillOpacity: 40, + lineInterpolation: LineInterpolation.Smooth, + }, + }), + [color] + ); + + if (!sparkline) { + return null; + } + + return ( +
+ +
+ ); } +); - const showNameAndValue = textMode === 'value_and_name'; - const height = radius / (showNameAndValue ? 4 : 3); - const width = radius * (shape === 'gauge' ? 1.6 : 1.4) - barWidth; - const topPos = - shape === 'gauge' - ? `${dimensions.gaugeBottomY - height}px` - : `calc(50% + ${radius / (showNameAndValue ? 3.3 : 4)}px)`; - - const config: FieldConfig = { - color: { - mode: 'fixed', - fixedColor: color ?? 'blue', - }, - custom: { - gradientMode: GraphGradientMode.Opacity, - fillOpacity: 40, - lineInterpolation: LineInterpolation.Smooth, - }, - }; - - return ( -
- -
- ); -} +RadialSparkline.displayName = 'RadialSparkline'; diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx index 51a1c64c842..69ab16e450e 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx @@ -1,4 +1,5 @@ import { css } from '@emotion/css'; +import { memo } from 'react'; import { DisplayValue, @@ -11,13 +12,12 @@ import { import { useStyles2 } from '../../themes/ThemeContext'; import { calculateFontSize } from '../../utils/measureText'; -import { RadialShape, RadialTextMode } from './RadialGauge'; -import { GaugeDimensions } from './utils'; +import { RadialShape, RadialTextMode, RadialGaugeDimensions } from './types'; interface RadialTextProps { displayValue: DisplayValue; theme: GrafanaTheme2; - dimensions: GaugeDimensions; + dimensions: RadialGaugeDimensions; textMode: Exclude; shape: RadialShape; sparkline?: FieldSparkline; @@ -26,123 +26,137 @@ interface RadialTextProps { nameManualFontSize?: number; } -export function RadialText({ - displayValue, - theme, - dimensions, - textMode, - shape, - sparkline, - alignmentFactors, - valueManualFontSize, - nameManualFontSize, -}: RadialTextProps) { - const styles = useStyles2(getStyles); - const { centerX, centerY, radius, barWidth } = dimensions; +const LINE_HEIGHT_FACTOR = 1.21; +const VALUE_WIDTH_TO_RADIUS_FACTOR = 0.82; +const NAME_TO_HEIGHT_FACTOR = 0.45; +const LARGE_RADIUS_SCALING_DECAY = 0.86; +const MAX_TEXT_WIDTH_DIVISOR = 7; +const MAX_NAME_HEIGHT_DIVISOR = 4; +const VALUE_SPACE_PERCENTAGE = 0.7; +const SPARKLINE_SPACING = 8; +const MIN_VALUE_FONT_SIZE = 1; +const MIN_NAME_FONT_SIZE = 10; +const MIN_UNIT_FONT_SIZE = 6; - if (textMode === 'none') { - return null; - } +export const RadialText = memo( + ({ + displayValue, + theme, + dimensions, + textMode, + shape, + sparkline, + alignmentFactors, + valueManualFontSize, + nameManualFontSize, + }: RadialTextProps) => { + const styles = useStyles2(getStyles); + const { centerX, centerY, radius, barWidth } = dimensions; - const nameToAlignTo = (alignmentFactors ? alignmentFactors.title : displayValue.title) ?? ''; - const valueToAlignTo = formattedValueToString(alignmentFactors ? alignmentFactors : displayValue); + if (textMode === 'none') { + return null; + } - const showValue = textMode === 'value' || textMode === 'value_and_name'; - const showName = textMode === 'name' || textMode === 'value_and_name'; - const maxTextWidth = radius * 2 - barWidth - radius / 7; + const nameToAlignTo = (alignmentFactors ? alignmentFactors.title : displayValue.title) ?? ''; + const valueToAlignTo = formattedValueToString(alignmentFactors ? alignmentFactors : displayValue); - // Not sure where this comes from but svg text is not using body line-height - const lineHeight = 1.21; - const valueWidthToRadiusFactor = 0.82; - const nameToHeightFactor = 0.45; - const largeRadiusScalingDecay = 0.86; + const showValue = textMode === 'value' || textMode === 'value_and_name'; + const showName = textMode === 'name' || textMode === 'value_and_name'; + const maxTextWidth = radius * 2 - barWidth - radius / MAX_TEXT_WIDTH_DIVISOR; - // This pow 0.92 factor is to create a decay so the font size does not become rediculously large for very large panels - let maxValueHeight = valueWidthToRadiusFactor * Math.pow(radius, largeRadiusScalingDecay); - let maxNameHeight = radius / 4; + // This pow 0.92 factor is to create a decay so the font size does not become rediculously large for very large panels + let maxValueHeight = VALUE_WIDTH_TO_RADIUS_FACTOR * Math.pow(radius, LARGE_RADIUS_SCALING_DECAY); + let maxNameHeight = radius / MAX_NAME_HEIGHT_DIVISOR; - if (showValue && showName) { - maxValueHeight = valueWidthToRadiusFactor * Math.pow(radius, largeRadiusScalingDecay); - maxNameHeight = nameToHeightFactor * Math.pow(radius, largeRadiusScalingDecay); - } + if (showValue && showName) { + maxValueHeight = VALUE_WIDTH_TO_RADIUS_FACTOR * Math.pow(radius, LARGE_RADIUS_SCALING_DECAY); + maxNameHeight = NAME_TO_HEIGHT_FACTOR * Math.pow(radius, LARGE_RADIUS_SCALING_DECAY); + } - const valueFontSize = - valueManualFontSize ?? - calculateFontSize( - valueToAlignTo, - maxTextWidth, - maxValueHeight, - lineHeight, - undefined, - theme.typography.body.fontWeight + const valueFontSize = Math.max( + valueManualFontSize ?? + calculateFontSize( + valueToAlignTo, + maxTextWidth, + maxValueHeight, + LINE_HEIGHT_FACTOR, + undefined, + theme.typography.body.fontWeight + ), + MIN_VALUE_FONT_SIZE ); - const nameFontSize = - nameManualFontSize ?? - calculateFontSize( - nameToAlignTo, - maxTextWidth, - maxNameHeight, - lineHeight, - undefined, - theme.typography.body.fontWeight + const nameFontSize = Math.max( + nameManualFontSize ?? + calculateFontSize( + nameToAlignTo, + maxTextWidth, + maxNameHeight, + LINE_HEIGHT_FACTOR, + undefined, + theme.typography.body.fontWeight + ), + MIN_NAME_FONT_SIZE ); - const unitFontSize = Math.max(valueFontSize * 0.7, 5); - const valueHeight = valueFontSize * lineHeight; - const nameHeight = nameFontSize * lineHeight; + const unitFontSize = Math.max(valueFontSize * VALUE_SPACE_PERCENTAGE, MIN_UNIT_FONT_SIZE); + const valueHeight = valueFontSize * LINE_HEIGHT_FACTOR; + const nameHeight = nameFontSize * LINE_HEIGHT_FACTOR; - const valueY = showName ? centerY - nameHeight * 0.3 : centerY; - const nameY = showValue ? valueY + valueHeight * 0.7 : centerY; - const nameColor = showValue ? theme.colors.text.secondary : theme.colors.text.primary; - const suffixShift = (valueFontSize - unitFontSize * 1.2) / 2; + const valueY = showName ? centerY - nameHeight * (1 - VALUE_SPACE_PERCENTAGE) : centerY; + const nameY = showValue ? valueY + valueHeight * VALUE_SPACE_PERCENTAGE : centerY; + const nameColor = showValue ? theme.colors.text.secondary : theme.colors.text.primary; + const suffixShift = (valueFontSize - unitFontSize * LINE_HEIGHT_FACTOR) / 2; - // adjust the text up on gauges and when sparklines are present - let yOffset = 0; - if (shape === 'gauge') { - // we render from the center of the gauge, so move up by half of half of the total height - yOffset -= (valueHeight + nameHeight) / 4; - } - if (sparkline) { - yOffset -= 8; + // adjust the text up on gauges and when sparklines are present + let yOffset = 0; + if (shape === 'gauge') { + // we render from the center of the gauge, so move up by half of half of the total height + yOffset -= (valueHeight + nameHeight) / 4; + } + if (sparkline) { + yOffset -= SPARKLINE_SPACING; + } + + return ( + + {showValue && ( + + {displayValue.prefix ?? ''} + {displayValue.text} + + {displayValue.suffix ?? ''} + + + )} + {showName && ( + + {displayValue.title} + + )} + + ); } +); - return ( - - {showValue && ( - - {displayValue.prefix ?? ''} - {displayValue.text} - - {displayValue.suffix ?? ''} - - - )} - {showName && ( - - {displayValue.title} - - )} - - ); -} +RadialText.displayName = 'RadialText'; -const getStyles = (theme: GrafanaTheme2) => ({ +const getStyles = (_theme: GrafanaTheme2) => ({ text: css({ verticalAlign: 'bottom', }), diff --git a/packages/grafana-ui/src/components/RadialGauge/ThresholdsBar.tsx b/packages/grafana-ui/src/components/RadialGauge/ThresholdsBar.tsx index 602038ccf10..cb2829934b9 100644 --- a/packages/grafana-ui/src/components/RadialGauge/ThresholdsBar.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/ThresholdsBar.tsx @@ -1,20 +1,22 @@ import { FieldDisplay, Threshold } from '@grafana/data'; import { RadialArcPath } from './RadialArcPath'; -import { RadialColorDefs } from './RadialColorDefs'; -import { GaugeDimensions } from './utils'; +import { GradientStop, RadialGaugeDimensions, RadialShape } from './types'; +import { getFieldConfigMinMax } from './utils'; -export interface Props { - dimensions: GaugeDimensions; +interface ThresholdsBarProps { + dimensions: RadialGaugeDimensions; angleRange: number; startAngle: number; endAngle: number; + shape: RadialShape; fieldDisplay: FieldDisplay; roundedBars?: boolean; glowFilter?: string; - colorDefs: RadialColorDefs; thresholds: Threshold[]; + gradient?: GradientStop[]; } + export function ThresholdsBar({ dimensions, fieldDisplay, @@ -22,19 +24,18 @@ export function ThresholdsBar({ angleRange, roundedBars, glowFilter, - colorDefs, thresholds, -}: Props) { - const fieldConfig = fieldDisplay.field; - const min = fieldConfig.min ?? 0; - const max = fieldConfig.max ?? 100; - + shape, + gradient, +}: ThresholdsBarProps) { const thresholdDimensions = { ...dimensions, barWidth: dimensions.thresholdsBarWidth, radius: dimensions.thresholdsBarRadius, }; + const [min, max] = getFieldConfigMinMax(fieldDisplay); + let currentStart = startAngle; let paths: React.ReactNode[] = []; @@ -48,27 +49,26 @@ export function ThresholdsBar({ valueDeg = 0; } - let lengthDeg = valueDeg - currentStart + startAngle; + const lengthDeg = valueDeg - currentStart + startAngle; + const colorProps = gradient ? { gradient } : { color: threshold.color }; paths.push( ); currentStart += lengthDeg; } - return ( - <> - {paths} - {colorDefs.getDefs()} - - ); + return {paths}; } diff --git a/packages/grafana-ui/src/components/RadialGauge/__snapshots__/colors.test.ts.snap b/packages/grafana-ui/src/components/RadialGauge/__snapshots__/colors.test.ts.snap new file mode 100644 index 00000000000..97b053c2d61 --- /dev/null +++ b/packages/grafana-ui/src/components/RadialGauge/__snapshots__/colors.test.ts.snap @@ -0,0 +1,144 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`RadialGauge color utils buildGradientColors should map threshold colors correctly (with baseColor if displayProcessor does not return colors) 1`] = ` +[ + { + "color": "#444444", + "percent": 0, + }, + { + "color": "#FADE2A", + "percent": 0.5, + }, + { + "color": "#F2495C", + "percent": 0.8, + }, + { + "color": "#444444", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should map threshold colors correctly (with baseColor if displayProcessor does not return colors) 2`] = ` +[ + { + "color": "#FF0000", + "percent": 0, + }, + { + "color": "#FADE2A", + "percent": 0.5, + }, + { + "color": "#F2495C", + "percent": 0.8, + }, + { + "color": "#FF0000", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should return gradient colors for by-value color mode in dark theme 1`] = ` +[ + { + "color": "#181b1f", + "percent": 0, + }, + { + "color": "#1F60C4", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should return gradient colors for by-value color mode in light theme 1`] = ` +[ + { + "color": "#ffffff", + "percent": 0, + }, + { + "color": "#1250B0", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should return gradient colors for continuous color modes 1`] = ` +[ + { + "color": "rgb(0, 32, 81)", + "percent": 0, + }, + { + "color": "rgb(17, 54, 108)", + "percent": 0.125, + }, + { + "color": "rgb(60, 77, 110)", + "percent": 0.25, + }, + { + "color": "rgb(98, 100, 111)", + "percent": 0.375, + }, + { + "color": "rgb(127, 124, 117)", + "percent": 0.5, + }, + { + "color": "rgb(154, 148, 120)", + "percent": 0.625, + }, + { + "color": "rgb(187, 175, 113)", + "percent": 0.75, + }, + { + "color": "rgb(226, 203, 92)", + "percent": 0.875, + }, + { + "color": "rgb(253, 234, 69)", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should return gradient colors for fixed color mode in dark theme 1`] = ` +[ + { + "color": "#37237a", + "percent": 0, + }, + { + "color": "#a146da", + "percent": 0.75, + }, + { + "color": "#a146da", + "percent": 1, + }, +] +`; + +exports[`RadialGauge color utils buildGradientColors should return gradient colors for fixed color mode in light theme 1`] = ` +[ + { + "color": "#a146da", + "percent": 0, + }, + { + "color": "#3e2b9a", + "percent": 0.75, + }, + { + "color": "#3e2b9a", + "percent": 1, + }, +] +`; diff --git a/packages/grafana-ui/src/components/RadialGauge/__snapshots__/utils.test.ts.snap b/packages/grafana-ui/src/components/RadialGauge/__snapshots__/utils.test.ts.snap new file mode 100644 index 00000000000..db4c1c40882 --- /dev/null +++ b/packages/grafana-ui/src/components/RadialGauge/__snapshots__/utils.test.ts.snap @@ -0,0 +1,17 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for center x and y 1`] = `"M 150 110 A 90 90 0 1 1 149.98429203681178 110.00000137077838 A 10 10 0 0 1 149.98778269529805 130.00000106616096 A 70 70 0 1 0 150 130 A 10 10 0 0 1 150 110 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for half arc 1`] = `"M 100 10 A 90 90 0 0 1 100 190 L 100 170 A 70 70 0 0 0 100 30 L 100 10 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for narrow bar width 1`] = `"M 100 17.5 A 82.5 82.5 0 0 1 100 182.5 L 100 177.5 A 77.5 77.5 0 0 0 100 22.5 L 100 17.5 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for narrow radius 1`] = `"M 100 40 A 60 60 0 0 1 100 160 L 100 140 A 40 40 0 0 0 100 60 L 100 40 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for quarter arc 1`] = `"M 100 10 A 90 90 0 0 1 190 100 L 170 100 A 70 70 0 0 0 100 30 L 100 10 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for rounded bars 1`] = `"M 100 10 A 90 90 0 1 1 10 100.00000000000001 A 10 10 0 0 1 30 100.00000000000001 A 70 70 0 1 0 100 30 A 10 10 0 0 1 100 10 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for three quarter arc 1`] = `"M 100 10 A 90 90 0 1 1 10 100.00000000000001 L 30 100.00000000000001 A 70 70 0 1 0 100 30 L 100 10 Z"`; + +exports[`RadialGauge utils drawRadialArcPath should draw correct path for wide bar width 1`] = `"M 100 -5 A 105 105 0 0 1 100 205 L 100 155 A 55 55 0 0 0 100 45 L 100 -5 Z"`; diff --git a/packages/grafana-ui/src/components/RadialGauge/colors.test.ts b/packages/grafana-ui/src/components/RadialGauge/colors.test.ts new file mode 100644 index 00000000000..321e95bb921 --- /dev/null +++ b/packages/grafana-ui/src/components/RadialGauge/colors.test.ts @@ -0,0 +1,306 @@ +import { defaultsDeep } from 'lodash'; + +import { createTheme, FALLBACK_COLOR, Field, FieldDisplay, FieldType, ThresholdsMode } from '@grafana/data'; +import { FieldColorModeId } from '@grafana/schema'; + +import { + buildGradientColors, + colorAtGradientPercent, + getBarEndcapColors, + getEndpointMarkerColors, + getGradientCss, + getGradientStopsForPercent, +} from './colors'; + +export type DeepPartial = { + [P in keyof T]?: DeepPartial; +}; + +describe('RadialGauge color utils', () => { + describe('buildGradientColors', () => { + const createField = (colorMode: FieldColorModeId): Field => + ({ + type: FieldType.number, + name: 'Test Field', + config: { + color: { + mode: colorMode, + }, + thresholds: { + mode: ThresholdsMode.Absolute, + steps: [ + { value: -Infinity, color: 'green' }, + { value: 50, color: 'yellow' }, + { value: 80, color: 'red' }, + ], + }, + }, + values: [70, 40, 30, 90, 55], + }) satisfies Field; + + const buildFieldDisplay = (field: Field, part = {}): FieldDisplay => + defaultsDeep(part, { + field: field.config, + colIndex: 0, + view: { + getFieldDisplayProcessor: jest.fn(() => jest.fn(() => ({ color: undefined }))), + }, + display: { + numeric: 75, + }, + }); + + it('should return the baseColor if gradient is false-y', () => { + expect( + buildGradientColors(false, createTheme(), buildFieldDisplay(createField(FieldColorModeId.Fixed)), '#FF0000') + ).toEqual([ + { color: '#FF0000', percent: 0 }, + { color: '#FF0000', percent: 1 }, + ]); + + expect( + buildGradientColors(undefined, createTheme(), buildFieldDisplay(createField(FieldColorModeId.Fixed)), '#FF0000') + ).toEqual([ + { color: '#FF0000', percent: 0 }, + { color: '#FF0000', percent: 1 }, + ]); + }); + + it('uses the fallback color if no baseColor is set', () => { + expect(buildGradientColors(false, createTheme(), buildFieldDisplay(createField(FieldColorModeId.Fixed)))).toEqual( + [ + { color: FALLBACK_COLOR, percent: 0 }, + { color: FALLBACK_COLOR, percent: 1 }, + ] + ); + }); + + it('should map threshold colors correctly (with baseColor if displayProcessor does not return colors)', () => { + expect( + buildGradientColors( + true, + createTheme(), + buildFieldDisplay(createField(FieldColorModeId.Thresholds), { + view: { getFieldDisplayProcessor: jest.fn(() => jest.fn(() => ({ color: '#444444' }))) }, + }) + ) + ).toMatchSnapshot(); + }); + + it('should map threshold colors correctly (with baseColor if displayProcessor does not return colors)', () => { + expect( + buildGradientColors(true, createTheme(), buildFieldDisplay(createField(FieldColorModeId.Thresholds)), '#FF0000') + ).toMatchSnapshot(); + }); + + it('should return gradient colors for continuous color modes', () => { + expect( + buildGradientColors( + true, + createTheme(), + buildFieldDisplay(createField(FieldColorModeId.ContinuousCividis)), + '#00FF00' + ) + ).toMatchSnapshot(); + }); + + it.each(['dark', 'light'] as const)('should return gradient colors for by-value color mode in %s theme', (mode) => { + expect( + buildGradientColors( + true, + createTheme({ colors: { mode } }), + buildFieldDisplay(createField(FieldColorModeId.ContinuousBlues)) + ) + ).toMatchSnapshot(); + }); + + it.each(['dark', 'light'] as const)('should return gradient colors for fixed color mode in %s theme', (mode) => { + expect( + buildGradientColors( + true, + createTheme({ colors: { mode } }), + buildFieldDisplay(createField(FieldColorModeId.Fixed)), + '#442299' + ) + ).toMatchSnapshot(); + }); + }); + + describe('colorAtGradientPercent', () => { + it('should calculate the color at a given percent in a gradient of two colors', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#0000ff', percent: 1 }, + ]; + expect(colorAtGradientPercent(gradient, 0).toHexString()).toBe('#ff0000'); + expect(colorAtGradientPercent(gradient, 0.25).toHexString()).toBe('#bf0040'); + expect(colorAtGradientPercent(gradient, 0.5).toHexString()).toBe('#800080'); + expect(colorAtGradientPercent(gradient, 0.75).toHexString()).toBe('#4000bf'); + expect(colorAtGradientPercent(gradient, 1).toHexString()).toBe('#0000ff'); + }); + + it('should calculate the color at a given percent in a gradient of multiple colors', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + expect(colorAtGradientPercent(gradient, 0).toHexString()).toBe('#ff0000'); + expect(colorAtGradientPercent(gradient, 0.25).toHexString()).toBe('#808000'); + expect(colorAtGradientPercent(gradient, 0.5).toHexString()).toBe('#00ff00'); + expect(colorAtGradientPercent(gradient, 0.75).toHexString()).toBe('#008080'); + expect(colorAtGradientPercent(gradient, 1).toHexString()).toBe('#0000ff'); + }); + + it('will still work if unsorted', () => { + const gradient = [ + { color: '#0000ff', percent: 1 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#ff0000', percent: 0 }, + ]; + expect(colorAtGradientPercent(gradient, 0).toHexString()).toBe('#ff0000'); + expect(colorAtGradientPercent(gradient, 0.25).toHexString()).toBe('#808000'); + expect(colorAtGradientPercent(gradient, 0.5).toHexString()).toBe('#00ff00'); + expect(colorAtGradientPercent(gradient, 0.75).toHexString()).toBe('#008080'); + expect(colorAtGradientPercent(gradient, 1).toHexString()).toBe('#0000ff'); + }); + + it('should not throw an error when percent is outside 0-1 range', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#0000ff', percent: 1 }, + ]; + expect(colorAtGradientPercent(gradient, -0.5).toHexString()).toBe('#ff0000'); + expect(colorAtGradientPercent(gradient, 1.5).toHexString()).toBe('#0000ff'); + }); + + it('should throw an error when less than two stops are provided', () => { + expect(() => { + colorAtGradientPercent([], 0.5); + }).toThrow('colorAtGradientPercent requires at least two color stops'); + expect(() => { + colorAtGradientPercent([{ color: '#ff0000', percent: 0 }], 0.5); + }).toThrow('colorAtGradientPercent requires at least two color stops'); + }); + }); + + describe('getBarEndcapColors', () => { + it('should return the first and last colors in the gradient', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + const [startColor, endColor] = getBarEndcapColors(gradient); + expect(startColor).toBe('#ff0000'); + expect(endColor).toBe('#0000ff'); + }); + + it('should return the correct end color based on percent', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + const [startColor, endColor] = getBarEndcapColors(gradient, 0.25); + expect(startColor).toBe('#ff0000'); + expect(endColor).toBe('#808000'); + }); + + it('should handle gradients with only one colors', () => { + const gradient = [{ color: '#ff0000', percent: 0 }]; + const [startColor, endColor] = getBarEndcapColors(gradient); + expect(startColor).toBe('#ff0000'); + expect(endColor).toBe('#ff0000'); + }); + + it('should throw an error when no colors are provided', () => { + expect(() => { + getBarEndcapColors([]); + }).toThrow('getBarEndcapColors requires at least one color stop'); + }); + }); + + describe('getGradientCss', () => { + it('should return conic-gradient CSS for circle shape', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + const css = getGradientCss(gradient, 'circle'); + expect(css).toBe('conic-gradient(from 0deg, #ff0000 0.00%, #00ff00 50.00%, #0000ff 100.00%)'); + }); + + it('should return linear-gradient CSS for arc shape', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + const css = getGradientCss(gradient, 'gauge'); + expect(css).toBe('linear-gradient(90deg, #ff0000 0.00%, #00ff00 50.00%, #0000ff 100.00%)'); + }); + }); + + describe('getEndpointMarkerColors', () => { + it('should return contrasting guide dot colors based on the gradient endpoints and percent', () => { + const gradient = [ + { color: '#000000', percent: 0 }, + { color: '#ffffff', percent: 0.5 }, + { color: '#ffffff', percent: 1 }, + ]; + const [startDotColor, endDotColor] = getEndpointMarkerColors(gradient, 0.35); + expect(startDotColor).toBe('#fbfbfb'); + expect(endDotColor).toBe('#111217'); + }); + }); + + describe('getGradientStopsForPercent', () => { + it('should return the correct gradient stops for a given percent', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + const [left, right] = getGradientStopsForPercent(gradient, 0.25); + expect(left).toEqual({ color: '#ff0000', percent: 0 }); + expect(right).toEqual({ color: '#00ff00', percent: 0.5 }); + }); + + it('should handle edge cases where percent is at the boundaries', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + let [left, right] = getGradientStopsForPercent(gradient, 0); + expect(left).toEqual({ color: '#ff0000', percent: 0 }); + expect(right).toEqual({ color: '#ff0000', percent: 0 }); + + [left, right] = getGradientStopsForPercent(gradient, 1); + expect(left).toEqual({ color: '#0000ff', percent: 1 }); + expect(right).toEqual({ color: '#0000ff', percent: 1 }); + }); + + it('should return the same stop if there is one that is equal to the percentage', () => { + const gradient = [ + { color: '#ff0000', percent: 0 }, + { color: '#00ff00', percent: 0.5 }, + { color: '#0000ff', percent: 1 }, + ]; + + let [left, right] = getGradientStopsForPercent(gradient, 0); + expect(left).toEqual({ color: '#ff0000', percent: 0 }); + expect(right).toEqual({ color: '#ff0000', percent: 0 }); + + [left, right] = getGradientStopsForPercent(gradient, 0.5); + expect(left).toEqual({ color: '#00ff00', percent: 0.5 }); + expect(right).toEqual({ color: '#00ff00', percent: 0.5 }); + + [left, right] = getGradientStopsForPercent(gradient, 1); + expect(left).toEqual({ color: '#0000ff', percent: 1 }); + expect(right).toEqual({ color: '#0000ff', percent: 1 }); + }); + }); +}); diff --git a/packages/grafana-ui/src/components/RadialGauge/colors.ts b/packages/grafana-ui/src/components/RadialGauge/colors.ts new file mode 100644 index 00000000000..61160a9f826 --- /dev/null +++ b/packages/grafana-ui/src/components/RadialGauge/colors.ts @@ -0,0 +1,195 @@ +import tinycolor from 'tinycolor2'; + +import { colorManipulator, FALLBACK_COLOR, FieldDisplay, getFieldColorMode, GrafanaTheme2 } from '@grafana/data'; +import { FieldColorModeId } from '@grafana/schema'; + +import { GradientStop, RadialShape } from './types'; +import { getFieldConfigMinMax, getFieldDisplayProcessor, getValuePercentageForValue } from './utils'; + +export function buildGradientColors( + gradient = false, + theme: GrafanaTheme2, + fieldDisplay: FieldDisplay, + baseColor = fieldDisplay.display.color ?? FALLBACK_COLOR +): GradientStop[] { + if (!gradient) { + return [ + { color: baseColor, percent: 0 }, + { color: baseColor, percent: 1 }, + ]; + } + + const colorMode = getFieldColorMode(fieldDisplay.field.color?.mode); + + // thresholds get special handling + if (colorMode.id === FieldColorModeId.Thresholds) { + const displayProcessor = getFieldDisplayProcessor(fieldDisplay); + const [min, max] = getFieldConfigMinMax(fieldDisplay); + const thresholds = fieldDisplay.field.thresholds?.steps ?? []; + + const result: Array<{ color: string; percent: number }> = [ + { color: displayProcessor(min).color ?? baseColor, percent: 0 }, + ]; + + for (const threshold of thresholds) { + if (threshold.value > min && threshold.value < max) { + const percent = (threshold.value - min) / (max - min); + result.push({ color: theme.visualization.getColorByName(threshold.color), percent }); + } + } + + result.push({ color: displayProcessor(max).color ?? baseColor, percent: 1 }); + + return result; + } + + // Handle continuous color modes before other by-value modes + if (colorMode.isContinuous && colorMode.getColors) { + const colors = colorMode.getColors(theme); + return colors.map((color, idx) => ({ color, percent: idx / (colors.length - 1) })); + } + + // For value-based colors, we want to stay more true to the specific color, + // so a radial gradient that adds a bit of light and shade works best + if (colorMode.isByValue) { + const darkerColor = tinycolor(baseColor).darken(5); + const lighterColor = tinycolor(baseColor).spin(20).lighten(10); + + const color1 = theme.isDark ? lighterColor : darkerColor; + const color2 = theme.isDark ? darkerColor : lighterColor; + + return [ + { color: color1.toString(), percent: 0 }, + { color: color2.toString(), percent: 0.6 }, + { color: color2.toString(), percent: 1 }, + ]; + } + + // For fixed / palette based color scales we can create a more hue and light + // based linear gradient that we rotate with the value + const darkerColor = tinycolor(baseColor) + .spin(-20) + .darken(theme.isDark ? 15 : 5); + const lighterColor = tinycolor(baseColor).saturate(20).spin(20).brighten(10).lighten(10); + + const underlyingGradient = [ + { color: theme.isDark ? darkerColor.toString() : lighterColor.toString(), percent: 0 }, + { color: theme.isDark ? lighterColor.toString() : darkerColor.toString(), percent: 1 }, + ]; + + // rotate the gradient so that the highest contrasting point is the value, depending on theme. + const valuePercent = getValuePercentageForValue(fieldDisplay); + const startColor = theme.isDark + ? colorAtGradientPercent(underlyingGradient, 1 - valuePercent).toHexString() + : underlyingGradient[0].color; + const endColor = theme.isDark + ? underlyingGradient[1].color + : colorAtGradientPercent(underlyingGradient, valuePercent).toHexString(); + return [ + { color: startColor, percent: 0 }, + { color: endColor, percent: valuePercent }, + { color: endColor, percent: 1 }, + ]; +} + +/** + * get the relevant gradient stops surrounding a given percentage. could be same stop if the + * percent matches a stop exactly. + * + * @param sortedGradientStops - gradient stops sorted by percent + * @param percent - percentage 0..1 + * @returns {[GradientStop, GradientStop]} - the two gradient stops surrounding the given percentage + */ +export function getGradientStopsForPercent( + sortedGradientStops: GradientStop[], + percent: number +): [GradientStop, GradientStop] { + if (percent <= 0) { + return [sortedGradientStops[0], sortedGradientStops[0]]; + } + if (percent >= 1) { + const last = sortedGradientStops.length - 1; + return [sortedGradientStops[last], sortedGradientStops[last]]; + } + + // find surrounding stops using binary search + let lo = 0; + let hi = sortedGradientStops.length - 1; + while (lo + 1 < hi) { + const mid = (lo + hi) >> 1; + if (percent === sortedGradientStops[mid].percent) { + return [sortedGradientStops[mid], sortedGradientStops[mid]]; + } + + if (percent < sortedGradientStops[mid].percent) { + hi = mid; + } else { + lo = mid; + } + } + return [sortedGradientStops[lo], sortedGradientStops[hi]]; +} + +/** + * @alpha - perhaps this should go in colorManipulator.ts + * Given color stops (each with a color and percentage 0..1) returns the color at a given percentage. + * Uses tinycolor.mix for interpolation. + * @params stops - array of color stops (percentages 0..1) + * @params percent - percentage 0..1 + * @returns color at the given percentage + */ +export function colorAtGradientPercent(stops: GradientStop[], percent: number): tinycolor.Instance { + if (!stops || stops.length < 2) { + throw new Error('colorAtGradientPercent requires at least two color stops'); + } + + const sorted = stops + .map((s: GradientStop): GradientStop => ({ color: s.color, percent: Math.min(Math.max(0, s.percent), 1) })) + .sort((a: GradientStop, b: GradientStop) => a.percent - b.percent); + + const [left, right] = getGradientStopsForPercent(sorted, percent); + const range = right.percent - left.percent; + const t = range === 0 ? 0 : (percent - left.percent) / range; // 0..1 + return tinycolor.mix(left.color, right.color, t * 100); +} + +export function getBarEndcapColors(gradientStops: GradientStop[], percent = 1): [string, string] { + if (gradientStops.length === 0) { + throw new Error('getBarEndcapColors requires at least one color stop'); + } + + const startColor = gradientStops[0].color; + let endColor = gradientStops[gradientStops.length - 1].color; + + // if we have a percentageFilled, use it to get a the correct end color based on where the bar terminates + if (gradientStops.length >= 2) { + const endColorByPercentage = colorAtGradientPercent(gradientStops, percent); + endColor = + endColorByPercentage.getAlpha() === 1 ? endColorByPercentage.toHexString() : endColorByPercentage.toHex8String(); + } + return [startColor, endColor]; +} + +export function getGradientCss(gradientStops: GradientStop[], shape: RadialShape): string { + const colorStrings = gradientStops.map((stop) => `${stop.color} ${(stop.percent * 100).toFixed(2)}%`); + if (shape === 'circle') { + return `conic-gradient(from 0deg, ${colorStrings.join(', ')})`; + } + return `linear-gradient(90deg, ${colorStrings.join(', ')})`; +} + +// the theme does not make the full palette available to us, and we +// don't want transparent colors which our grays usually have. +const GRAY_05 = '#111217'; +const GRAY_90 = '#fbfbfb'; +const CONTRAST_THRESHOLD_MAX = 4.5; +const getGuideDotColor = (color: string): string => { + const darkColor = GRAY_05; + const lightColor = GRAY_90; + return colorManipulator.getContrastRatio(darkColor, color) >= CONTRAST_THRESHOLD_MAX ? darkColor : lightColor; +}; + +export function getEndpointMarkerColors(gradientStops: GradientStop[], percent = 1): [string, string] { + const [startColor, endColor] = getBarEndcapColors(gradientStops, percent); + return [getGuideDotColor(startColor), getGuideDotColor(endColor)]; +} diff --git a/packages/grafana-ui/src/components/RadialGauge/effects.tsx b/packages/grafana-ui/src/components/RadialGauge/effects.tsx index 354a68a25ba..c48307f177e 100644 --- a/packages/grafana-ui/src/components/RadialGauge/effects.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/effects.tsx @@ -1,15 +1,18 @@ import { GrafanaTheme2 } from '@grafana/data'; -import { GaugeDimensions } from './utils'; +import { RadialGaugeDimensions } from './types'; export interface GlowGradientProps { id: string; barWidth: number; } +const MIN_GLOW_SIZE = 0.75; +const GLOW_FACTOR = 0.08; + export function GlowGradient({ id, barWidth }: GlowGradientProps) { // 0.75 is the minimum glow size, and it scales with bar width - const glowSize = 0.75 + barWidth * 0.08; + const glowSize = MIN_GLOW_SIZE + barWidth * GLOW_FACTOR; return ( @@ -22,56 +25,19 @@ export function GlowGradient({ id, barWidth }: GlowGradientProps) { ); } -export function SpotlightGradient({ - id, - dimensions, - roundedBars, - angle, - theme, -}: { - id: string; - dimensions: GaugeDimensions; - angle: number; - roundedBars: boolean; - theme: GrafanaTheme2; -}) { - const angleRadian = ((angle - 90) * Math.PI) / 180; - - let x1 = dimensions.centerX + dimensions.radius * Math.cos(angleRadian - 0.2); - let y1 = dimensions.centerY + dimensions.radius * Math.sin(angleRadian - 0.2); - let x2 = dimensions.centerX + dimensions.radius * Math.cos(angleRadian); - let y2 = dimensions.centerY + dimensions.radius * Math.sin(angleRadian); - - if (theme.isLight) { - return ( - - - - - - ); - } - - return ( - - - - {roundedBars && } - - ); -} +const CENTER_GLOW_OPACITY = 0.15; export function CenterGlowGradient({ gaugeId, color }: { gaugeId: string; color: string }) { return ( - - + + ); } export interface CenterGlowProps { - dimensions: GaugeDimensions; + dimensions: RadialGaugeDimensions; gaugeId: string; color?: string; } @@ -82,8 +48,8 @@ export function MiddleCircleGlow({ dimensions, gaugeId, color }: CenterGlowProps return ( <> - - + + @@ -93,3 +59,36 @@ export function MiddleCircleGlow({ dimensions, gaugeId, color }: CenterGlowProps ); } + +export function SpotlightGradient({ + id, + dimensions, + roundedBars, + angle, + theme, +}: { + id: string; + dimensions: RadialGaugeDimensions; + angle: number; + roundedBars: boolean; + theme: GrafanaTheme2; +}) { + if (theme.isLight) { + return null; + } + + const angleRadian = ((angle - 90) * Math.PI) / 180; + + let x1 = dimensions.centerX + dimensions.radius * Math.cos(angleRadian - 0.2); + let y1 = dimensions.centerY + dimensions.radius * Math.sin(angleRadian - 0.2); + let x2 = dimensions.centerX + dimensions.radius * Math.cos(angleRadian); + let y2 = dimensions.centerY + dimensions.radius * Math.sin(angleRadian); + + return ( + + + + {roundedBars && } + + ); +} diff --git a/packages/grafana-ui/src/components/RadialGauge/types.ts b/packages/grafana-ui/src/components/RadialGauge/types.ts new file mode 100644 index 00000000000..cc233dd524c --- /dev/null +++ b/packages/grafana-ui/src/components/RadialGauge/types.ts @@ -0,0 +1,25 @@ +export type RadialTextMode = 'auto' | 'value_and_name' | 'value' | 'name' | 'none'; +export type RadialShape = 'circle' | 'gauge'; + +export interface RadialGaugeDimensions { + margin: number; + radius: number; + centerX: number; + centerY: number; + barWidth: number; + endAngle?: number; + barIndex: number; + thresholdsBarRadius: number; + thresholdsBarWidth: number; + thresholdsBarSpacing: number; + scaleLabelsFontSize: number; + scaleLabelsSpacing: number; + scaleLabelsRadius: number; + gaugeBottomY: number; +} + +/** @alpha - perhaps this should go in @grafana/data */ +export interface GradientStop { + color: string; + percent: number; +} diff --git a/packages/grafana-ui/src/components/RadialGauge/utils.test.ts b/packages/grafana-ui/src/components/RadialGauge/utils.test.ts index 5e3f34d62cd..b9b2e4ad8f3 100644 --- a/packages/grafana-ui/src/components/RadialGauge/utils.test.ts +++ b/packages/grafana-ui/src/components/RadialGauge/utils.test.ts @@ -1,24 +1,111 @@ -import { FieldDisplay } from '@grafana/data'; +import { DataFrameView, FieldDisplay } from '@grafana/data'; import type { RadialGaugeProps } from './RadialGauge'; -import { calculateDimensions, toRad, getValueAngleForValue } from './utils'; +import { RadialGaugeDimensions } from './types'; +import { + calculateDimensions, + toRad, + getValueAngleForValue, + drawRadialArcPath, + getFieldConfigMinMax, + getFieldDisplayProcessor, + getAngleBetweenSegments, + getOptimalSegmentCount, +} from './utils'; describe('RadialGauge utils', () => { - function calc(overrides: Partial = {}) { - return calculateDimensions( - overrides.width ?? 200, - overrides.height ?? 200, - overrides.shape === 'gauge' ? 110 : 360, - overrides.glowBar ?? false, - overrides.roundedBars ?? false, - overrides.barWidthFactor ?? 0.4, - overrides.barIndex ?? 0, - overrides.thresholdsBar ?? false, - overrides.showScaleLabels ?? false - ); - } + describe('getFieldDisplayProcessor', () => { + it('should return display processor from view when available', () => { + const mockProcessor = jest.fn(); + const mockView = { + getFieldDisplayProcessor: jest.fn().mockReturnValue(mockProcessor), + } as unknown as DataFrameView; + + const fieldDisplay: FieldDisplay = { + display: { numeric: 50, text: '50', color: 'blue' }, + field: {}, + view: mockView, + colIndex: 0, + rowIndex: 0, + name: 'test', + getLinks: () => [], + hasLinks: false, + }; + + const dp = getFieldDisplayProcessor(fieldDisplay); + expect(dp).toBe(mockProcessor); + expect(mockView.getFieldDisplayProcessor).toHaveBeenCalledWith(0); + }); + + it('should return default display processor when view is not available', () => { + const fieldDisplay: FieldDisplay = { + display: { numeric: 50, text: '50', color: 'blue' }, + field: {}, + view: undefined, + colIndex: 0, + rowIndex: 0, + name: 'test', + getLinks: () => [], + hasLinks: false, + }; + + const dp = getFieldDisplayProcessor(fieldDisplay); + expect(dp).toBeDefined(); + expect(typeof dp).toBe('function'); + }); + }); + + describe('getFieldConfigMinMax', () => { + it('should return min and max from field config when defined', () => { + const fieldDisplay: FieldDisplay = { + display: { numeric: 50, text: '50', color: 'blue' }, + field: { min: 10, max: 90 }, + view: undefined, + colIndex: 0, + rowIndex: 0, + name: 'test', + getLinks: () => [], + hasLinks: false, + }; + + const [min, max] = getFieldConfigMinMax(fieldDisplay); + expect(min).toBe(10); + expect(max).toBe(90); + }); + + it('should return default min and max when not defined in field config', () => { + const fieldDisplay: FieldDisplay = { + display: { numeric: 50, text: '50', color: 'blue' }, + field: {}, + view: undefined, + colIndex: 0, + rowIndex: 0, + name: 'test', + getLinks: () => [], + hasLinks: false, + }; + + const [min, max] = getFieldConfigMinMax(fieldDisplay); + expect(min).toBe(0); + expect(max).toBe(100); + }); + }); describe('calculateDimensions', () => { + function calc(overrides: Partial = {}) { + return calculateDimensions( + overrides.width ?? 200, + overrides.height ?? 200, + overrides.shape === 'gauge' ? 110 : 360, + overrides.glowBar ?? false, + overrides.roundedBars ?? false, + overrides.barWidthFactor ?? 0.4, + overrides.barIndex ?? 0, + overrides.thresholdsBar ?? false, + overrides.showScaleLabels ?? false + ); + } + it('should calculate basic dimensions for a square gauge', () => { const result = calc(); @@ -194,4 +281,84 @@ describe('RadialGauge utils', () => { expect(result.angle).toBe(240); }); }); + + describe('drawRadialArcPath', () => { + const defaultDims: RadialGaugeDimensions = Object.freeze({ + centerX: 100, + centerY: 100, + radius: 80, + barWidth: 20, + margin: 0, + barIndex: 0, + thresholdsBarWidth: 0, + thresholdsBarSpacing: 0, + thresholdsBarRadius: 0, + scaleLabelsFontSize: 0, + scaleLabelsSpacing: 0, + scaleLabelsRadius: 0, + gaugeBottomY: 0, + }); + + it.each([ + { description: 'quarter arc', startAngle: 0, endAngle: 90 }, + { description: 'half arc', startAngle: 0, endAngle: 180 }, + { description: 'three quarter arc', startAngle: 0, endAngle: 270 }, + { description: 'rounded bars', startAngle: 0, endAngle: 270, roundedBars: true }, + { description: 'wide bar width', startAngle: 0, endAngle: 180, dimensions: { barWidth: 50 } }, + { description: 'narrow bar width', startAngle: 0, endAngle: 180, dimensions: { barWidth: 5 } }, + { description: 'narrow radius', startAngle: 0, endAngle: 180, dimensions: { radius: 50 } }, + { + description: 'center x and y', + startAngle: 0, + endAngle: 360, + roundedBars: true, + dimensions: { centerX: 150, centerY: 200 }, + }, + ])(`should draw correct path for $description`, ({ startAngle, endAngle, dimensions, roundedBars }) => { + const path = drawRadialArcPath(startAngle, endAngle, { ...defaultDims, ...dimensions }, roundedBars); + expect(path).toMatchSnapshot(); + }); + + describe('edge cases', () => { + it('should adjust 360deg or greater arcs to avoid SVG rendering issues', () => { + expect(drawRadialArcPath(0, 360, defaultDims)).toEqual(drawRadialArcPath(0, 359.99, defaultDims)); + expect(drawRadialArcPath(0, 380, defaultDims)).toEqual(drawRadialArcPath(0, 380, defaultDims)); + }); + + it('should return empty string if inner radius collapses to zero or below', () => { + const smallRadiusDims = { ...defaultDims, radius: 5, barWidth: 20 }; + expect(drawRadialArcPath(0, 180, smallRadiusDims)).toBe(''); + }); + }); + }); + + describe('getAngleBetweenSegments', () => { + it('should calculate angle between segments based on spacing and count', () => { + expect(getAngleBetweenSegments(2, 10, 360)).toBe(48); + expect(getAngleBetweenSegments(5, 15, 180)).toBe(40); + }); + }); + + describe('getOptimalSegmentCount', () => { + it('should adjust segment count based on dimensions and spacing', () => { + const dimensions: RadialGaugeDimensions = { + centerX: 100, + centerY: 100, + radius: 80, + barWidth: 20, + margin: 0, + barIndex: 0, + thresholdsBarWidth: 0, + thresholdsBarSpacing: 0, + thresholdsBarRadius: 0, + scaleLabelsFontSize: 0, + scaleLabelsSpacing: 0, + scaleLabelsRadius: 0, + gaugeBottomY: 0, + }; + + expect(getOptimalSegmentCount(dimensions, 2, 10, 360)).toBe(8); + expect(getOptimalSegmentCount(dimensions, 1, 5, 360)).toBe(5); + }); + }); }); diff --git a/packages/grafana-ui/src/components/RadialGauge/utils.ts b/packages/grafana-ui/src/components/RadialGauge/utils.ts index 44f767d89b2..e26cf5eed2a 100644 --- a/packages/grafana-ui/src/components/RadialGauge/utils.ts +++ b/packages/grafana-ui/src/components/RadialGauge/utils.ts @@ -1,11 +1,38 @@ -import { FieldDisplay } from '@grafana/data'; +import { FieldDisplay, getDisplayProcessor } from '@grafana/data'; -export function getValueAngleForValue(fieldDisplay: FieldDisplay, startAngle: number, endAngle: number) { - const angleRange = (360 % (startAngle === 0 ? 1 : startAngle)) + endAngle; +import { RadialGaugeDimensions } from './types'; + +export function getFieldDisplayProcessor(displayValue: FieldDisplay) { + if (displayValue.view && displayValue.colIndex != null) { + const dp = displayValue.view.getFieldDisplayProcessor(displayValue.colIndex); + if (dp) { + return dp; + } + } + + return getDisplayProcessor(); +} + +export function getFieldConfigMinMax(fieldDisplay: FieldDisplay) { const min = fieldDisplay.field.min ?? 0; const max = fieldDisplay.field.max ?? 100; + return [min, max]; +} - let angle = ((fieldDisplay.display.numeric - min) / (max - min)) * angleRange; +export function getValuePercentageForValue(fieldDisplay: FieldDisplay, value = fieldDisplay.display.numeric) { + const [min, max] = getFieldConfigMinMax(fieldDisplay); + return (value - min) / (max - min); +} + +export function getValueAngleForValue( + fieldDisplay: FieldDisplay, + startAngle: number, + endAngle: number, + value = fieldDisplay.display.numeric +) { + const angleRange = (360 % (startAngle === 0 ? 1 : startAngle)) + endAngle; + + let angle = getValuePercentageForValue(fieldDisplay, value) * angleRange; if (angle > angleRange) { angle = angleRange; @@ -26,24 +53,19 @@ export function toRad(angle: number) { return ((angle - 90) * Math.PI) / 180; } -export interface GaugeDimensions { - margin: number; - radius: number; - centerX: number; - centerY: number; - barWidth: number; - endAngle?: number; - barIndex: number; - thresholdsBarRadius: number; - thresholdsBarWidth: number; - thresholdsBarSpacing: number; - showScaleLabels?: boolean; - scaleLabelsFontSize: number; - scaleLabelsSpacing: number; - scaleLabelsRadius: number; - gaugeBottomY: number; -} - +/** + * returns the calculated dimensions for the radial gauge + * @param width + * @param height + * @param endAngle + * @param glow + * @param roundedBars + * @param barWidthFactor + * @param barIndex + * @param thresholdBar + * @param showScaleLabels + * @returns {RadialGaugeDimensions} + */ export function calculateDimensions( width: number, height: number, @@ -54,7 +76,7 @@ export function calculateDimensions( barIndex: number, thresholdBar?: boolean, showScaleLabels?: boolean -): GaugeDimensions { +): RadialGaugeDimensions { const yMaxAngle = endAngle > 180 ? 180 : endAngle; let margin = 0; @@ -97,6 +119,7 @@ export function calculateDimensions( maxRadiusW -= labelsSize; maxRadiusH -= labelsSize; + // FIXME: needs coverage // For gauges the max label needs a bit more vertical space so that it does not get clipped if (maxRadiusIsLimitedByHeight && endAngle < 180) { const amount = outerRadius * 0.07; @@ -155,3 +178,105 @@ export function toCartesian(centerX: number, centerY: number, radius: number, an y: centerY + radius * Math.sin(radian), }; } + +export function drawRadialArcPath( + startAngle: number, + endAngle: number, + dimensions: RadialGaugeDimensions, + roundedBars?: boolean +): string { + const { radius, centerX, centerY, barWidth } = dimensions; + + // For some reason a 100% full arc cannot be rendered + if (endAngle >= 360) { + endAngle = 359.99; + } + + const startRadians = toRad(startAngle); + const endRadians = toRad(startAngle + endAngle); + + const largeArc = endAngle > 180 ? 1 : 0; + + const outerR = radius + barWidth / 2; + const innerR = Math.max(0, radius - barWidth / 2); + if (innerR <= 0) { + return ''; // cannot draw arc with 0 inner radius + } + + // get points for both an inner and outer arc. we draw + // the arc entirely with a path's fill instead of using stroke + // so that it can be used as a clip-path. + const ox1 = centerX + outerR * Math.cos(startRadians); + const oy1 = centerY + outerR * Math.sin(startRadians); + const ox2 = centerX + outerR * Math.cos(endRadians); + const oy2 = centerY + outerR * Math.sin(endRadians); + + const ix1 = centerX + innerR * Math.cos(startRadians); + const iy1 = centerY + innerR * Math.sin(startRadians); + const ix2 = centerX + innerR * Math.cos(endRadians); + const iy2 = centerY + innerR * Math.sin(endRadians); + + // calculate the cap width in case we're drawing rounded bars + const capR = barWidth / 2; + + const pathParts = [ + // start at outer start + 'M', + ox1, + oy1, + // outer arc from start to end (clockwise) + 'A', + outerR, + outerR, + 0, + largeArc, + 1, + ox2, + oy2, + ]; + + if (roundedBars) { + // rounded end cap: small arc connecting outer end to inner end + pathParts.push('A', capR, capR, 0, 0, 1, ix2, iy2); + } else { + // straight line to inner end (square butt) + pathParts.push('L', ix2, iy2); + } + + // inner arc from end back to start (counter-clockwise) + pathParts.push('A', innerR, innerR, 0, largeArc, 0, ix1, iy1); + + if (roundedBars) { + // rounded start cap: small arc connecting inner start back to outer start + pathParts.push('A', capR, capR, 0, 0, 1, ox1, oy1); + } else { + // straight line back to outer start (square butt) + pathParts.push('L', ox1, oy1); + } + + pathParts.push('Z'); + + return pathParts.join(' '); +} + +export function getAngleBetweenSegments(segmentSpacing: number, segmentCount: number, range: number) { + // Max spacing is 8 degrees between segments + // Changing this constant could be considered a breaking change + const maxAngleBetweenSegments = Math.max(range / 1.5 / segmentCount, 2); + return segmentSpacing * maxAngleBetweenSegments; +} + +export function getOptimalSegmentCount( + dimensions: RadialGaugeDimensions, + segmentSpacing: number, + segmentCount: number, + range: number +) { + const angleBetweenSegments = getAngleBetweenSegments(segmentSpacing, segmentCount, range); + + const innerRadius = dimensions.radius - dimensions.barWidth / 2; + const circumference = Math.PI * innerRadius * 2 * (range / 360); + const maxSegments = Math.floor(circumference / (angleBetweenSegments + 3)); + + return Math.min(maxSegments, segmentCount); +} diff --git a/packages/grafana-ui/src/components/Table/CellActions.tsx b/packages/grafana-ui/src/components/Table/CellActions.tsx index e2fe8a658ba..f21be659c4f 100644 --- a/packages/grafana-ui/src/components/Table/CellActions.tsx +++ b/packages/grafana-ui/src/components/Table/CellActions.tsx @@ -1,3 +1,4 @@ +import { isPlainObject } from 'lodash'; import { useCallback } from 'react'; import * as React from 'react'; @@ -63,7 +64,18 @@ export function CellActions({ tooltip={t('grafana-ui.table.cell-inspect', 'Inspect value')} onClick={() => { if (setInspectCell) { - setInspectCell({ value: cell.value, mode: previewMode }); + let mode = TableCellInspectorMode.text; + let inspectValue = cell.value; + try { + const parsed = typeof inspectValue === 'string' ? JSON.parse(inspectValue) : inspectValue; + if (Array.isArray(parsed) || isPlainObject(parsed)) { + inspectValue = JSON.stringify(parsed, null, 2); + mode = TableCellInspectorMode.code; + } + } catch { + // do nothing + } + setInspectCell({ value: inspectValue, mode }); } }} {...commonButtonProps} diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegendTable.test.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.test.tsx new file mode 100644 index 00000000000..131133bcdfb --- /dev/null +++ b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.test.tsx @@ -0,0 +1,78 @@ +import { render, screen } from '@testing-library/react'; + +import { VizLegendTable } from './VizLegendTable'; +import { VizLegendItem } from './types'; + +describe('VizLegendTable', () => { + const mockItems: VizLegendItem[] = [ + { label: 'Series 1', color: 'red', yAxis: 1 }, + { label: 'Series 2', color: 'blue', yAxis: 1 }, + { label: 'Series 3', color: 'green', yAxis: 1 }, + ]; + + it('renders without crashing', () => { + const { container } = render(); + expect(container.querySelector('table')).toBeInTheDocument(); + }); + + it('renders all items', () => { + render(); + expect(screen.getByText('Series 1')).toBeInTheDocument(); + expect(screen.getByText('Series 2')).toBeInTheDocument(); + expect(screen.getByText('Series 3')).toBeInTheDocument(); + }); + + it('renders table headers when items have display values', () => { + const itemsWithStats: VizLegendItem[] = [ + { + label: 'Series 1', + color: 'red', + yAxis: 1, + getDisplayValues: () => [ + { numeric: 100, text: '100', title: 'Max' }, + { numeric: 50, text: '50', title: 'Min' }, + ], + }, + ]; + render(); + expect(screen.getByText('Max')).toBeInTheDocument(); + expect(screen.getByText('Min')).toBeInTheDocument(); + }); + + it('renders sort icon when sorted', () => { + const { container } = render( + + ); + expect(container.querySelector('svg')).toBeInTheDocument(); + }); + + it('calls onToggleSort when header is clicked', () => { + const onToggleSort = jest.fn(); + render(); + const header = screen.getByText('Name'); + header.click(); + expect(onToggleSort).toHaveBeenCalledWith('Name'); + }); + + it('does not call onToggleSort when not sortable', () => { + const onToggleSort = jest.fn(); + render(); + const header = screen.getByText('Name'); + header.click(); + expect(onToggleSort).not.toHaveBeenCalled(); + }); + + it('renders with long labels', () => { + const itemsWithLongLabels: VizLegendItem[] = [ + { + label: 'This is a very long series name that should be scrollable within its table cell', + color: 'red', + yAxis: 1, + }, + ]; + render(); + expect( + screen.getByText('This is a very long series name that should be scrollable within its table cell') + ).toBeInTheDocument(); + }); +}); diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx index b654a2d3ac6..0c2859453eb 100644 --- a/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx +++ b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx @@ -119,7 +119,6 @@ const getStyles = (theme: GrafanaTheme2) => ({ table: css({ width: '100%', 'th:first-child': { - width: '100%', borderBottom: `1px solid ${theme.colors.border.weak}`, }, }), diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.test.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.test.tsx new file mode 100644 index 00000000000..4ca95aa395c --- /dev/null +++ b/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.test.tsx @@ -0,0 +1,112 @@ +import { render, screen } from '@testing-library/react'; + +import { LegendTableItem } from './VizLegendTableItem'; +import { VizLegendItem } from './types'; + +describe('LegendTableItem', () => { + const mockItem: VizLegendItem = { + label: 'Series 1', + color: 'red', + yAxis: 1, + }; + + it('renders without crashing', () => { + const { container } = render( + + + + +
+ ); + expect(container.querySelector('tr')).toBeInTheDocument(); + }); + + it('renders label text', () => { + render( + + + + +
+ ); + expect(screen.getByText('Series 1')).toBeInTheDocument(); + }); + + it('renders with long label text', () => { + const longLabelItem: VizLegendItem = { + ...mockItem, + label: 'This is a very long series name that should be scrollable in the table cell', + }; + render( + + + + +
+ ); + expect( + screen.getByText('This is a very long series name that should be scrollable in the table cell') + ).toBeInTheDocument(); + }); + + it('renders stat values when provided', () => { + const itemWithStats: VizLegendItem = { + ...mockItem, + getDisplayValues: () => [ + { numeric: 100, text: '100', title: 'Max' }, + { numeric: 50, text: '50', title: 'Min' }, + ], + }; + render( + + + + +
+ ); + expect(screen.getByText('100')).toBeInTheDocument(); + expect(screen.getByText('50')).toBeInTheDocument(); + }); + + it('renders right y-axis indicator when yAxis is 2', () => { + const rightAxisItem: VizLegendItem = { + ...mockItem, + yAxis: 2, + }; + render( + + + + +
+ ); + expect(screen.getByText('(right y-axis)')).toBeInTheDocument(); + }); + + it('calls onLabelClick when label is clicked', () => { + const onLabelClick = jest.fn(); + render( + + + + +
+ ); + const button = screen.getByRole('button'); + button.click(); + expect(onLabelClick).toHaveBeenCalledWith(mockItem, expect.any(Object)); + }); + + it('does not call onClick when readonly', () => { + const onLabelClick = jest.fn(); + render( + + + + +
+ ); + const button = screen.getByRole('button'); + expect(button).toBeDisabled(); + }); +}); diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.tsx index 335cf4309e9..56ec6cb733e 100644 --- a/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.tsx +++ b/packages/grafana-ui/src/components/VizLegend/VizLegendTableItem.tsx @@ -69,7 +69,7 @@ export const LegendTableItem = ({ return ( - + - +
+ +
{item.getDisplayValues && @@ -128,6 +130,27 @@ const getStyles = (theme: GrafanaTheme2) => { background: rowHoverBg, }, }), + labelCell: css({ + label: 'LegendLabelCell', + maxWidth: 0, + width: '100%', + }), + labelCellInner: css({ + label: 'LegendLabelCellInner', + display: 'block', + flex: 1, + minWidth: 0, + overflowX: 'auto', + overflowY: 'hidden', + paddingRight: theme.spacing(3), + scrollbarWidth: 'none', + msOverflowStyle: 'none', + maskImage: `linear-gradient(to right, black calc(100% - ${theme.spacing(3)}), transparent 100%)`, + WebkitMaskImage: `linear-gradient(to right, black calc(100% - ${theme.spacing(3)}), transparent 100%)`, + '&::-webkit-scrollbar': { + display: 'none', + }, + }), label: css({ label: 'LegendLabel', whiteSpace: 'nowrap', @@ -135,9 +158,6 @@ const getStyles = (theme: GrafanaTheme2) => { border: 'none', fontSize: 'inherit', padding: 0, - maxWidth: '600px', - textOverflow: 'ellipsis', - overflow: 'hidden', userSelect: 'text', }), labelDisabled: css({ diff --git a/pkg/api/apierrors/folder.go b/pkg/api/apierrors/folder.go index 9509ff4ff55..a938b165852 100644 --- a/pkg/api/apierrors/folder.go +++ b/pkg/api/apierrors/folder.go @@ -29,7 +29,8 @@ func ToFolderErrorResponse(err error) response.Response { errors.Is(err, dashboards.ErrDashboardTypeMismatch) || errors.Is(err, dashboards.ErrDashboardInvalidUid) || errors.Is(err, dashboards.ErrDashboardUidTooLong) || - errors.Is(err, folder.ErrFolderCannotBeParentOfItself) { + errors.Is(err, folder.ErrFolderCannotBeParentOfItself) || + errors.Is(err, folder.ErrMaximumDepthReached) { return response.Error(http.StatusBadRequest, err.Error(), nil) } diff --git a/pkg/api/apierrors/folder_test.go b/pkg/api/apierrors/folder_test.go index 0ca8b16fc87..233254dc6cc 100644 --- a/pkg/api/apierrors/folder_test.go +++ b/pkg/api/apierrors/folder_test.go @@ -30,7 +30,7 @@ func TestToFolderErrorResponse(t *testing.T) { { name: "maximum depth reached", input: folder.ErrMaximumDepthReached.Errorf("Maximum nested folder depth reached"), - want: response.Err(folder.ErrMaximumDepthReached.Errorf("Maximum nested folder depth reached")), + want: response.Error(http.StatusBadRequest, "[folder.maximum-depth-reached] Maximum nested folder depth reached", nil), }, { name: "bad request errors", diff --git a/pkg/api/folder.go b/pkg/api/folder.go index 851910a9e1d..5b0bf9d121e 100644 --- a/pkg/api/folder.go +++ b/pkg/api/folder.go @@ -214,7 +214,7 @@ func (hs *HTTPServer) MoveFolder(c *contextmodel.ReqContext) response.Response { cmd.SignedInUser = c.SignedInUser theFolder, err := hs.folderService.Move(c.Req.Context(), &cmd) if err != nil { - return response.ErrOrFallback(http.StatusInternalServerError, "move folder failed", err) + return apierrors.ToFolderErrorResponse(err) } folderDTO, err := hs.newToFolderDto(c, theFolder) diff --git a/pkg/middleware/loggermw/logger.go b/pkg/middleware/loggermw/logger.go index 1255d87aa0e..1b4f3d4d2d4 100644 --- a/pkg/middleware/loggermw/logger.go +++ b/pkg/middleware/loggermw/logger.go @@ -64,10 +64,7 @@ func (l *loggerImpl) Middleware() web.Middleware { // put the start time on context so we can measure it later. r = r.WithContext(log.InitstartTime(r.Context(), time.Now())) - //nolint:staticcheck // not yet migrated to OpenFeature - if l.flags.IsEnabled(r.Context(), featuremgmt.FlagUnifiedRequestLog) { - r = r.WithContext(errutil.SetUnifiedLogging(r.Context())) - } + r = r.WithContext(errutil.SetUnifiedLogging(r.Context())) rw := web.Rw(w, r) next.ServeHTTP(rw, r) diff --git a/pkg/operators/provisioning/config.go b/pkg/operators/provisioning/config.go index 8e496e5e556..05552e56095 100644 --- a/pkg/operators/provisioning/config.go +++ b/pkg/operators/provisioning/config.go @@ -178,7 +178,7 @@ func setupFromConfig(cfg *setting.Cfg, registry prometheus.Registerer) (controll APIPath: "/apis", Host: url, WrapTransport: transport.WrapperFunc(func(rt http.RoundTripper) http.RoundTripper { - return authrt.NewRoundTripper(tokenExchangeClient, rt, group) + return authrt.NewRoundTripper(tokenExchangeClient, rt, group, authrt.ExtraAudience(provisioning.GROUP)) }), Transport: &http.Transport{ MaxConnsPerHost: 100, diff --git a/pkg/registry/apis/folders/register.go b/pkg/registry/apis/folders/register.go index 64e51c06312..7c39fbe22ae 100644 --- a/pkg/registry/apis/folders/register.go +++ b/pkg/registry/apis/folders/register.go @@ -356,7 +356,7 @@ func (b *FolderAPIBuilder) Validate(ctx context.Context, a admission.Attributes, if !ok { return fmt.Errorf("obj is not folders.Folder") } - return validateOnUpdate(ctx, f, old, b.storage, b.parents, folder.MaxNestedFolderDepth) + return validateOnUpdate(ctx, f, old, b.storage, b.parents, b.searcher, folder.MaxNestedFolderDepth) default: return nil } diff --git a/pkg/registry/apis/folders/register_test.go b/pkg/registry/apis/folders/register_test.go index 066f8793776..1eb00f0a7e5 100644 --- a/pkg/registry/apis/folders/register_test.go +++ b/pkg/registry/apis/folders/register_test.go @@ -376,6 +376,10 @@ func TestFolderAPIBuilder_Validate_Update(t *testing.T) { m.On("Get", mock.Anything, "new-parent", mock.Anything).Return( &folders.Folder{}, nil).Once() + // also retrieves old parent for depth difference calculation + m.On("Get", mock.Anything, "valid-parent", mock.Anything).Return( + &folders.Folder{}, + nil).Once() }, }, { diff --git a/pkg/registry/apis/folders/validate.go b/pkg/registry/apis/folders/validate.go index 7c956a670ea..fe9f0d5a719 100644 --- a/pkg/registry/apis/folders/validate.go +++ b/pkg/registry/apis/folders/validate.go @@ -6,6 +6,7 @@ import ( "slices" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/selection" "k8s.io/apiserver/pkg/registry/rest" folders "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" @@ -13,6 +14,7 @@ import ( "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/folder" + "github.com/grafana/grafana/pkg/storage/unified/resource" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" "github.com/grafana/grafana/pkg/util" ) @@ -73,6 +75,7 @@ func validateOnUpdate(ctx context.Context, old *folders.Folder, getter rest.Getter, parents parentsGetter, + searcher resourcepb.ResourceIndexClient, maxDepth int, ) error { folderObj, err := utils.MetaAccessor(obj) @@ -96,6 +99,10 @@ func validateOnUpdate(ctx context.Context, newParent := folderObj.GetFolder() switch newParent { + // If we move to root, we don't need to validate the depth, because the folder already existed + // before and wasn't too deep. This move will make it more shallow. + // + // We also don't need to validate circular references because the root folder cannot have a parent. case "", folder.GeneralFolderUID: return nil // OK, we do not need to validate the tree case folder.SharedWithMeFolderUID: @@ -114,9 +121,6 @@ func validateOnUpdate(ctx context.Context, if !ok { return fmt.Errorf("expected folder, found %T", parentObj) } - - //FIXME: until we have a way to represent the tree, we can only - // look at folder parents to check how deep the new folder tree will be info, err := parents(ctx, parent) if err != nil { return err @@ -130,13 +134,162 @@ func validateOnUpdate(ctx context.Context, } } - // if by moving a folder we exceed the max depth, return an error + // if by moving a folder we exceed the max depth just from its parents + itself, return an error if len(info.Items) > maxDepth+1 { return folder.ErrMaximumDepthReached.Errorf("maximum folder depth reached") } + // To try to save some computation, get the parents of the old parent (this is typically cheaper + // than looking at the children of the folder). If the old parent has more parents or the same + // number of parents as the new parent, we can return early, because we know the folder had to be + // safe from the creation validation. If we cannot access the older parent, we will continue to check the children. + if canSkipChildrenCheck(ctx, oldFolder, getter, parents, len(info.Items)) { + return nil + } + + // Now comes the more expensive part: we need to check if moving this folder will cause + // any descendant folders to exceed the max depth. + // + // Calculate the maximum allowed subtree depth after the move. + allowedDepth := (maxDepth + 1) - len(info.Items) + if allowedDepth <= 0 { + return nil + } + + return checkSubtreeDepth(ctx, searcher, obj.Namespace, obj.Name, allowedDepth, maxDepth) +} + +// canSkipChildrenCheck determines if we can skip the expensive children depth check. +// If the old parent depth is >= the new parent depth, the folder was already valid +// and this move won't make descendants exceed max depth. +func canSkipChildrenCheck(ctx context.Context, oldFolder utils.GrafanaMetaAccessor, getter rest.Getter, parents parentsGetter, newParentDepth int) bool { + if oldFolder.GetFolder() == folder.RootFolderUID { + return false + } + + oldParentObj, err := getter.Get(ctx, oldFolder.GetFolder(), &metav1.GetOptions{}) + if err != nil { + return false + } + + oldParent, ok := oldParentObj.(*folders.Folder) + if !ok { + return false + } + + oldInfo, err := parents(ctx, oldParent) + if err != nil { + return false + } + + oldParentDepth := len(oldInfo.Items) + levelDifference := newParentDepth - oldParentDepth + return levelDifference <= 0 +} + +// checkSubtreeDepth uses a hybrid DFS+batching approach: +// 1. fetches one page of children for the current folder(s) +// 2. batches all those children into one request to get their children +// 3. continues depth-first (batching still) until max depth or violation +// 4. only fetches more siblings after fully exploring current batch +func checkSubtreeDepth(ctx context.Context, searcher resourcepb.ResourceIndexClient, namespace string, folderUID string, remainingDepth int, maxDepth int) error { + if remainingDepth <= 0 { + return nil + } + + // Start with the folder being moved + return checkSubtreeDepthBatched(ctx, searcher, namespace, []string{folderUID}, remainingDepth, maxDepth) +} + +// checkSubtreeDepthBatched checks depth for a batch of folders at the same level +func checkSubtreeDepthBatched(ctx context.Context, searcher resourcepb.ResourceIndexClient, namespace string, parentUIDs []string, remainingDepth int, maxDepth int) error { + if remainingDepth <= 0 || len(parentUIDs) == 0 { + return nil + } + + const pageSize int64 = 1000 + var offset int64 + totalPages := 0 + hasMore := true + + // Using an upper limit to ensure no infinite loops can happen + for hasMore && totalPages < 1000 { + totalPages++ + + var err error + var children []string + children, hasMore, err = getChildrenBatch(ctx, searcher, namespace, parentUIDs, pageSize, offset) + if err != nil { + return fmt.Errorf("failed to get children: %w", err) + } + + if len(children) == 0 { + return nil + } + + // if we are at the last allowed depth and children exist, we will hit the max + if remainingDepth == 1 { + return folder.ErrMaximumDepthReached.Errorf("maximum folder depth %d would be exceeded after move", maxDepth) + } + + if err := checkSubtreeDepthBatched(ctx, searcher, namespace, children, remainingDepth-1, maxDepth); err != nil { + return err + } + + if !hasMore { + return nil + } + + offset += pageSize + } + return nil } +// getChildrenBatch fetches children for multiple parents +func getChildrenBatch(ctx context.Context, searcher resourcepb.ResourceIndexClient, namespace string, parentUIDs []string, limit int64, offset int64) ([]string, bool, error) { + if len(parentUIDs) == 0 { + return nil, false, nil + } + + resp, err := searcher.Search(ctx, &resourcepb.ResourceSearchRequest{ + Options: &resourcepb.ListOptions{ + Key: &resourcepb.ResourceKey{ + Namespace: namespace, + Group: folders.FolderResourceInfo.GroupVersionResource().Group, + Resource: folders.FolderResourceInfo.GroupVersionResource().Resource, + }, + Fields: []*resourcepb.Requirement{{ + Key: resource.SEARCH_FIELD_FOLDER, + Operator: string(selection.In), + Values: parentUIDs, + }}, + }, + Limit: limit, + Offset: offset, + }) + if err != nil { + return nil, false, fmt.Errorf("failed to search folders: %w", err) + } + + if resp.Error != nil { + return nil, false, fmt.Errorf("search error: %s", resp.Error.Message) + } + + if resp.Results == nil || len(resp.Results.Rows) == 0 { + return nil, false, nil + } + + children := make([]string, 0, len(resp.Results.Rows)) + for _, row := range resp.Results.Rows { + if row.Key != nil { + children = append(children, row.Key.Name) + } + } + + hasMore := resp.Results.NextPageToken != "" + return children, hasMore, nil +} + func validateOnDelete(ctx context.Context, f *folders.Folder, searcher resourcepb.ResourceIndexClient, diff --git a/pkg/registry/apis/folders/validate_test.go b/pkg/registry/apis/folders/validate_test.go index 7fdb3cfae12..b9f55571ce0 100644 --- a/pkg/registry/apis/folders/validate_test.go +++ b/pkg/registry/apis/folders/validate_test.go @@ -282,6 +282,7 @@ func TestValidateUpdate(t *testing.T) { old *folders.Folder parents *folders.FolderInfoList parentsError error + allFolders []folders.Folder expectedErr string maxDepth int // defaults to 5 unless set }{ @@ -454,6 +455,74 @@ func TestValidateUpdate(t *testing.T) { }, expectedErr: "cannot move folder under its own descendant", }, + { + name: "error when moving folder from root to level2 with children exceeds max depth", + folder: &folders.Folder{ + ObjectMeta: metav1.ObjectMeta{ + Name: "folderWithChildren", + Annotations: map[string]string{ + utils.AnnoKeyFolder: "level2", + }, + }, + Spec: folders.FolderSpec{ + Title: "folder with children", + }, + }, + old: &folders.Folder{ + ObjectMeta: metav1.ObjectMeta{ + Name: "folderWithChildren", + }, + Spec: folders.FolderSpec{ + Title: "folder with children", + }, + }, + parents: &folders.FolderInfoList{ + Items: []folders.FolderInfo{ + {Name: "level2", Parent: "level1"}, + {Name: "level1", Parent: folder.GeneralFolderUID}, + {Name: folder.GeneralFolderUID}, + }, + }, + allFolders: []folders.Folder{ + {ObjectMeta: metav1.ObjectMeta{Name: "child1", Annotations: map[string]string{utils.AnnoKeyFolder: "folderWithChildren"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "grandchild1", Annotations: map[string]string{utils.AnnoKeyFolder: "child1"}}}, + }, + maxDepth: 4, + expectedErr: "[folder.maximum-depth-reached]", + }, + { + name: "can move folder from root level to level1 with children when within max depth", + folder: &folders.Folder{ + ObjectMeta: metav1.ObjectMeta{ + Name: "folderWithChildren", + Annotations: map[string]string{ + utils.AnnoKeyFolder: "level1", + }, + }, + Spec: folders.FolderSpec{ + Title: "folder with children", + }, + }, + old: &folders.Folder{ + ObjectMeta: metav1.ObjectMeta{ + Name: "folderWithChildren", + }, + Spec: folders.FolderSpec{ + Title: "folder with children", + }, + }, + parents: &folders.FolderInfoList{ + Items: []folders.FolderInfo{ + {Name: "level1", Parent: folder.GeneralFolderUID}, + {Name: folder.GeneralFolderUID}, + }, + }, + allFolders: []folders.Folder{ + {ObjectMeta: metav1.ObjectMeta{Name: "child1", Annotations: map[string]string{utils.AnnoKeyFolder: "folderWithChildren"}}}, + {ObjectMeta: metav1.ObjectMeta{Name: "grandchild1", Annotations: map[string]string{utils.AnnoKeyFolder: "child1"}}}, + }, + maxDepth: 4, + }, } for _, tt := range tests { @@ -474,11 +543,17 @@ func TestValidateUpdate(t *testing.T) { }, nil).Maybe() } } + for i := range tt.allFolders { + f := tt.allFolders[i] + m.On("Get", context.Background(), f.Name, &metav1.GetOptions{}).Return(&f, nil).Maybe() + } err := validateOnUpdate(context.Background(), tt.folder, tt.old, m, func(ctx context.Context, folder *folders.Folder) (*folders.FolderInfoList, error) { return tt.parents, tt.parentsError - }, maxDepth) + }, + &mockSearchClient{folders: tt.allFolders}, + maxDepth) if tt.expectedErr == "" { require.NoError(t, err) @@ -693,8 +768,7 @@ type mockSearchClient struct { stats *resourcepb.ResourceStatsResponse statsErr error - search *resourcepb.ResourceSearchResponse - searchErr error + folders []folders.Folder } // GetStats implements resourcepb.ResourceIndexClient. @@ -703,8 +777,37 @@ func (m *mockSearchClient) GetStats(ctx context.Context, in *resourcepb.Resource } // Search implements resourcepb.ResourceIndexClient. -func (m *mockSearchClient) Search(ctx context.Context, in *resourcepb.ResourceSearchRequest, opts ...grpc.CallOption) (*resourcepb.ResourceSearchResponse, error) { - return m.search, m.searchErr +func (m *mockSearchClient) Search(ctx context.Context, req *resourcepb.ResourceSearchRequest, opts ...grpc.CallOption) (*resourcepb.ResourceSearchResponse, error) { + // get the list of parents from the search request + parentSet := make(map[string]bool) + if req.Options != nil && req.Options.Fields != nil { + for _, field := range req.Options.Fields { + if field.Key == "folder" && field.Operator == "in" { + for _, v := range field.Values { + parentSet[v] = true + } + } + } + } + + // find children that match the parent filter + var rows []*resourcepb.ResourceTableRow + for i := range m.folders { + meta, err := utils.MetaAccessor(&m.folders[i]) + if err != nil { + continue + } + parentUID := meta.GetFolder() + if parentSet[parentUID] { + rows = append(rows, &resourcepb.ResourceTableRow{ + Key: &resourcepb.ResourceKey{Name: m.folders[i].Name}, + }) + } + } + + return &resourcepb.ResourceSearchResponse{ + Results: &resourcepb.ResourceTable{Rows: rows}, + }, nil } // RebuildIndexes implements resourcepb.ResourceIndexClient. diff --git a/pkg/registry/apis/provisioning/accesscontrol.go b/pkg/registry/apis/provisioning/accesscontrol.go index e56ab7b06e2..755eabb60da 100644 --- a/pkg/registry/apis/provisioning/accesscontrol.go +++ b/pkg/registry/apis/provisioning/accesscontrol.go @@ -12,6 +12,12 @@ const ( ActionProvisioningRepositoriesRead = "provisioning.repositories:read" // GET + LIST. ActionProvisioningRepositoriesDelete = "provisioning.repositories:delete" // DELETE. + // Connections + ActionProvisioningConnectionsCreate = "provisioning.connections:create" // CREATE. + ActionProvisioningConnectionsWrite = "provisioning.connections:write" // UPDATE. + ActionProvisioningConnectionsRead = "provisioning.connections:read" // GET + LIST. + ActionProvisioningConnectionsDelete = "provisioning.connections:delete" // DELETE. + // Jobs ActionProvisioningJobsCreate = "provisioning.jobs:create" // CREATE. ActionProvisioningJobsWrite = "provisioning.jobs:write" // UPDATE. @@ -20,6 +26,12 @@ const ( // Historic Jobs ActionProvisioningHistoricJobsRead = "provisioning.historicjobs:read" // GET + LIST. + + // Settings (read-only, needed by multiple UI pages) + ActionProvisioningSettingsRead = "provisioning.settings:read" // GET + LIST. + + // Stats (read-only, admin-only) + ActionProvisioningStatsRead = "provisioning.stats:read" // GET + LIST. ) func registerAccessControlRoles(service accesscontrol.Service) error { @@ -63,6 +75,46 @@ func registerAccessControlRoles(service accesscontrol.Service) error { Grants: []string{string(org.RoleAdmin)}, } + // Connections + connectionsReader := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:provisioning.connections:reader", + DisplayName: "Connections Reader", + Description: "Read and list provisioning connections.", + Group: "Provisioning", + Permissions: []accesscontrol.Permission{ + { + Action: ActionProvisioningConnectionsRead, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + connectionsWriter := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:provisioning.connections:writer", + DisplayName: "Connections Writer", + Description: "Create, update and delete provisioning connections.", + Group: "Provisioning", + Permissions: []accesscontrol.Permission{ + { + Action: ActionProvisioningConnectionsCreate, + }, + { + Action: ActionProvisioningConnectionsRead, + }, + { + Action: ActionProvisioningConnectionsWrite, + }, + { + Action: ActionProvisioningConnectionsDelete, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + // Jobs jobsReader := accesscontrol.RoleRegistration{ Role: accesscontrol.RoleDTO{ @@ -119,11 +171,47 @@ func registerAccessControlRoles(service accesscontrol.Service) error { Grants: []string{string(org.RoleAdmin)}, } + // Settings - granted to Viewer (accessible by all logged-in users) + settingsReader := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:provisioning.settings:reader", + DisplayName: "Settings Reader", + Description: "Read provisioning settings.", + Group: "Provisioning", + Permissions: []accesscontrol.Permission{ + { + Action: ActionProvisioningSettingsRead, + }, + }, + }, + Grants: []string{string(org.RoleViewer)}, + } + + // Stats - granted to Admin only + statsReader := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:provisioning.stats:reader", + DisplayName: "Stats Reader", + Description: "Read provisioning stats.", + Group: "Provisioning", + Permissions: []accesscontrol.Permission{ + { + Action: ActionProvisioningStatsRead, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + return service.DeclareFixedRoles( repositoriesReader, repositoriesWriter, + connectionsReader, + connectionsWriter, jobsReader, jobsWriter, historicJobsReader, + settingsReader, + statsReader, ) } diff --git a/pkg/registry/apis/provisioning/files.go b/pkg/registry/apis/provisioning/files.go index ad9bc4bc472..a418860caac 100644 --- a/pkg/registry/apis/provisioning/files.go +++ b/pkg/registry/apis/provisioning/files.go @@ -13,9 +13,10 @@ import ( authlib "github.com/grafana/authlib/types" "github.com/grafana/grafana-app-sdk/logging" provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/auth" "github.com/grafana/grafana/apps/provisioning/pkg/repository" "github.com/grafana/grafana/apps/provisioning/pkg/safepath" - "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/registry/apis/provisioning/resources" ) @@ -26,12 +27,12 @@ const ( type filesConnector struct { getter RepoGetter - access authlib.AccessChecker + access auth.AccessChecker parsers resources.ParserFactory clients resources.ClientFactory } -func NewFilesConnector(getter RepoGetter, parsers resources.ParserFactory, clients resources.ClientFactory, access authlib.AccessChecker) *filesConnector { +func NewFilesConnector(getter RepoGetter, parsers resources.ParserFactory, clients resources.ClientFactory, access auth.AccessChecker) *filesConnector { return &filesConnector{getter: getter, parsers: parsers, clients: clients, access: access} } @@ -74,179 +75,233 @@ func (c *filesConnector) Connect(ctx context.Context, name string, opts runtime. ctx = logging.Context(ctx, logger) return WithTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - repo, err := c.getRepo(ctx, r.Method, name) - if err != nil { - logger.Debug("failed to find repository", "error", err) - responder.Error(err) - return - } - - readWriter, ok := repo.(repository.ReaderWriter) - if !ok { - responder.Error(apierrors.NewBadRequest("repository does not support read-writing")) - return - } - - parser, err := c.parsers.GetParser(ctx, readWriter) - if err != nil { - responder.Error(fmt.Errorf("failed to get parser: %w", err)) - return - } - - clients, err := c.clients.Clients(ctx, repo.Config().Namespace) - if err != nil { - responder.Error(fmt.Errorf("failed to get clients: %w", err)) - return - } - - folderClient, err := clients.Folder(ctx) - if err != nil { - responder.Error(fmt.Errorf("failed to get folder client: %w", err)) - return - } - folders := resources.NewFolderManager(readWriter, folderClient, resources.NewEmptyFolderTree()) - dualReadWriter := resources.NewDualReadWriter(readWriter, parser, folders, c.access) - query := r.URL.Query() - opts := resources.DualWriteOptions{ - Ref: query.Get("ref"), - Message: query.Get("message"), - SkipDryRun: query.Get("skipDryRun") == "true", - OriginalPath: query.Get("originalPath"), - Branch: repo.Config().Branch(), - } - logger := logger.With("url", r.URL.Path, "ref", opts.Ref, "message", opts.Message) - ctx := logging.Context(r.Context(), logger) - - opts.Path, err = pathAfterPrefix(r.URL.Path, fmt.Sprintf("/%s/files", name)) - if err != nil { - responder.Error(apierrors.NewBadRequest(err.Error())) - return - } - - if err := resources.IsPathSupported(opts.Path); err != nil { - responder.Error(apierrors.NewBadRequest(err.Error())) - return - } - - isDir := safepath.IsDir(opts.Path) - if r.Method == http.MethodGet && isDir { - files, err := c.listFolderFiles(ctx, opts.Path, opts.Ref, readWriter) - if err != nil { - responder.Error(err) - return - } - - responder.Object(http.StatusOK, files) - return - } - - if opts.Path == "" { - responder.Error(apierrors.NewBadRequest("missing request path")) - return - } - - var obj *provisioning.ResourceWrapper - code := http.StatusOK - switch r.Method { - case http.MethodGet: - resource, err := dualReadWriter.Read(ctx, opts.Path, opts.Ref) - if err != nil { - respondWithError(responder, err) - return - } - obj = resource.AsResourceWrapper() - case http.MethodPost: - // Check if this is a move operation first (originalPath query parameter is present) - if opts.OriginalPath != "" { - // For move operations, only read body for file moves (not directory moves) - if !isDir { - opts.Data, err = readBody(r, filesMaxBodySize) - if err != nil { - responder.Error(err) - return - } - } - - resource, err := dualReadWriter.MoveResource(ctx, opts) - if err != nil { - respondWithError(responder, err) - return - } - obj = resource.AsResourceWrapper() - } else if isDir { - obj, err = dualReadWriter.CreateFolder(ctx, opts) - } else { - opts.Data, err = readBody(r, filesMaxBodySize) - if err != nil { - responder.Error(err) - return - } - - var resource *resources.ParsedResource - resource, err = dualReadWriter.CreateResource(ctx, opts) - if err != nil { - respondWithError(responder, err) - return - } - obj = resource.AsResourceWrapper() - } - case http.MethodPut: - // TODO: document in API specification - if isDir { - err = apierrors.NewMethodNotSupported(provisioning.RepositoryResourceInfo.GroupResource(), r.Method) - } else { - opts.Data, err = readBody(r, filesMaxBodySize) - if err != nil { - responder.Error(err) - return - } - - resource, err := dualReadWriter.UpdateResource(ctx, opts) - if err != nil { - respondWithError(responder, err) - return - } - obj = resource.AsResourceWrapper() - } - case http.MethodDelete: - resource, err := dualReadWriter.Delete(ctx, opts) - if err != nil { - respondWithError(responder, err) - return - } - obj = resource.AsResourceWrapper() - default: - err = apierrors.NewMethodNotSupported(provisioning.RepositoryResourceInfo.GroupResource(), r.Method) - } - - if err != nil { - logger.Debug("got an error after processing request", "error", err) - responder.Error(err) - return - } - - if len(obj.Errors) > 0 { - code = http.StatusPartialContent - } - - logger.Debug("request resulted in valid object", "object", obj) - responder.Object(code, obj) + c.handleRequest(ctx, name, r, responder, logger) }), 30*time.Second), nil } -// listFolderFiles returns a list of files in a folder -func (c *filesConnector) listFolderFiles(ctx context.Context, filePath string, ref string, readWriter repository.ReaderWriter) (*provisioning.FileList, error) { - id, err := identity.GetRequester(ctx) +// handleRequest processes the HTTP request for files operations. +func (c *filesConnector) handleRequest(ctx context.Context, name string, r *http.Request, responder rest.Responder, logger logging.Logger) { + repo, err := c.getRepo(ctx, r.Method, name) if err != nil { - return nil, fmt.Errorf("missing auth info in context") + logger.Debug("failed to find repository", "error", err) + responder.Error(err) + return } - // TODO: replace with access check on the repo itself - if !id.GetOrgRole().Includes(identity.RoleAdmin) { - return nil, apierrors.NewForbidden(resources.DashboardResource.GroupResource(), "", - fmt.Errorf("requires admin role")) + readWriter, ok := repo.(repository.ReaderWriter) + if !ok { + responder.Error(apierrors.NewBadRequest("repository does not support read-writing")) + return } + dualReadWriter, err := c.createDualReadWriter(ctx, repo, readWriter) + if err != nil { + responder.Error(err) + return + } + + opts, err := c.parseRequestOptions(r, name, repo) + if err != nil { + responder.Error(apierrors.NewBadRequest(err.Error())) + return + } + + logger = logger.With("url", r.URL.Path, "ref", opts.Ref, "message", opts.Message) + ctx = logging.Context(r.Context(), logger) + + // Handle directory listing separately + isDir := safepath.IsDir(opts.Path) + if r.Method == http.MethodGet && isDir { + c.handleDirectoryListing(ctx, name, opts, readWriter, responder) + return + } + + if opts.Path == "" { + responder.Error(apierrors.NewBadRequest("missing request path")) + return + } + + obj, err := c.handleMethodRequest(ctx, r, opts, isDir, dualReadWriter) + if err != nil { + logger.Debug("got an error after processing request", "error", err) + respondWithError(responder, err) + return + } + + code := http.StatusOK + if len(obj.Errors) > 0 { + code = http.StatusPartialContent + } + + logger.Debug("request resulted in valid object", "object", obj) + responder.Object(code, obj) +} + +// createDualReadWriter sets up the dual read writer with all required dependencies. +func (c *filesConnector) createDualReadWriter(ctx context.Context, repo repository.Repository, readWriter repository.ReaderWriter) (*resources.DualReadWriter, error) { + parser, err := c.parsers.GetParser(ctx, readWriter) + if err != nil { + return nil, fmt.Errorf("failed to get parser: %w", err) + } + + clients, err := c.clients.Clients(ctx, repo.Config().Namespace) + if err != nil { + return nil, fmt.Errorf("failed to get clients: %w", err) + } + + folderClient, err := clients.Folder(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get folder client: %w", err) + } + + folders := resources.NewFolderManager(readWriter, folderClient, resources.NewEmptyFolderTree()) + return resources.NewDualReadWriter(readWriter, parser, folders, c.access), nil +} + +// parseRequestOptions extracts options from the HTTP request. +func (c *filesConnector) parseRequestOptions(r *http.Request, name string, repo repository.Repository) (resources.DualWriteOptions, error) { + query := r.URL.Query() + opts := resources.DualWriteOptions{ + Ref: query.Get("ref"), + Message: query.Get("message"), + SkipDryRun: query.Get("skipDryRun") == "true", + OriginalPath: query.Get("originalPath"), + Branch: repo.Config().Branch(), + } + + path, err := pathAfterPrefix(r.URL.Path, fmt.Sprintf("/%s/files", name)) + if err != nil { + return opts, err + } + opts.Path = path + + if err := resources.IsPathSupported(opts.Path); err != nil { + return opts, err + } + + return opts, nil +} + +// handleDirectoryListing handles GET requests for directory listing. +func (c *filesConnector) handleDirectoryListing(ctx context.Context, name string, opts resources.DualWriteOptions, readWriter repository.ReaderWriter, responder rest.Responder) { + if err := c.authorizeListFiles(ctx, name); err != nil { + responder.Error(err) + return + } + + files, err := c.listFolderFiles(ctx, opts.Path, opts.Ref, readWriter) + if err != nil { + responder.Error(err) + return + } + + responder.Object(http.StatusOK, files) +} + +// handleMethodRequest routes the request to the appropriate handler based on HTTP method. +func (c *filesConnector) handleMethodRequest(ctx context.Context, r *http.Request, opts resources.DualWriteOptions, isDir bool, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + switch r.Method { + case http.MethodGet: + return c.handleGet(ctx, opts, dualReadWriter) + case http.MethodPost: + return c.handlePost(ctx, r, opts, isDir, dualReadWriter) + case http.MethodPut: + return c.handlePut(ctx, r, opts, isDir, dualReadWriter) + case http.MethodDelete: + return c.handleDelete(ctx, opts, dualReadWriter) + default: + return nil, apierrors.NewMethodNotSupported(provisioning.RepositoryResourceInfo.GroupResource(), r.Method) + } +} + +func (c *filesConnector) handleGet(ctx context.Context, opts resources.DualWriteOptions, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + resource, err := dualReadWriter.Read(ctx, opts.Path, opts.Ref) + if err != nil { + return nil, err + } + return resource.AsResourceWrapper(), nil +} + +func (c *filesConnector) handlePost(ctx context.Context, r *http.Request, opts resources.DualWriteOptions, isDir bool, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + // Check if this is a move operation (originalPath query parameter is present) + if opts.OriginalPath != "" { + return c.handleMove(ctx, r, opts, isDir, dualReadWriter) + } + + if isDir { + return dualReadWriter.CreateFolder(ctx, opts) + } + + data, err := readBody(r, filesMaxBodySize) + if err != nil { + return nil, err + } + opts.Data = data + + resource, err := dualReadWriter.CreateResource(ctx, opts) + if err != nil { + return nil, err + } + return resource.AsResourceWrapper(), nil +} + +func (c *filesConnector) handleMove(ctx context.Context, r *http.Request, opts resources.DualWriteOptions, isDir bool, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + // For move operations, only read body for file moves (not directory moves) + if !isDir { + data, err := readBody(r, filesMaxBodySize) + if err != nil { + return nil, err + } + opts.Data = data + } + + resource, err := dualReadWriter.MoveResource(ctx, opts) + if err != nil { + return nil, err + } + return resource.AsResourceWrapper(), nil +} + +func (c *filesConnector) handlePut(ctx context.Context, r *http.Request, opts resources.DualWriteOptions, isDir bool, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + if isDir { + return nil, apierrors.NewMethodNotSupported(provisioning.RepositoryResourceInfo.GroupResource(), r.Method) + } + + data, err := readBody(r, filesMaxBodySize) + if err != nil { + return nil, err + } + opts.Data = data + + resource, err := dualReadWriter.UpdateResource(ctx, opts) + if err != nil { + return nil, err + } + return resource.AsResourceWrapper(), nil +} + +func (c *filesConnector) handleDelete(ctx context.Context, opts resources.DualWriteOptions, dualReadWriter *resources.DualReadWriter) (*provisioning.ResourceWrapper, error) { + resource, err := dualReadWriter.Delete(ctx, opts) + if err != nil { + return nil, err + } + return resource.AsResourceWrapper(), nil +} + +// authorizeListFiles checks if the user has repositories:read permission for listing files. +// The access checker handles AccessPolicy identities, namespace resolution, and role-based fallback internally. +func (c *filesConnector) authorizeListFiles(ctx context.Context, repoName string) error { + return c.access.Check(ctx, authlib.CheckRequest{ + Verb: utils.VerbGet, + Group: provisioning.GROUP, + Resource: provisioning.RepositoryResourceInfo.GetName(), + Name: repoName, + }, "") +} + +// listFolderFiles returns a list of files in a folder. +// Authorization is checked via authorizeListFiles before calling this function. +func (c *filesConnector) listFolderFiles(ctx context.Context, filePath string, ref string, readWriter repository.ReaderWriter) (*provisioning.FileList, error) { // TODO: Implement folder navigation if len(filePath) > 0 { return nil, apierrors.NewBadRequest("folder navigation not yet supported") diff --git a/pkg/registry/apis/provisioning/register.go b/pkg/registry/apis/provisioning/register.go index 80c22338ae0..26e97f56b3c 100644 --- a/pkg/registry/apis/provisioning/register.go +++ b/pkg/registry/apis/provisioning/register.go @@ -29,6 +29,7 @@ import ( "github.com/grafana/grafana-app-sdk/logging" provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/auth" connectionvalidation "github.com/grafana/grafana/apps/provisioning/pkg/connection" appcontroller "github.com/grafana/grafana/apps/provisioning/pkg/controller" clientset "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned" @@ -111,7 +112,10 @@ type APIBuilder struct { unified resource.ResourceClient repoFactory repository.Factory client client.ProvisioningV0alpha1Interface - access authlib.AccessChecker + access auth.AccessChecker + accessWithAdmin auth.AccessChecker + accessWithEditor auth.AccessChecker + accessWithViewer auth.AccessChecker statusPatcher *appcontroller.RepositoryStatusPatcher healthChecker *controller.HealthChecker validator repository.RepositoryValidator @@ -158,6 +162,14 @@ func NewAPIBuilder( parsers := resources.NewParserFactory(clients) resourceLister := resources.NewResourceListerForMigrations(unified) + // Create access checker based on mode + var accessChecker auth.AccessChecker + if useExclusivelyAccessCheckerForAuthz { + accessChecker = auth.NewTokenAccessChecker(access) + } else { + accessChecker = auth.NewSessionAccessChecker(access) + } + b := &APIBuilder{ onlyApiServer: onlyApiServer, tracer: tracer, @@ -170,7 +182,10 @@ func NewAPIBuilder( resourceLister: resourceLister, dashboardAccess: dashboardAccess, unified: unified, - access: access, + access: accessChecker, + accessWithAdmin: accessChecker.WithFallbackRole(identity.RoleAdmin), + accessWithEditor: accessChecker.WithFallbackRole(identity.RoleEditor), + accessWithViewer: accessChecker.WithFallbackRole(identity.RoleViewer), jobHistoryConfig: jobHistoryConfig, extraWorkers: extraWorkers, restConfigGetter: restConfigGetter, @@ -298,161 +313,142 @@ func (b *APIBuilder) GetAuthorizer() authorizer.Authorizer { } } - info, ok := authlib.AuthInfoFrom(ctx) - // when running as standalone API server, the identity type may not always match TypeAccessPolicy - // so we allow it to use the access checker if there is any auth info available - if ok && (authlib.IsIdentityType(info.GetIdentityType(), authlib.TypeAccessPolicy) || b.useExclusivelyAccessCheckerForAuthz) { - res, err := b.access.Check(ctx, info, authlib.CheckRequest{ - Verb: a.GetVerb(), - Group: a.GetAPIGroup(), - Resource: a.GetResource(), - Name: a.GetName(), - Namespace: a.GetNamespace(), - Subresource: a.GetSubresource(), - Path: a.GetPath(), - }, "") - if err != nil { - return authorizer.DecisionDeny, "failed to perform authorization", err - } - - if !res.Allowed { - return authorizer.DecisionDeny, "permission denied", nil - } - - return authorizer.DecisionAllow, "", nil - } - - id, err := identity.GetRequester(ctx) - if err != nil { - return authorizer.DecisionDeny, "failed to find requester", err - } - - return b.authorizeResource(ctx, a, id) + return b.authorizeResource(ctx, a) }) } // authorizeResource handles authorization for different resources. -// Different routes may need different permissions. -// * Reading and modifying a repository's configuration requires administrator privileges. -// * Reading a repository's limited configuration (/stats & /settings) requires viewer privileges. -// * Reading a repository's files requires viewer privileges. -// * Reading a repository's refs requires viewer privileges. -// * Editing a repository's files requires editor privileges. -// * Syncing a repository requires editor privileges. -// * Exporting a repository requires administrator privileges. -// * Migrating a repository requires administrator privileges. -// * Testing a repository configuration requires administrator privileges. -// * Viewing a repository's history requires editor privileges. -func (b *APIBuilder) authorizeResource(ctx context.Context, a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { +// Uses fine-grained permissions defined in accesscontrol.go: +// +// Repositories: +// - CRUD: repositories:create/read/write/delete +// - Subresources: files (any auth), refs (editor), resources/history/status (admin) +// - Test: repositories:write +// - Jobs subresource: jobs:create/read +// +// Connections: +// - CRUD: connections:create/read/write/delete +// - Status: connections:read +// +// Jobs: +// - CRUD: jobs:create/read/write/delete +// +// Historic Jobs: +// - Read-only: historicjobs:read +// +// Settings: +// - settings:read - granted to Viewer (all logged-in users) +// +// Stats: +// - stats:read - granted to Admin only +func (b *APIBuilder) authorizeResource(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) { switch a.GetResource() { case provisioning.RepositoryResourceInfo.GetName(): - return b.authorizeRepositorySubresource(a, id) - case "stats": - return b.authorizeStats(id) - case "settings": - return b.authorizeSettings(id) - case provisioning.JobResourceInfo.GetName(), provisioning.HistoricJobResourceInfo.GetName(): - return b.authorizeJobs(id) + return b.authorizeRepositorySubresource(ctx, a) case provisioning.ConnectionResourceInfo.GetName(): - return b.authorizeConnectionSubresource(a, id) + return b.authorizeConnectionSubresource(ctx, a) + case provisioning.JobResourceInfo.GetName(): + return toAuthorizerDecision(b.accessWithEditor.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: provisioning.JobResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + case provisioning.HistoricJobResourceInfo.GetName(): + // Historic jobs are read-only and admin-only (not editor) + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: provisioning.HistoricJobResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + case "settings": + // Settings are read-only and accessible by all logged-in users (Viewer role) + return toAuthorizerDecision(b.accessWithViewer.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: "settings", + Namespace: a.GetNamespace(), + }, "")) + case "stats": + // Stats are read-only and admin-only + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: "stats", + Namespace: a.GetNamespace(), + }, "")) default: - return b.authorizeDefault(id) + return b.authorizeDefault(ctx) } } // authorizeRepositorySubresource handles authorization for repository subresources. -func (b *APIBuilder) authorizeRepositorySubresource(a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { - // TODO: Support more fine-grained permissions than the basic roles. Especially on Enterprise. - switch a.GetSubresource() { - case "", "test": - // Doing something with the repository itself. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil - - case "jobs": - // Posting jobs requires editor privileges (for syncing). - if id.GetOrgRole().Includes(identity.RoleAdmin) || id.GetOrgRole().Includes(identity.RoleEditor) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "editor role is required", nil - - case "refs": - // This is strictly a read operation. It is handy on the frontend for viewers. - if id.GetOrgRole().Includes(identity.RoleViewer) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "viewer role is required", nil - - case "files": - // Access to files is controlled by the AccessClient - return authorizer.DecisionAllow, "", nil - - case "resources", "sync", "history": - // These are strictly read operations. - // Sync can also be somewhat destructive, but it's expected to be fine to import changes. - if id.GetOrgRole().Includes(identity.RoleEditor) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "editor role is required", nil - - case "status": - if id.GetOrgRole().Includes(identity.RoleViewer) && a.GetVerb() == apiutils.VerbGet { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "users cannot update the status of a repository", nil - - default: - if id.GetIsGrafanaAdmin() { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "unmapped subresource defaults to no access", nil - } -} - -// authorizeStats handles authorization for stats resource. -func (b *APIBuilder) authorizeStats(id identity.Requester) (authorizer.Decision, string, error) { - // This can leak information one shouldn't necessarily have access to. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil -} - -// authorizeSettings handles authorization for settings resource. -func (b *APIBuilder) authorizeSettings(id identity.Requester) (authorizer.Decision, string, error) { - // This is strictly a read operation. It is handy on the frontend for viewers. - if id.GetOrgRole().Includes(identity.RoleViewer) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "viewer role is required", nil -} - -// authorizeJobs handles authorization for job resources. -func (b *APIBuilder) authorizeJobs(id identity.Requester) (authorizer.Decision, string, error) { - // Jobs are shown on the configuration page. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil -} - -// authorizeRepositorySubresource handles authorization for connections subresources. -func (b *APIBuilder) authorizeConnectionSubresource(a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { +// Uses the access checker with verb-based authorization. +func (b *APIBuilder) authorizeRepositorySubresource(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) { switch a.GetSubresource() { + // Repository CRUD - use access checker with the actual verb case "": - // Doing something with the connection itself. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil - case "status": - if id.GetOrgRole().Includes(identity.RoleViewer) && a.GetVerb() == apiutils.VerbGet { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "users cannot update the status of a connection", nil + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: provisioning.RepositoryResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + // Test requires write permission (testing before save) + case "test": + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: apiutils.VerbUpdate, + Group: provisioning.GROUP, + Resource: provisioning.RepositoryResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + // Files subresource: allow any authenticated user at route level. + // Directory listing checks repositories:read in the connector. + // Individual file operations are authorized by DualReadWriter based on the actual resource. + case "files": + return authorizer.DecisionAllow, "", nil + + // refs subresource - editors need to see branches to push changes + case "refs": + return toAuthorizerDecision(b.accessWithEditor.Check(ctx, authlib.CheckRequest{ + Verb: apiutils.VerbGet, + Group: provisioning.GROUP, + Resource: provisioning.RepositoryResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + // Read-only subresources: resources, history, status (admin only) + case "resources", "history", "status": + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: apiutils.VerbGet, + Group: provisioning.GROUP, + Resource: provisioning.RepositoryResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + // Jobs subresource - check jobs permissions with the verb (editors can manage jobs) + case "jobs": + return toAuthorizerDecision(b.accessWithEditor.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: provisioning.JobResourceInfo.GetName(), + Namespace: a.GetNamespace(), + }, "")) + default: + id, err := identity.GetRequester(ctx) + if err != nil { + return authorizer.DecisionDeny, "failed to find requester", err + } if id.GetIsGrafanaAdmin() { return authorizer.DecisionAllow, "", nil } @@ -460,8 +456,60 @@ func (b *APIBuilder) authorizeConnectionSubresource(a authorizer.Attributes, id } } +// authorizeConnectionSubresource handles authorization for connection subresources. +// Uses the access checker with verb-based authorization. +func (b *APIBuilder) authorizeConnectionSubresource(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) { + switch a.GetSubresource() { + // Connection CRUD - use access checker with the actual verb + case "": + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: a.GetVerb(), + Group: provisioning.GROUP, + Resource: provisioning.ConnectionResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + // Status is read-only + case "status": + return toAuthorizerDecision(b.accessWithAdmin.Check(ctx, authlib.CheckRequest{ + Verb: apiutils.VerbGet, + Group: provisioning.GROUP, + Resource: provisioning.ConnectionResourceInfo.GetName(), + Name: a.GetName(), + Namespace: a.GetNamespace(), + }, "")) + + default: + id, err := identity.GetRequester(ctx) + if err != nil { + return authorizer.DecisionDeny, "failed to find requester", err + } + if id.GetIsGrafanaAdmin() { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "unmapped subresource defaults to no access", nil + } +} + +// ---------------------------------------------------------------------------- +// Authorization helpers +// ---------------------------------------------------------------------------- + +// toAuthorizerDecision converts an access check error to an authorizer decision tuple. +func toAuthorizerDecision(err error) (authorizer.Decision, string, error) { + if err != nil { + return authorizer.DecisionDeny, err.Error(), nil + } + return authorizer.DecisionAllow, "", nil +} + // authorizeDefault handles authorization for unmapped resources. -func (b *APIBuilder) authorizeDefault(id identity.Requester) (authorizer.Decision, string, error) { +func (b *APIBuilder) authorizeDefault(ctx context.Context) (authorizer.Decision, string, error) { + id, err := identity.GetRequester(ctx) + if err != nil { + return authorizer.DecisionDeny, "failed to find requester", err + } // We haven't bothered with this kind yet. if id.GetIsGrafanaAdmin() { return authorizer.DecisionAllow, "", nil @@ -558,7 +606,7 @@ func (b *APIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.APIGroupI // TODO: Add some logic so that the connectors can registered themselves and we don't have logic all over the place storage[provisioning.RepositoryResourceInfo.StoragePath("test")] = NewTestConnector(b, repository.NewRepositoryTesterWithExistingChecker(repository.NewSimpleRepositoryTester(b.validator), b.VerifyAgainstExistingRepositories)) - storage[provisioning.RepositoryResourceInfo.StoragePath("files")] = NewFilesConnector(b, b.parsers, b.clients, b.access) + storage[provisioning.RepositoryResourceInfo.StoragePath("files")] = NewFilesConnector(b, b.parsers, b.clients, b.accessWithAdmin) storage[provisioning.RepositoryResourceInfo.StoragePath("refs")] = NewRefsConnector(b) storage[provisioning.RepositoryResourceInfo.StoragePath("resources")] = &listConnector{ getter: b, @@ -673,7 +721,8 @@ func (b *APIBuilder) Validate(ctx context.Context, a admission.Attributes, o adm // // the only time to add configuration checks here is if you need to compare // the incoming change to the current configuration - list := b.validator.ValidateRepository(repo) + isCreate := a.GetOperation() == admission.Create + list := b.validator.ValidateRepository(repo, isCreate) cfg := repo.Config() if a.GetOperation() == admission.Update { diff --git a/pkg/registry/apis/provisioning/resources/dualwriter.go b/pkg/registry/apis/provisioning/resources/dualwriter.go index 9180ace494d..e8a7ee83dd0 100644 --- a/pkg/registry/apis/provisioning/resources/dualwriter.go +++ b/pkg/registry/apis/provisioning/resources/dualwriter.go @@ -12,6 +12,7 @@ import ( authlib "github.com/grafana/authlib/types" "github.com/grafana/grafana-app-sdk/logging" provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/auth" "github.com/grafana/grafana/apps/provisioning/pkg/repository" "github.com/grafana/grafana/apps/provisioning/pkg/safepath" "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1" @@ -32,7 +33,7 @@ type DualReadWriter struct { repo repository.ReaderWriter parser Parser folders *FolderManager - access authlib.AccessChecker + access auth.AccessChecker } type DualWriteOptions struct { @@ -48,7 +49,7 @@ type DualWriteOptions struct { Branch string // Configured default branch } -func NewDualReadWriter(repo repository.ReaderWriter, parser Parser, folders *FolderManager, access authlib.AccessChecker) *DualReadWriter { +func NewDualReadWriter(repo repository.ReaderWriter, parser Parser, folders *FolderManager, access auth.AccessChecker) *DualReadWriter { return &DualReadWriter{repo: repo, parser: parser, folders: folders, access: access} } @@ -492,11 +493,6 @@ func (r *DualReadWriter) moveFile(ctx context.Context, opts DualWriteOptions) (* } func (r *DualReadWriter) authorize(ctx context.Context, parsed *ParsedResource, verb string) error { - id, err := identity.GetRequester(ctx) - if err != nil { - return apierrors.NewUnauthorized(err.Error()) - } - var name string if parsed.Existing != nil { name = parsed.Existing.GetName() @@ -504,27 +500,15 @@ func (r *DualReadWriter) authorize(ctx context.Context, parsed *ParsedResource, name = parsed.Obj.GetName() } - rsp, err := r.access.Check(ctx, id, authlib.CheckRequest{ - Group: parsed.GVR.Group, - Resource: parsed.GVR.Resource, - Namespace: id.GetNamespace(), - Name: name, - Verb: verb, + return r.access.Check(ctx, authlib.CheckRequest{ + Group: parsed.GVR.Group, + Resource: parsed.GVR.Resource, + Name: name, + Verb: verb, }, parsed.Meta.GetFolder()) - if err != nil || !rsp.Allowed { - return apierrors.NewForbidden(parsed.GVR.GroupResource(), parsed.Obj.GetName(), - fmt.Errorf("no access to perform %s on the resource", verb)) - } - - return nil } func (r *DualReadWriter) authorizeCreateFolder(ctx context.Context, path string) error { - id, err := identity.GetRequester(ctx) - if err != nil { - return apierrors.NewUnauthorized(err.Error()) - } - // Determine parent folder from path parentFolder := "" if path != "" { @@ -537,19 +521,12 @@ func (r *DualReadWriter) authorizeCreateFolder(ctx context.Context, path string) } // For folder create operations, use empty name to check parent folder permissions - rsp, err := r.access.Check(ctx, id, authlib.CheckRequest{ - Group: FolderResource.Group, - Resource: FolderResource.Resource, - Namespace: id.GetNamespace(), - Name: "", // Empty name for create operations - Verb: utils.VerbCreate, + return r.access.Check(ctx, authlib.CheckRequest{ + Group: FolderResource.Group, + Resource: FolderResource.Resource, + Name: "", // Empty name for create operations + Verb: utils.VerbCreate, }, parentFolder) - if err != nil || !rsp.Allowed { - return apierrors.NewForbidden(FolderResource.GroupResource(), path, - fmt.Errorf("no access to create folder in parent folder '%s'", parentFolder)) - } - - return nil } func (r *DualReadWriter) deleteFolder(ctx context.Context, opts DualWriteOptions) (*ParsedResource, error) { diff --git a/pkg/registry/apps/logsdrilldown/authorizer.go b/pkg/registry/apps/logsdrilldown/authorizer.go index f485937121d..b9ba63a3cd2 100644 --- a/pkg/registry/apps/logsdrilldown/authorizer.go +++ b/pkg/registry/apps/logsdrilldown/authorizer.go @@ -24,26 +24,38 @@ func GetAuthorizer() authorizer.Authorizer { return authorizer.DecisionDeny, "valid user is required", err } + // check if is admin + if u.GetIsGrafanaAdmin() { + return authorizer.DecisionAllow, "isGrafanaAdmin", nil + } + // Auth handling for LogsDrilldownDefaults resource if attr.GetResource() == "logsdrilldowndefaults" { // Allow list and get for everyone if attr.GetVerb() == "list" || attr.GetVerb() == "get" { return authorizer.DecisionAllow, "", nil } - // Only allow admins to update (create, update, patch, delete) - if u.GetIsGrafanaAdmin() { - return authorizer.DecisionAllow, "", nil - } // Deny all other operations for non-admins return authorizer.DecisionDeny, "admin access required", nil } - // check if is admin - if u.GetIsGrafanaAdmin() { - return authorizer.DecisionAllow, "", nil + p := u.GetPermissions() + + // Auth handling for Logs Drilldown default columns + if attr.GetResource() == "logsdrilldowndefaultcolumns" { + // Allow get for all users + if attr.GetVerb() == "get" { + return authorizer.DecisionAllow, "", nil + } + // require plugins:write permissions for other operations + _, ok := p[accesscontrol.PluginRolePrefix+"write"] + if ok { + return authorizer.DecisionAllow, "user has plugins:write", nil + } else { + return authorizer.DecisionDeny, "user missing plugins:write", nil + } } - p := u.GetPermissions() if len(p) == 0 { return authorizer.DecisionDeny, "no permissions", nil } diff --git a/pkg/services/authn/clients/ext_jwt.go b/pkg/services/authn/clients/ext_jwt.go index b479f314c76..be9efa9ce76 100644 --- a/pkg/services/authn/clients/ext_jwt.go +++ b/pkg/services/authn/clients/ext_jwt.go @@ -131,7 +131,8 @@ func (s *ExtendedJWT) authenticateAsUser( return nil, errExtJWTInvalid.Errorf("failed to parse id token subject: %w", err) } - if !claims.IsIdentityType(t, claims.TypeUser) { + // TODO: How to support other identity types like render and anonymous here? + if !claims.IsIdentityType(t, claims.TypeUser, claims.TypeServiceAccount) { return nil, errExtJWTInvalidSubject.Errorf("unexpected identity: %s", idTokenClaims.Subject) } diff --git a/pkg/services/authn/clients/ext_jwt_test.go b/pkg/services/authn/clients/ext_jwt_test.go index 88cf11fb83a..3c7203844b1 100644 --- a/pkg/services/authn/clients/ext_jwt_test.go +++ b/pkg/services/authn/clients/ext_jwt_test.go @@ -53,6 +53,17 @@ var ( Namespace: "default", // org ID of 1 is special and translates to default }, } + validIDTokenClaimsWithServiceAccount = idTokenClaims{ + Claims: jwt.Claims{ + Subject: "service-account:3", + Expiry: jwt.NewNumericDate(time.Date(2023, 5, 3, 0, 0, 0, 0, time.UTC)), + IssuedAt: jwt.NewNumericDate(time.Date(2023, 5, 2, 0, 0, 0, 0, time.UTC)), + }, + Rest: authnlib.IDTokenClaims{ + AuthenticatedBy: "extended_jwt", + Namespace: "default", // org ID of 1 is special and translates to default + }, + } validIDTokenClaimsWithStackSet = idTokenClaims{ Claims: jwt.Claims{ Subject: "user:2", @@ -118,7 +129,7 @@ var ( } invalidSubjectIDTokenClaims = idTokenClaims{ Claims: jwt.Claims{ - Subject: "service-account:2", + Subject: "anonymous:2", Expiry: jwt.NewNumericDate(time.Date(2023, 5, 3, 0, 0, 0, 0, time.UTC)), IssuedAt: jwt.NewNumericDate(time.Date(2023, 5, 2, 0, 0, 0, 0, time.UTC)), }, @@ -286,6 +297,29 @@ func TestExtendedJWT_Authenticate(t *testing.T) { }, }, }, + { + name: "should authenticate as service account", + accessToken: &validAccessTokenClaims, + idToken: &validIDTokenClaimsWithServiceAccount, + orgID: 1, + want: &authn.Identity{ + ID: "3", + Type: claims.TypeServiceAccount, + OrgID: 1, + AccessTokenClaims: &validAccessTokenClaims, + IDTokenClaims: &validIDTokenClaimsWithServiceAccount, + Namespace: "default", + AuthenticatedBy: "extendedjwt", + AuthID: "access-policy:this-uid", + ClientParams: authn.ClientParams{ + FetchSyncedUser: true, + SyncPermissions: true, + FetchPermissionsParams: authn.FetchPermissionsParams{ + RestrictedActions: []string{"dashboards:create", "folders:read", "datasources:explore", "datasources.insights:read"}, + }, + }, + }, + }, { name: "should authenticate as user in the user namespace", accessToken: &validAccessTokenClaimsWildcard, diff --git a/pkg/services/authz/rbac/mapper.go b/pkg/services/authz/rbac/mapper.go index 9444d35d0ae..dcf2432fb2c 100644 --- a/pkg/services/authz/rbac/mapper.go +++ b/pkg/services/authz/rbac/mapper.go @@ -279,8 +279,11 @@ func NewMapperRegistry() MapperRegistry { }, "provisioning.grafana.app": { "repositories": newResourceTranslation("provisioning.repositories", "uid", false, skipScopeOnAllVerbs), + "connections": newResourceTranslation("provisioning.connections", "uid", false, skipScopeOnAllVerbs), "jobs": newResourceTranslation("provisioning.jobs", "uid", false, skipScopeOnAllVerbs), "historicjobs": newResourceTranslation("provisioning.historicjobs", "uid", false, skipScopeOnAllVerbs), + "settings": newResourceTranslation("provisioning.settings", "", false, skipScopeOnAllVerbs), + "stats": newResourceTranslation("provisioning.stats", "", false, skipScopeOnAllVerbs), }, "secret.grafana.app": { "securevalues": newResourceTranslation("secret.securevalues", "uid", false, nil), diff --git a/pkg/services/featuremgmt/registry.go b/pkg/services/featuremgmt/registry.go index e9a4a8c7caf..d6f2bcbec2e 100644 --- a/pkg/services/featuremgmt/registry.go +++ b/pkg/services/featuremgmt/registry.go @@ -185,13 +185,6 @@ var ( Stage: FeatureStageExperimental, Owner: grafanaDatasourcesCoreServicesSquad, }, - { - Name: "unifiedRequestLog", - Description: "Writes error logs to the request logger", - Stage: FeatureStageGeneralAvailability, - Owner: grafanaBackendGroup, - Expression: "true", - }, { Name: "renderAuthJWT", Description: "Uses JWT-based auth for rendering instead of relying on remote cache", @@ -892,6 +885,13 @@ var ( Owner: grafanaAlertingSquad, FrontendOnly: true, }, + { + Name: "alertingSavedSearches", + Description: "Enables saved searches for alert rules list", + Stage: FeatureStageExperimental, + Owner: grafanaAlertingSquad, + FrontendOnly: true, + }, { Name: "alertingDisableSendAlertsExternal", Description: "Disables the ability to send alerts to an external Alertmanager datasource.", @@ -1975,6 +1975,14 @@ var ( Owner: identityAccessTeam, Expression: "true", }, + { + Name: "pluginInsights", + Description: "Show insights for plugins in the plugin details page", + Stage: FeatureStageExperimental, + FrontendOnly: true, + Owner: grafanaPluginsPlatformSquad, + Expression: "false", + }, { Name: "panelTimeSettings", Description: "Enables a new panel time settings drawer", diff --git a/pkg/services/featuremgmt/toggles_gen.csv b/pkg/services/featuremgmt/toggles_gen.csv index d56aff17bb7..179568aa0c4 100644 --- a/pkg/services/featuremgmt/toggles_gen.csv +++ b/pkg/services/featuremgmt/toggles_gen.csv @@ -24,7 +24,6 @@ influxqlStreamingParser,experimental,@grafana/partner-datasources,false,false,fa influxdbRunQueriesInParallel,privatePreview,@grafana/partner-datasources,false,false,false lokiLogsDataplane,experimental,@grafana/observability-logs,false,false,false disableSSEDataplane,experimental,@grafana/grafana-datasources-core-services,false,false,false -unifiedRequestLog,GA,@grafana/grafana-backend-group,false,false,false renderAuthJWT,preview,@grafana/grafana-operator-experience-squad,false,false,false refactorVariablesTimeRange,preview,@grafana/dashboards-squad,false,false,false faroDatasourceSelector,preview,@grafana/app-o11y,false,false,true @@ -123,6 +122,7 @@ suggestedDashboards,experimental,@grafana/sharing-squad,false,false,false dashboardTemplates,preview,@grafana/sharing-squad,false,false,false logsExploreTableDefaultVisualization,experimental,@grafana/observability-logs,false,false,true alertingListViewV2,privatePreview,@grafana/alerting-squad,false,false,true +alertingSavedSearches,experimental,@grafana/alerting-squad,false,false,true alertingDisableSendAlertsExternal,experimental,@grafana/alerting-squad,false,false,false preserveDashboardStateWhenNavigating,experimental,@grafana/dashboards-squad,false,false,false alertingCentralAlertHistory,experimental,@grafana/alerting-squad,false,false,false @@ -268,6 +268,7 @@ jaegerEnableGrpcEndpoint,experimental,@grafana/oss-big-tent,false,false,false pluginStoreServiceLoading,experimental,@grafana/plugins-platform-backend,false,false,false newPanelPadding,preview,@grafana/dashboards-squad,false,false,true onlyStoreActionSets,GA,@grafana/identity-access-team,false,false,false +pluginInsights,experimental,@grafana/plugins-platform-backend,false,false,true panelTimeSettings,experimental,@grafana/dashboards-squad,false,false,false elasticsearchRawDSLQuery,experimental,@grafana/partner-datasources,false,false,false kubernetesAnnotations,experimental,@grafana/grafana-backend-services-squad,false,false,false diff --git a/pkg/services/featuremgmt/toggles_gen.go b/pkg/services/featuremgmt/toggles_gen.go index fd77326e8b0..2797b046d57 100644 --- a/pkg/services/featuremgmt/toggles_gen.go +++ b/pkg/services/featuremgmt/toggles_gen.go @@ -79,10 +79,6 @@ const ( // Disables dataplane specific processing in server side expressions. FlagDisableSSEDataplane = "disableSSEDataplane" - // FlagUnifiedRequestLog - // Writes error logs to the request logger - FlagUnifiedRequestLog = "unifiedRequestLog" - // FlagRenderAuthJWT // Uses JWT-based auth for rendering instead of relying on remote cache FlagRenderAuthJWT = "renderAuthJWT" diff --git a/pkg/services/featuremgmt/toggles_gen.json b/pkg/services/featuremgmt/toggles_gen.json index a0afcd87626..42922ecf82d 100644 --- a/pkg/services/featuremgmt/toggles_gen.json +++ b/pkg/services/featuremgmt/toggles_gen.json @@ -498,6 +498,19 @@ "codeowner": "@grafana/alerting-squad" } }, + { + "metadata": { + "name": "alertingSavedSearches", + "resourceVersion": "1765453147546", + "creationTimestamp": "2025-12-11T11:39:07Z" + }, + "spec": { + "description": "Enables saved searches for alert rules list", + "stage": "experimental", + "codeowner": "@grafana/alerting-squad", + "frontend": true + } + }, { "metadata": { "name": "alertingTriage", @@ -2720,6 +2733,20 @@ "expression": "false" } }, + { + "metadata": { + "name": "pluginInsights", + "resourceVersion": "1761300628147", + "creationTimestamp": "2025-10-24T10:10:28Z" + }, + "spec": { + "description": "Show insights for plugins in the plugin details page", + "stage": "experimental", + "codeowner": "@grafana/plugins-platform-backend", + "frontend": true, + "expression": "false" + } + }, { "metadata": { "name": "pluginInstallAPISync", @@ -3515,7 +3542,8 @@ "metadata": { "name": "unifiedRequestLog", "resourceVersion": "1764664939750", - "creationTimestamp": "2023-03-31T13:38:09Z" + "creationTimestamp": "2023-03-31T13:38:09Z", + "deletionTimestamp": "2025-12-18T14:21:02Z" }, "spec": { "description": "Writes error logs to the request logger", diff --git a/pkg/services/folder/folderimpl/folder_unifiedstorage.go b/pkg/services/folder/folderimpl/folder_unifiedstorage.go index 9b238b769fe..69b8cb59311 100644 --- a/pkg/services/folder/folderimpl/folder_unifiedstorage.go +++ b/pkg/services/folder/folderimpl/folder_unifiedstorage.go @@ -726,19 +726,6 @@ func (s *Service) moveOnApiServer(ctx context.Context, cmd *folder.MoveFolderCom return nil, folder.ErrBadRequest.Errorf("k6 project may not be moved") } - f, err := s.unifiedStore.Get(ctx, folder.GetFolderQuery{ - UID: &cmd.UID, - OrgID: cmd.OrgID, - SignedInUser: cmd.SignedInUser, - }) - if err != nil { - return nil, err - } - - if f != nil && f.ParentUID == accesscontrol.K6FolderUID { - return nil, folder.ErrBadRequest.Errorf("k6 project may not be moved") - } - // Check that the user is allowed to move the folder to the destination folder hasAccess, evalErr := s.canMoveViaApiServer(ctx, cmd) if evalErr != nil { @@ -748,30 +735,7 @@ func (s *Service) moveOnApiServer(ctx context.Context, cmd *folder.MoveFolderCom return nil, dashboards.ErrFolderAccessDenied } - // here we get the folder, we need to get the height of current folder - // and the depth of the new parent folder, the sum can't bypass 8 - folderHeight, err := s.unifiedStore.GetHeight(ctx, cmd.UID, cmd.OrgID, &cmd.NewParentUID) - if err != nil { - return nil, err - } - parents, err := s.unifiedStore.GetParents(ctx, folder.GetParentsQuery{UID: cmd.NewParentUID, OrgID: cmd.OrgID}) - if err != nil { - return nil, err - } - - // height of the folder that is being moved + this current folder itself + depth of the NewParent folder should be less than or equal MaxNestedFolderDepth - if folderHeight+len(parents)+1 > folder.MaxNestedFolderDepth { - return nil, folder.ErrMaximumDepthReached.Errorf("failed to move folder") - } - - for _, parent := range parents { - // if the current folder is already a parent of newparent, we should return error - if parent.UID == cmd.UID { - return nil, folder.ErrCircularReference.Errorf("failed to move folder") - } - } - - f, err = s.unifiedStore.Update(ctx, folder.UpdateFolderCommand{ + f, err := s.unifiedStore.Update(ctx, folder.UpdateFolderCommand{ UID: cmd.UID, OrgID: cmd.OrgID, NewParentUID: &cmd.NewParentUID, diff --git a/pkg/services/ngalert/api/api_prometheus_test.go b/pkg/services/ngalert/api/api_prometheus_test.go index 71e25d4c963..75ec6c901fd 100644 --- a/pkg/services/ngalert/api/api_prometheus_test.go +++ b/pkg/services/ngalert/api/api_prometheus_test.go @@ -2169,6 +2169,57 @@ func TestRouteGetRuleStatuses(t *testing.T) { }) }) + t.Run("compact mode with receiver_name filter returns only matching rules", func(t *testing.T) { + fakeStore, _, api := setupAPI(t) + + ruleA := gen.With( + gen.WithGroupKey(ngmodels.AlertRuleGroupKey{ + NamespaceUID: "folder-1", + RuleGroup: "group-1", + OrgID: orgID, + }), + gen.WithNotificationSettings( + ngmodels.NotificationSettings{ + Receiver: "receiver-a", + GroupBy: []string{"alertname"}, + }, + ), + ).GenerateRef() + fakeStore.PutRule(context.Background(), ruleA) + + ruleB := gen.With( + gen.WithGroupKey(ngmodels.AlertRuleGroupKey{ + NamespaceUID: "folder-2", + RuleGroup: "group-2", + OrgID: orgID, + }), + gen.WithNotificationSettings( + ngmodels.NotificationSettings{ + Receiver: "receiver-b", + GroupBy: []string{"alertname"}, + }, + ), + ).GenerateRef() + fakeStore.PutRule(context.Background(), ruleB) + r, err := http.NewRequest("GET", "/api/v1/rules?compact=true&receiver_name=receiver-a", nil) + require.NoError(t, err) + c := &contextmodel.ReqContext{ + Context: &web.Context{Req: r}, + SignedInUser: &user.SignedInUser{ + OrgID: orgID, + Permissions: queryPermissions, + }, + } + resp := api.RouteGetRuleStatuses(c) + require.Equal(t, http.StatusOK, resp.Status()) + var res apimodels.RuleResponse + require.NoError(t, json.Unmarshal(resp.Body(), &res)) + + require.Len(t, res.Data.RuleGroups, 1) + require.Equal(t, "group-1", res.Data.RuleGroups[0].Name) + require.Empty(t, res.Data.RuleGroups[0].Rules[0].Query, "Query should be empty in compact mode") + }) + t.Run("provenance as expected", func(t *testing.T) { fakeStore, fakeAIM, api, provStore := setupAPIFull(t) // Rule without provenance diff --git a/pkg/services/ngalert/store/alert_rule.go b/pkg/services/ngalert/store/alert_rule.go index 5957e7026b2..30856587794 100644 --- a/pkg/services/ngalert/store/alert_rule.go +++ b/pkg/services/ngalert/store/alert_rule.go @@ -642,6 +642,23 @@ func (st DBstore) ListAlertRulesByGroup(ctx context.Context, query *ngmodels.Lis _ = rows.Close() }() + opts := AlertRuleConvertOptions{} + if query.Compact { + opts.ExcludeAlertQueries = true + opts.ExcludeNotificationSettings = true + opts.ExcludeMetadata = true + + if query.ReceiverName != "" || query.TimeIntervalName != "" { + // Need NotificationSettings for these filters + opts.ExcludeNotificationSettings = false + } + + if query.HasPrometheusRuleDefinition != nil { + // Need Metadata for this filter + opts.ExcludeMetadata = false + } + } + // Process rules and implement per-group pagination var groupsFetched int64 var rulesFetched int64 @@ -653,12 +670,7 @@ func (st DBstore) ListAlertRulesByGroup(ctx context.Context, query *ngmodels.Lis continue } - var converted ngmodels.AlertRule - if query.Compact { - converted, err = alertRuleToModelsAlertRuleCompact(*rule, st.Logger) - } else { - converted, err = alertRuleToModelsAlertRule(*rule, st.Logger) - } + converted, err := convertAlertRuleToModel(*rule, st.Logger, opts) if err != nil { st.Logger.Error("Invalid rule found in DB store, cannot convert, ignoring it", "func", "ListAlertRulesByGroup", "error", err) diff --git a/pkg/services/ngalert/store/compat.go b/pkg/services/ngalert/store/compat.go index fbb69addc72..57dcf411853 100644 --- a/pkg/services/ngalert/store/compat.go +++ b/pkg/services/ngalert/store/compat.go @@ -15,22 +15,23 @@ type compactQuery struct { DatasourceUID string `json:"datasourceUid"` } -func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, error) { - return convertAlertRuleToModel(ar, l, false) +// AlertRuleConvertOptions controls which fields to parse during conversion from alertRule to models.AlertRule. +// By default all fields are included. Set Exclude* to true to skip parsing expensive fields. +type AlertRuleConvertOptions struct { + ExcludeAlertQueries bool // Only parse datasource UIDs from queries + ExcludeNotificationSettings bool + ExcludeMetadata bool } -// alertRuleToModelsAlertRuleCompact transforms an alertRule to a models.AlertRule -// ignoring alert queries (except for data source UIDs), notification settings, and metadata. -func alertRuleToModelsAlertRuleCompact(ar alertRule, l log.Logger) (models.AlertRule, error) { - return convertAlertRuleToModel(ar, l, true) +func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, error) { + return convertAlertRuleToModel(ar, l, AlertRuleConvertOptions{}) } // convertAlertRuleToModel creates a models.AlertRule from an alertRule. -// When 'compact' is set to 'true', it skips parsing the alert queries (except for the data source UID), notification -// settings, and metadata, thus reducing the number of JSON serializations needed. -func convertAlertRuleToModel(ar alertRule, l log.Logger, compact bool) (models.AlertRule, error) { +// opts.Exclude* fields control which expensive fields to skip parsing, reducing JSON serializations. +func convertAlertRuleToModel(ar alertRule, l log.Logger, opts AlertRuleConvertOptions) (models.AlertRule, error) { var data []models.AlertQuery - if compact { + if opts.ExcludeAlertQueries { var cqs []compactQuery if err := json.Unmarshal([]byte(ar.Data), &cqs); err != nil { return models.AlertRule{}, fmt.Errorf("failed to parse data: %w", err) @@ -118,7 +119,7 @@ func convertAlertRuleToModel(ar alertRule, l log.Logger, compact bool) (models.A } } - if !compact && ar.NotificationSettings != "" { + if !opts.ExcludeNotificationSettings && ar.NotificationSettings != "" { ns, err := parseNotificationSettings(ar.NotificationSettings) if err != nil { return models.AlertRule{}, fmt.Errorf("failed to parse notification settings: %w", err) @@ -126,7 +127,7 @@ func convertAlertRuleToModel(ar alertRule, l log.Logger, compact bool) (models.A result.NotificationSettings = ns } - if !compact && ar.Metadata != "" { + if !opts.ExcludeMetadata && ar.Metadata != "" { err = json.Unmarshal([]byte(ar.Metadata), &result.Metadata) if err != nil { return models.AlertRule{}, fmt.Errorf("failed to metadata: %w", err) diff --git a/pkg/services/ngalert/store/compat_test.go b/pkg/services/ngalert/store/compat_test.go index ef80f51d668..d4aab40931f 100644 --- a/pkg/services/ngalert/store/compat_test.go +++ b/pkg/services/ngalert/store/compat_test.go @@ -84,7 +84,11 @@ func TestAlertRuleToModelsAlertRuleCompact(t *testing.T) { Metadata: `{"editor_settings":{"simplified_query_and_expressions_section":true}}`, } - compactResult, err := alertRuleToModelsAlertRuleCompact(rule, &logtest.Fake{}) + compactResult, err := convertAlertRuleToModel(rule, &logtest.Fake{}, AlertRuleConvertOptions{ + ExcludeAlertQueries: true, + ExcludeNotificationSettings: true, + ExcludeMetadata: true, + }) require.NoError(t, err) // Should have datasource UIDs. @@ -142,6 +146,82 @@ func TestAlertRuleToModelsAlertRuleCompact(t *testing.T) { // Should have metadata (metadata is parsed from JSON to struct). require.NotEqual(t, ngmodels.AlertRuleMetadata{}, fullResult.Metadata) }) + + t.Run("compact mode with notification settings included for filtering", func(t *testing.T) { + rule := alertRule{ + ID: 1, + OrgID: 1, + UID: "test-uid", + Title: "Test Rule", + Condition: "A", + Data: `[{"datasourceUid":"ds1","refId":"A","queryType":"test","model":{"expr":"up"}}]`, + IntervalSeconds: 60, + Version: 1, + NamespaceUID: "ns-uid", + RuleGroup: "test-group", + NoDataState: "NoData", + ExecErrState: "Error", + NotificationSettings: `[{"receiver":"test-receiver"}]`, + Metadata: `{"editor_settings":{"simplified_query_and_expressions_section":true}}`, + } + + result, err := convertAlertRuleToModel(rule, &logtest.Fake{}, AlertRuleConvertOptions{ + ExcludeAlertQueries: true, + ExcludeNotificationSettings: false, + ExcludeMetadata: true, + }) + require.NoError(t, err) + + // Should have compact query data (only datasource UIDs). + require.Len(t, result.Data, 1) + require.Equal(t, "ds1", result.Data[0].DatasourceUID) + require.Empty(t, result.Data[0].RefID) + + // Should have notification settings for filtering. + require.Len(t, result.NotificationSettings, 1) + require.Equal(t, "test-receiver", result.NotificationSettings[0].Receiver) + + // Should not have metadata. + require.Equal(t, ngmodels.AlertRuleMetadata{}, result.Metadata) + }) + + t.Run("compact mode with metadata included for filtering", func(t *testing.T) { + rule := alertRule{ + ID: 1, + OrgID: 1, + UID: "test-uid", + Title: "Test Rule", + Condition: "A", + Data: `[{"datasourceUid":"ds1","refId":"A","queryType":"test","model":{"expr":"up"}}]`, + IntervalSeconds: 60, + Version: 1, + NamespaceUID: "ns-uid", + RuleGroup: "test-group", + NoDataState: "NoData", + ExecErrState: "Error", + NotificationSettings: `[{"receiver":"test-receiver"}]`, + Metadata: `{"prometheus_style_rule":{"original_rule_definition":"alert: TestAlert\n expr: rate(metric[5m]) > 1"}}`, + } + + result, err := convertAlertRuleToModel(rule, &logtest.Fake{}, AlertRuleConvertOptions{ + ExcludeAlertQueries: true, + ExcludeNotificationSettings: true, + ExcludeMetadata: false, + }) + require.NoError(t, err) + + // Should have compact query data (only datasource UIDs). + require.Len(t, result.Data, 1) + require.Equal(t, "ds1", result.Data[0].DatasourceUID) + require.Empty(t, result.Data[0].RefID) + + // Should not have notification settings. + require.Empty(t, result.NotificationSettings) + + // Should have metadata for filtering. + require.NotEqual(t, ngmodels.AlertRuleMetadata{}, result.Metadata) + require.True(t, result.HasPrometheusRuleDefinition()) + }) } func TestAlertRuleVersionToAlertRule(t *testing.T) { diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go index 00bcdabd88d..995a01ad825 100644 --- a/pkg/setting/setting.go +++ b/pkg/setting/setting.go @@ -2167,7 +2167,7 @@ func (cfg *Cfg) readProvisioningSettings(iniFile *ini.File) error { } cfg.ProvisioningAllowedTargets = iniFile.Section("provisioning").Key("allowed_targets").Strings("|") if len(cfg.ProvisioningAllowedTargets) == 0 { - cfg.ProvisioningAllowedTargets = []string{"instance", "folder"} + cfg.ProvisioningAllowedTargets = []string{"folder"} } cfg.ProvisioningAllowImageRendering = iniFile.Section("provisioning").Key("allow_image_rendering").MustBool(true) cfg.ProvisioningMinSyncInterval = iniFile.Section("provisioning").Key("min_sync_interval").MustDuration(10 * time.Second) diff --git a/pkg/storage/unified/resource/data/sqlkv_batch_delete.sql b/pkg/storage/unified/resource/data/sqlkv_batch_delete.sql new file mode 100644 index 00000000000..c165007d23d --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_batch_delete.sql @@ -0,0 +1,7 @@ +DELETE +FROM {{ .TableName }} +WHERE {{ .Ident "key_path" }} IN ( + {{ range $id, $key_path := .KeyPaths }} + {{ if ne $id 0 }}, {{ end }}{{ $.Arg $key_path }} + {{ end }} +); diff --git a/pkg/storage/unified/resource/data/sqlkv_delete_legacy_resource.sql b/pkg/storage/unified/resource/data/sqlkv_delete_legacy_resource.sql new file mode 100644 index 00000000000..e27ee578a41 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_delete_legacy_resource.sql @@ -0,0 +1,5 @@ +DELETE FROM {{ .Ident "resource" }} +WHERE {{ .Ident "group" }} = {{ .Arg .Group }} +AND {{ .Ident "resource" }} = {{ .Arg .Resource }} +AND {{ .Ident "namespace" }} = {{ .Arg .Namespace }} +AND {{ .Ident "name" }} = {{ .Arg .Name }}; diff --git a/pkg/storage/unified/resource/data/sqlkv_insert_datastore.sql b/pkg/storage/unified/resource/data/sqlkv_insert_datastore.sql new file mode 100644 index 00000000000..8372eb73463 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_insert_datastore.sql @@ -0,0 +1,21 @@ +INSERT INTO {{ .Ident .TableName }} +( + {{ .Ident "guid" }}, + {{ .Ident "key_path" }}, + {{ .Ident "value" }}, + {{ .Ident "group" }}, + {{ .Ident "resource" }}, + {{ .Ident "namespace" }}, + {{ .Ident "name" }}, + {{ .Ident "action" }} +) +VALUES ( + {{ .Arg .GUID }}, + {{ .Arg .KeyPath }}, + COALESCE({{ .Arg .Value }}, ""), + {{ .Arg .Group }}, + {{ .Arg .Resource }}, + {{ .Arg .Namespace }}, + {{ .Arg .Name }}, + {{ .Arg .Action }} +); diff --git a/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource.sql b/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource.sql new file mode 100644 index 00000000000..1f58bd28b43 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource.sql @@ -0,0 +1,31 @@ +INSERT INTO {{ .Ident "resource" }} +( + {{ .Ident "value" }}, + {{ .Ident "guid" }}, + {{ .Ident "group" }}, + {{ .Ident "resource" }}, + {{ .Ident "namespace" }}, + {{ .Ident "name" }}, + {{ .Ident "action" }}, + {{ .Ident "folder" }}, + {{ .Ident "previous_resource_version" }} +) +VALUES ( + COALESCE({{ .Arg .Value }}, ""), + {{ .Arg .GUID }}, + {{ .Arg .Group }}, + {{ .Arg .Resource }}, + {{ .Arg .Namespace }}, + {{ .Arg .Name }}, + {{ .Arg .Action }}, + {{ .Arg .Folder }}, + CASE WHEN {{ .Arg .Action }} = 1 THEN 0 ELSE ( + SELECT {{ .Ident "resource_version" }} + FROM {{ .Ident "resource" }} + WHERE {{ .Ident "group" }} = {{ .Arg .Group }} + AND {{ .Ident "resource" }} = {{ .Arg .Resource }} + AND {{ .Ident "namespace" }} = {{ .Arg .Namespace }} + AND {{ .Ident "name" }} = {{ .Arg .Name }} + ORDER BY {{ .Ident "resource_version" }} DESC LIMIT 1 + ) END +); diff --git a/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource_history.sql b/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource_history.sql new file mode 100644 index 00000000000..d52aac5063d --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_insert_legacy_resource_history.sql @@ -0,0 +1,44 @@ +INSERT INTO {{ .Ident "resource_history" }} +( + {{ .Ident "value" }}, + {{ .Ident "guid" }}, + {{ .Ident "group" }}, + {{ .Ident "resource" }}, + {{ .Ident "namespace" }}, + {{ .Ident "name" }}, + {{ .Ident "action" }}, + {{ .Ident "folder" }}, + {{ .Ident "previous_resource_version" }}, + {{ .Ident "generation" }} +) +VALUES ( + COALESCE({{ .Arg .Value }}, ""), + {{ .Arg .GUID }}, + {{ .Arg .Group }}, + {{ .Arg .Resource }}, + {{ .Arg .Namespace }}, + {{ .Arg .Name }}, + {{ .Arg .Action }}, + {{ .Arg .Folder }}, + CASE WHEN {{ .Arg .Action }} = 1 THEN 0 ELSE ( + SELECT {{ .Ident "resource_version" }} + FROM {{ .Ident "resource_history" }} + WHERE {{ .Ident "group" }} = {{ .Arg .Group }} + AND {{ .Ident "resource" }} = {{ .Arg .Resource }} + AND {{ .Ident "namespace" }} = {{ .Arg .Namespace }} + AND {{ .Ident "name" }} = {{ .Arg .Name }} + ORDER BY {{ .Ident "resource_version" }} DESC LIMIT 1 + ) END, + CASE + WHEN {{ .Arg .Action }} = 1 THEN 1 + WHEN {{ .Arg .Action }} = 3 THEN 0 + ELSE 1 + ( + SELECT COUNT(1) + FROM {{ .Ident "resource_history" }} + WHERE {{ .Ident "group" }} = {{ .Arg .Group }} + AND {{ .Ident "resource" }} = {{ .Arg .Resource }} + AND {{ .Ident "namespace" }} = {{ .Arg .Namespace }} + AND {{ .Ident "name" }} = {{ .Arg .Name }} + ) + END +); diff --git a/pkg/storage/unified/resource/data/sqlkv_save_event.sql b/pkg/storage/unified/resource/data/sqlkv_save_event.sql new file mode 100644 index 00000000000..669497dbb19 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_save_event.sql @@ -0,0 +1,15 @@ +INSERT INTO {{ .Ident .TableName }} +( + {{ .Ident "key_path" }}, + {{ .Ident "value" }} +) +VALUES ( + {{ .Arg .KeyPath }}, + COALESCE({{ .Arg .Value }}, "") +) +{{- if eq .DialectName "mysql" }} +ON DUPLICATE KEY UPDATE {{ .Ident "value" }} = {{ .Arg .Value }} +{{- else }} +ON CONFLICT ({{ .Ident "key_path" }}) DO UPDATE SET {{ .Ident "value" }} = {{ .Arg .Value }} +{{- end }} +; diff --git a/pkg/storage/unified/resource/data/sqlkv_update_datastore.sql b/pkg/storage/unified/resource/data/sqlkv_update_datastore.sql new file mode 100644 index 00000000000..677666e00a4 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_update_datastore.sql @@ -0,0 +1,3 @@ +UPDATE {{ .Ident .TableName }} +SET {{ .Ident "value" }} = {{ .Arg .Value }} +WHERE {{ .Ident "key_path" }} = {{ .Arg .KeyPath }}; diff --git a/pkg/storage/unified/resource/data/sqlkv_update_legacy_resource.sql b/pkg/storage/unified/resource/data/sqlkv_update_legacy_resource.sql new file mode 100644 index 00000000000..1565d0894a4 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_update_legacy_resource.sql @@ -0,0 +1,9 @@ +UPDATE {{ .Ident "resource" }} +SET + {{ .Ident "value" }} = {{ .Arg .Value }}, + {{ .Ident "action" }} = {{ .Arg .Action }}, + {{ .Ident "folder" }} = {{ .Arg .Folder }} +WHERE {{ .Ident "group" }} = {{ .Arg .Group }} +AND {{ .Ident "resource" }} = {{ .Arg .Resource }} +AND {{ .Ident "namespace" }} = {{ .Arg .Namespace }} +AND {{ .Ident "name" }} = {{ .Arg .Name }}; diff --git a/pkg/storage/unified/resource/datastore.go b/pkg/storage/unified/resource/datastore.go index 8a930492420..7a1b614323e 100644 --- a/pkg/storage/unified/resource/datastore.go +++ b/pkg/storage/unified/resource/datastore.go @@ -49,6 +49,9 @@ type DataKey struct { ResourceVersion int64 Action DataAction Folder string + + // needed to maintain backwards compatibility with unified/sql + GUID string } // GroupResource represents a unique group/resource combination @@ -61,6 +64,12 @@ func (k DataKey) String() string { return fmt.Sprintf("%s/%s/%s/%s/%d~%s~%s", k.Group, k.Resource, k.Namespace, k.Name, k.ResourceVersion, k.Action, k.Folder) } +// Temporary while we need to support unified/sql/backend compatibility +// Remove once we stop using RvManager in storage_backend.go +func (k DataKey) StringWithGUID() string { + return fmt.Sprintf("%s/%s/%s/%s/%d~%s~%s~%s", k.Group, k.Resource, k.Namespace, k.Name, k.ResourceVersion, k.Action, k.Folder, k.GUID) +} + func (k DataKey) Equals(other DataKey) bool { return k.Group == other.Group && k.Resource == other.Resource && k.Namespace == other.Namespace && k.Name == other.Name && k.ResourceVersion == other.ResourceVersion && k.Action == other.Action && k.Folder == other.Folder } @@ -516,7 +525,13 @@ func (d *dataStore) Save(ctx context.Context, key DataKey, value io.Reader) erro return fmt.Errorf("invalid data key: %w", err) } - writer, err := d.kv.Save(ctx, dataSection, key.String()) + var writer io.WriteCloser + var err error + if key.GUID != "" { + writer, err = d.kv.Save(ctx, dataSection, key.StringWithGUID()) + } else { + writer, err = d.kv.Save(ctx, dataSection, key.String()) + } if err != nil { return err } @@ -583,6 +598,33 @@ func ParseKey(key string) (DataKey, error) { }, nil } +// Temporary while we need to support unified/sql/backend compatibility +// Remove once we stop using RvManager in storage_backend.go +func ParseKeyWithGUID(key string) (DataKey, error) { + parts := strings.Split(key, "/") + if len(parts) != 5 { + return DataKey{}, fmt.Errorf("invalid key: %s", key) + } + rvActionFolderGUIDParts := strings.Split(parts[4], "~") + if len(rvActionFolderGUIDParts) != 4 { + return DataKey{}, fmt.Errorf("invalid key: %s", key) + } + rv, err := strconv.ParseInt(rvActionFolderGUIDParts[0], 10, 64) + if err != nil { + return DataKey{}, fmt.Errorf("invalid resource version '%s' in key %s: %w", rvActionFolderGUIDParts[0], key, err) + } + return DataKey{ + Group: parts[0], + Resource: parts[1], + Namespace: parts[2], + Name: parts[3], + ResourceVersion: rv, + Action: DataAction(rvActionFolderGUIDParts[1]), + Folder: rvActionFolderGUIDParts[2], + GUID: rvActionFolderGUIDParts[3], + }, nil +} + // SameResource checks if this key represents the same resource as another key. // It compares the identifying fields: Group, Resource, Namespace, and Name. // ResourceVersion, Action, and Folder are ignored as they don't identify the resource itself. diff --git a/pkg/storage/unified/resource/eventstore.go b/pkg/storage/unified/resource/eventstore.go index 7f80fb6b87a..e0c01afb550 100644 --- a/pkg/storage/unified/resource/eventstore.go +++ b/pkg/storage/unified/resource/eventstore.go @@ -32,6 +32,7 @@ type EventKey struct { ResourceVersion int64 Action DataAction Folder string + GUID string } func (k EventKey) String() string { diff --git a/pkg/storage/unified/resource/sqlkv.go b/pkg/storage/unified/resource/sqlkv.go index 22cd3085122..6d406294a96 100644 --- a/pkg/storage/unified/resource/sqlkv.go +++ b/pkg/storage/unified/resource/sqlkv.go @@ -11,9 +11,12 @@ import ( "iter" "strings" "text/template" + "time" + "github.com/google/uuid" "github.com/grafana/grafana/pkg/storage/unified/sql/db" "github.com/grafana/grafana/pkg/storage/unified/sql/dbutil" + "github.com/grafana/grafana/pkg/storage/unified/sql/rvmanager" "github.com/grafana/grafana/pkg/storage/unified/sql/sqltemplate" ) @@ -34,10 +37,18 @@ func mustTemplate(filename string) *template.Template { // Templates. var ( - sqlKVKeys = mustTemplate("sqlkv_keys.sql") - sqlKVGet = mustTemplate("sqlkv_get.sql") - sqlKVBatchGet = mustTemplate("sqlkv_batch_get.sql") - sqlKVDelete = mustTemplate("sqlkv_delete.sql") + sqlKVKeys = mustTemplate("sqlkv_keys.sql") + sqlKVGet = mustTemplate("sqlkv_get.sql") + sqlKVBatchGet = mustTemplate("sqlkv_batch_get.sql") + sqlKVSaveEvent = mustTemplate("sqlkv_save_event.sql") + sqlKVInsertData = mustTemplate("sqlkv_insert_datastore.sql") + sqlKVUpdateData = mustTemplate("sqlkv_update_datastore.sql") + sqlKVInsertLegacyResourceHistory = mustTemplate("sqlkv_insert_legacy_resource_history.sql") + sqlKVInsertLegacyResource = mustTemplate("sqlkv_insert_legacy_resource.sql") + sqlKVUpdateLegacyResource = mustTemplate("sqlkv_update_legacy_resource.sql") + sqlKVDeleteLegacyResource = mustTemplate("sqlkv_delete_legacy_resource.sql") + sqlKVDelete = mustTemplate("sqlkv_delete.sql") + sqlKVBatchDelete = mustTemplate("sqlkv_batch_delete.sql") ) // sqlKVSection can be embedded in structs used when rendering query templates @@ -108,17 +119,17 @@ func (req sqlKVGetRequest) Results() ([]byte, error) { return req.Value, nil } -type sqlKVBatchGetRequest struct { +type sqlKVBatchRequest struct { sqltemplate.SQLTemplate sqlKVSection Keys []string } -func (req sqlKVBatchGetRequest) Validate() error { +func (req sqlKVBatchRequest) Validate() error { return req.sqlKVSection.Validate() } -func (req sqlKVBatchGetRequest) KeyPaths() []string { +func (req sqlKVBatchRequest) KeyPaths() []string { result := make([]string, 0, len(req.Keys)) for _, key := range req.Keys { result = append(result, req.Section+"/"+key) @@ -127,6 +138,45 @@ func (req sqlKVBatchGetRequest) KeyPaths() []string { return result } +type sqlKVSaveRequest struct { + sqltemplate.SQLTemplate + sqlKVSectionKey + Value []byte + + // old fields that can be removed once we prune resource_history + GUID string + Group string + Resource string + Namespace string + Name string + Action int64 + Folder string +} + +func (req sqlKVSaveRequest) Validate() error { + return req.sqlKVSectionKey.Validate() +} + +type sqlKVLegacySaveRequest struct { + sqltemplate.SQLTemplate + Value []byte + GUID string + Group string + Resource string + Namespace string + Name string + Action int64 + Folder string +} + +func (req sqlKVLegacySaveRequest) Validate() error { + return nil +} + +func (req sqlKVLegacySaveRequest) Results() ([]byte, error) { + return req.Value, nil +} + type sqlKVKeysRequest struct { sqltemplate.SQLTemplate sqlKVSection @@ -250,7 +300,7 @@ func (k *sqlKV) BatchGet(ctx context.Context, section string, keys []string) ite return } - rows, err := dbutil.QueryRows(ctx, k.db, sqlKVBatchGet, sqlKVBatchGetRequest{ + rows, err := dbutil.QueryRows(ctx, k.db, sqlKVBatchGet, sqlKVBatchRequest{ SQLTemplate: sqltemplate.New(k.dialect), sqlKVSection: sqlKVSection{section}, Keys: keys, @@ -284,20 +334,187 @@ func (k *sqlKV) BatchGet(ctx context.Context, section string, keys []string) ite } } -// TODO: this function only exists to support the testing of the sqlkv implementation before -// we have a proper implementation of `Save`. -func (k *sqlKV) TestingSave(ctx context.Context, key string, value []byte) error { - stmt := fmt.Sprintf( - `INSERT INTO resource_events (key_path, value) VALUES (%s, %s)`, - k.dialect.ArgPlaceholder(1), k.dialect.ArgPlaceholder(2), - ) +func (k *sqlKV) Save(ctx context.Context, section string, key string) (io.WriteCloser, error) { + sectionKey := sqlKVSectionKey{sqlKVSection{section}, key} + if err := sectionKey.Validate(); err != nil { + return nil, err + } - _, err := k.db.ExecContext(ctx, stmt, eventsSection+"/"+key, value) - return err + return &sqlWriteCloser{ + kv: k, + ctx: ctx, + sectionKey: sectionKey, + buf: &bytes.Buffer{}, + closed: false, + }, nil } -func (k *sqlKV) Save(ctx context.Context, section string, key string) (io.WriteCloser, error) { - panic("not implemented!") +type sqlWriteCloser struct { + kv *sqlKV + ctx context.Context + sectionKey sqlKVSectionKey + buf *bytes.Buffer + closed bool +} + +func (w *sqlWriteCloser) Write(value []byte) (int, error) { + if w.closed { + return 0, errors.New("write to closed writer") + } + + return w.buf.Write(value) +} + +func (w *sqlWriteCloser) Close() error { + if w.closed { + return nil + } + + w.closed = true + + // do regular kv save: simple key_path + value insert with conflict check. + // can only do this on resource_events for now, until we drop the columns in resource_history + if w.sectionKey.Section == eventsSection { + _, err := dbutil.Exec(w.ctx, w.kv.db, sqlKVSaveEvent, sqlKVSaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + sqlKVSectionKey: w.sectionKey, + Value: w.buf.Bytes(), + }) + + if err != nil { + return fmt.Errorf("failed to save: %w", err) + } + + return nil + } + + // if storage_backend is running with an RvManager, it will inject a transaction into the context + // used to keep backwards compatibility between sql-based kvstore and unified/sql/backend + tx, ok := rvmanager.TxFromCtx(w.ctx) + if !ok { + // temporary save for dataStore without rvmanager + // we can use the same template as the event one after we: + // - move PK from GUID to key_path + // - remove all unnecessary columns (or at least their NOT NULL constraints) + _, err := w.kv.Get(w.ctx, w.sectionKey.Section, w.sectionKey.Key) + if errors.Is(err, ErrNotFound) { + _, err := dbutil.Exec(w.ctx, w.kv.db, sqlKVInsertData, sqlKVSaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + sqlKVSectionKey: w.sectionKey, + GUID: uuid.New().String(), + Value: w.buf.Bytes(), + }) + + if err != nil { + return fmt.Errorf("failed to insert to datastore: %w", err) + } + + return nil + } + + if err != nil { + return fmt.Errorf("failed to get for save: %w", err) + } + + _, err = dbutil.Exec(w.ctx, w.kv.db, sqlKVUpdateData, sqlKVSaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + sqlKVSectionKey: w.sectionKey, + Value: w.buf.Bytes(), + }) + + if err != nil { + return fmt.Errorf("failed to update to datastore: %w", err) + } + + return nil + } + + // special, temporary save that includes all the fields in resource_history that are not relevant for the kvstore, + // as well as the resource table. This is only called if an RvManager was passed to storage_backend, as that + // component will be responsible for populating the resource_version and key_path columns + // note that we are not touching resource_version table, neither the resource_version columns or the key_path column + // as the RvManager will be responsible for this + dataKey, err := ParseKeyWithGUID(w.sectionKey.Key) + if err != nil { + return fmt.Errorf("failed to parse key: %w", err) + } + + var action int64 + switch dataKey.Action { + case DataActionCreated: + action = 1 + case DataActionUpdated: + action = 2 + case DataActionDeleted: + action = 3 + default: + return fmt.Errorf("failed to parse key: %w", err) + } + + _, err = dbutil.Exec(w.ctx, tx, sqlKVInsertLegacyResourceHistory, sqlKVSaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + sqlKVSectionKey: w.sectionKey, + Value: w.buf.Bytes(), + GUID: dataKey.GUID, + Group: dataKey.Group, + Resource: dataKey.Resource, + Namespace: dataKey.Namespace, + Name: dataKey.Name, + Action: action, + Folder: dataKey.Folder, + }) + + if err != nil { + return fmt.Errorf("failed to save to resource_history: %w", err) + } + + switch dataKey.Action { + case DataActionCreated: + _, err = dbutil.Exec(w.ctx, tx, sqlKVInsertLegacyResource, sqlKVLegacySaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + Value: w.buf.Bytes(), + GUID: dataKey.GUID, + Group: dataKey.Group, + Resource: dataKey.Resource, + Namespace: dataKey.Namespace, + Name: dataKey.Name, + Action: action, + Folder: dataKey.Folder, + }) + + if err != nil { + return fmt.Errorf("failed to insert to resource: %w", err) + } + case DataActionUpdated: + _, err = dbutil.Exec(w.ctx, tx, sqlKVUpdateLegacyResource, sqlKVLegacySaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + Value: w.buf.Bytes(), + Group: dataKey.Group, + Resource: dataKey.Resource, + Namespace: dataKey.Namespace, + Name: dataKey.Name, + Action: action, + Folder: dataKey.Folder, + }) + + if err != nil { + return fmt.Errorf("failed to update resource: %w", err) + } + case DataActionDeleted: + _, err = dbutil.Exec(w.ctx, tx, sqlKVDeleteLegacyResource, sqlKVLegacySaveRequest{ + SQLTemplate: sqltemplate.New(w.kv.dialect), + Group: dataKey.Group, + Resource: dataKey.Resource, + Namespace: dataKey.Namespace, + Name: dataKey.Name, + }) + + if err != nil { + return fmt.Errorf("failed to delete from resource: %w", err) + } + } + + return nil } func (k *sqlKV) Delete(ctx context.Context, section string, key string) error { @@ -318,15 +535,29 @@ func (k *sqlKV) Delete(ctx context.Context, section string, key string) error { return ErrNotFound } + // TODO reflect change to resource table + return nil } func (k *sqlKV) BatchDelete(ctx context.Context, section string, keys []string) error { - panic("not implemented!") + if len(keys) == 0 { + return nil + } + + if _, err := dbutil.Exec(ctx, k.db, sqlKVBatchDelete, sqlKVBatchRequest{ + SQLTemplate: sqltemplate.New(k.dialect), + sqlKVSection: sqlKVSection{section}, + Keys: keys, + }); err != nil { + return fmt.Errorf("failed to batch delete keys: %w", err) + } + + return nil } func (k *sqlKV) UnixTimestamp(ctx context.Context) (int64, error) { - panic("not implemented!") + return time.Now().Unix(), nil } func closeRows[T any](rows db.Rows, yield func(T, error) bool) { diff --git a/pkg/storage/unified/resource/storage_backend.go b/pkg/storage/unified/resource/storage_backend.go index b0f51702775..13f2b9d6159 100644 --- a/pkg/storage/unified/resource/storage_backend.go +++ b/pkg/storage/unified/resource/storage_backend.go @@ -14,6 +14,7 @@ import ( "time" "github.com/bwmarrin/snowflake" + "github.com/google/uuid" "github.com/grafana/grafana-app-sdk/logging" "github.com/prometheus/client_golang/prometheus" "go.opentelemetry.io/otel/trace" @@ -22,6 +23,8 @@ import ( "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" + "github.com/grafana/grafana/pkg/storage/unified/sql/db" + "github.com/grafana/grafana/pkg/storage/unified/sql/rvmanager" "github.com/grafana/grafana/pkg/util/debouncer" ) @@ -68,6 +71,8 @@ type kvStorageBackend struct { withExperimentalClusterScope bool //tracer trace.Tracer //reg prometheus.Registerer + + rvManager *rvmanager.ResourceVersionManager } var _ KVBackend = &kvStorageBackend{} @@ -85,6 +90,10 @@ type KVBackendOptions struct { EventPruningInterval time.Duration // How often to run the event pruning (default: 5 minutes) Tracer trace.Tracer // TODO add tracing Reg prometheus.Registerer // TODO add metrics + + // Adding RvManager overrides the RV generated with snowflake in order to keep backwards compatibility with + // unified/sql + RvManager *rvmanager.ResourceVersionManager } func NewKVStorageBackend(opts KVBackendOptions) (KVBackend, error) { @@ -119,6 +128,7 @@ func NewKVStorageBackend(opts KVBackendOptions) (KVBackend, error) { eventRetentionPeriod: eventRetentionPeriod, eventPruningInterval: eventPruningInterval, withExperimentalClusterScope: opts.WithExperimentalClusterScope, + rvManager: opts.RvManager, } err = backend.initPruner(ctx) if err != nil { @@ -317,9 +327,28 @@ func (k *kvStorageBackend) WriteEvent(ctx context.Context, event WriteEvent) (in Action: action, Folder: obj.GetFolder(), } - err := k.dataStore.Save(ctx, dataKey, bytes.NewReader(event.Value)) - if err != nil { - return 0, fmt.Errorf("failed to write data: %w", err) + + if k.rvManager != nil { + dataKey.GUID = uuid.New().String() + var err error + rv, err = k.rvManager.ExecWithRV(ctx, event.Key, func(tx db.Tx) (string, error) { + err := k.dataStore.Save(rvmanager.ContextWithTx(ctx, tx), dataKey, bytes.NewReader(event.Value)) + if err != nil { + return "", fmt.Errorf("failed to write data: %w", err) + } + + return dataKey.GUID, nil + }) + if err != nil { + return 0, fmt.Errorf("failed to write data: %w", err) + } + + dataKey.ResourceVersion = rv + } else { + err := k.dataStore.Save(ctx, dataKey, bytes.NewReader(event.Value)) + if err != nil { + return 0, fmt.Errorf("failed to write data: %w", err) + } } // Optimistic concurrency control to verify our write is the latest version @@ -340,14 +369,22 @@ func (k *kvStorageBackend) WriteEvent(ctx context.Context, event WriteEvent) (in } // Check if the RV we just wrote is the latest. If not, a concurrent write with higher RV happened - if latestKey.ResourceVersion != rv { + if !rvmanager.IsRvEqual(latestKey.ResourceVersion, rv) { // Delete the data we just wrote since it's not the latest + // if we're running with rvManager, convert the ResourceVersion back to snowflake to delete + if k.rvManager != nil { + dataKey.ResourceVersion = rvmanager.SnowflakeFromRv(dataKey.ResourceVersion) + } _ = k.dataStore.Delete(ctx, dataKey) return 0, fmt.Errorf("optimistic locking failed: concurrent modification detected") } - if prevKey.ResourceVersion != event.PreviousRV { + if !rvmanager.IsRvEqual(prevKey.ResourceVersion, event.PreviousRV) { // Another concurrent write happened between our read and write + // if we're running with rvManager, convert the ResourceVersion back to snowflake to delete + if k.rvManager != nil { + dataKey.ResourceVersion = rvmanager.SnowflakeFromRv(dataKey.ResourceVersion) + } _ = k.dataStore.Delete(ctx, dataKey) return 0, fmt.Errorf("optimistic locking failed: resource was modified concurrently (expected previous RV %d, found %d)", event.PreviousRV, prevKey.ResourceVersion) } @@ -366,8 +403,12 @@ func (k *kvStorageBackend) WriteEvent(ctx context.Context, event WriteEvent) (in } // Check if the RV we just wrote is the latest. If not, a concurrent create with higher RV happened - if latestKey.ResourceVersion != rv { + if !rvmanager.IsRvEqual(latestKey.ResourceVersion, rv) { // Delete the data we just wrote since it's not the latest + // if we're running with rvManager, convert the ResourceVersion back to snowflake to delete + if k.rvManager != nil { + dataKey.ResourceVersion = rvmanager.SnowflakeFromRv(dataKey.ResourceVersion) + } _ = k.dataStore.Delete(ctx, dataKey) return 0, fmt.Errorf("optimistic locking failed: concurrent create detected") } @@ -375,6 +416,10 @@ func (k *kvStorageBackend) WriteEvent(ctx context.Context, event WriteEvent) (in // Verify that the immediate predecessor is not a create if prevKey.Action == DataActionCreated { // Another concurrent create happened - delete our write and return error + // if we're running with rvManager, convert the ResourceVersion back to snowflake to delete + if k.rvManager != nil { + dataKey.ResourceVersion = rvmanager.SnowflakeFromRv(dataKey.ResourceVersion) + } _ = k.dataStore.Delete(ctx, dataKey) return 0, fmt.Errorf("optimistic locking failed: concurrent create detected") } @@ -391,7 +436,7 @@ func (k *kvStorageBackend) WriteEvent(ctx context.Context, event WriteEvent) (in Folder: obj.GetFolder(), PreviousRV: event.PreviousRV, } - err = k.eventStore.Save(ctx, eventData) + err := k.eventStore.Save(ctx, eventData) if err != nil { // Clean up the data we wrote since event save failed _ = k.dataStore.Delete(ctx, dataKey) diff --git a/pkg/storage/unified/sql/rvmanager/rv_manager.go b/pkg/storage/unified/sql/rvmanager/rv_manager.go index b4f3b5de596..b10685f22ad 100644 --- a/pkg/storage/unified/sql/rvmanager/rv_manager.go +++ b/pkg/storage/unified/sql/rvmanager/rv_manager.go @@ -21,6 +21,19 @@ import ( "github.com/grafana/grafana/pkg/storage/unified/sql/sqltemplate" ) +type contextKey string + +const txKey contextKey = "rvmanager_db_tx" + +func ContextWithTx(ctx context.Context, tx db.Tx) context.Context { + return context.WithValue(ctx, txKey, tx) +} + +func TxFromCtx(ctx context.Context) (db.Tx, bool) { + tx, ok := ctx.Value(txKey).(db.Tx) + return tx, ok +} + var tracer = otel.Tracer("github.com/grafana/grafana/pkg/storage/unified/sql/rvmanager") var ( @@ -294,7 +307,7 @@ func (m *ResourceVersionManager) execBatch(ctx context.Context, group, resource // Allocate the RVs for i, guid := range guids { guidToRV[guid] = rv - guidToSnowflakeRV[guid] = snowflakeFromRv(rv) + guidToSnowflakeRV[guid] = SnowflakeFromRv(rv) rvs[i] = rv rv++ } @@ -353,10 +366,20 @@ func (m *ResourceVersionManager) execBatch(ctx context.Context, group, resource // takes a unix microsecond rv and transforms into a snowflake format. The timestamp is converted from microsecond to // millisecond (the integer division) and the remainder is saved in the stepbits section. machine id is always 0 -func snowflakeFromRv(rv int64) int64 { +func SnowflakeFromRv(rv int64) int64 { return (((rv / 1000) - snowflake.Epoch) << (snowflake.NodeBits + snowflake.StepBits)) + (rv % 1000) } +// helper utility to compare two RVs. The first RV must be in snowflake format. Will convert rv2 to snowflake and retry +// if comparison fails +func IsRvEqual(rv1, rv2 int64) bool { + if rv1 == rv2 { + return true + } + + return rv1 == SnowflakeFromRv(rv2) +} + // Lock locks the resource version for the given key func (m *ResourceVersionManager) Lock(ctx context.Context, x db.ContextExecer, group, resource string) (nextRV int64, err error) { // 1. Lock the row and prevent concurrent updates until the transaction is committed diff --git a/pkg/storage/unified/sql/server.go b/pkg/storage/unified/sql/server.go index 84eda71ca20..f4a1ee3ce77 100644 --- a/pkg/storage/unified/sql/server.go +++ b/pkg/storage/unified/sql/server.go @@ -20,6 +20,8 @@ import ( "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/storage/unified/resource" "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" + "github.com/grafana/grafana/pkg/storage/unified/sql/rvmanager" + "github.com/grafana/grafana/pkg/storage/unified/sql/sqltemplate" ) type QOSEnqueueDequeuer interface { @@ -103,11 +105,34 @@ func NewResourceServer(opts ServerOptions) (resource.ResourceServer, error) { return nil, fmt.Errorf("error creating sqlkv: %s", err) } - kvBackend, err := resource.NewKVStorageBackend(resource.KVBackendOptions{ + kvBackendOpts := resource.KVBackendOptions{ KvStore: sqlkv, Tracer: opts.Tracer, Reg: opts.Reg, + } + + ctx := context.Background() + dbConn, err := eDB.Init(ctx) + if err != nil { + return nil, fmt.Errorf("error initializing DB: %w", err) + } + + dialect := sqltemplate.DialectForDriver(dbConn.DriverName()) + if dialect == nil { + return nil, fmt.Errorf("unsupported database driver: %s", dbConn.DriverName()) + } + + rvManager, err := rvmanager.NewResourceVersionManager(rvmanager.ResourceManagerOptions{ + Dialect: dialect, + DB: dbConn, }) + if err != nil { + return nil, fmt.Errorf("failed to create resource version manager: %w", err) + } + + // TODO add config to decide whether to pass RvManager or not + kvBackendOpts.RvManager = rvManager + kvBackend, err := resource.NewKVStorageBackend(kvBackendOpts) if err != nil { return nil, fmt.Errorf("error creating kv backend: %s", err) } diff --git a/pkg/storage/unified/testing/kv.go b/pkg/storage/unified/testing/kv.go index fbd831f6281..2031a3e38b2 100644 --- a/pkg/storage/unified/testing/kv.go +++ b/pkg/storage/unified/testing/kv.go @@ -5,6 +5,8 @@ import ( "context" "fmt" "io" + "maps" + "slices" "strings" "testing" "time" @@ -146,14 +148,15 @@ func runTestKVGet(t *testing.T, kv resource.KV, nsPrefix string) { func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { ctx := testutil.NewTestContext(t, time.Now().Add(30*time.Second)) - section := nsPrefix + "-save" + nsPrefix += "-save" t.Run("save new key", func(t *testing.T) { + newKey := namespacedKey(nsPrefix, "new-key") testValue := "new test value" - saveKVHelper(t, kv, ctx, section, "new-key", strings.NewReader(testValue)) + saveKVHelper(t, kv, ctx, testSection, newKey, strings.NewReader(testValue)) // Verify it was saved - reader, err := kv.Get(ctx, section, "new-key") + reader, err := kv.Get(ctx, testSection, newKey) require.NoError(t, err) value, err := io.ReadAll(reader) @@ -164,15 +167,39 @@ func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { }) t.Run("save overwrite existing key", func(t *testing.T) { + overwriteKey := namespacedKey(nsPrefix, "overwrite-key") + // First save - saveKVHelper(t, kv, ctx, section, "overwrite-key", strings.NewReader("old value")) + saveKVHelper(t, kv, ctx, testSection, overwriteKey, strings.NewReader("old value")) // Overwrite newValue := "new value" - saveKVHelper(t, kv, ctx, section, "overwrite-key", strings.NewReader(newValue)) + saveKVHelper(t, kv, ctx, testSection, overwriteKey, strings.NewReader(newValue)) // Verify it was updated - reader, err := kv.Get(ctx, section, "overwrite-key") + reader, err := kv.Get(ctx, testSection, overwriteKey) + require.NoError(t, err) + + value, err := io.ReadAll(reader) + require.NoError(t, err) + assert.Equal(t, newValue, string(value)) + err = reader.Close() + require.NoError(t, err) + }) + + t.Run("save overwrite existing key (datastore)", func(t *testing.T) { + section := "unified/data" + overwriteKey := namespacedKey(nsPrefix, "overwrite-key") + + // First save + saveKVHelper(t, kv, ctx, section, overwriteKey, strings.NewReader("old value")) + + // Overwrite + newValue := "new value" + saveKVHelper(t, kv, ctx, section, overwriteKey, strings.NewReader(newValue)) + + // Verify it was updated + reader, err := kv.Get(ctx, section, overwriteKey) require.NoError(t, err) value, err := io.ReadAll(reader) @@ -189,11 +216,13 @@ func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { }) t.Run("save binary data", func(t *testing.T) { + binaryKey := namespacedKey(nsPrefix, "binary-key") + binaryData := []byte{0x00, 0x01, 0x02, 0x03, 0xFF, 0xFE, 0xFD} - saveKVHelper(t, kv, ctx, section, "binary-key", bytes.NewReader(binaryData)) + saveKVHelper(t, kv, ctx, testSection, binaryKey, bytes.NewReader(binaryData)) // Verify binary data - reader, err := kv.Get(ctx, section, "binary-key") + reader, err := kv.Get(ctx, testSection, binaryKey) require.NoError(t, err) value, err := io.ReadAll(reader) @@ -204,11 +233,13 @@ func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { }) t.Run("save key with no data", func(t *testing.T) { + emptyKey := namespacedKey(nsPrefix, "empty-key") + // Save a key with empty data - saveKVHelper(t, kv, ctx, section, "empty-key", strings.NewReader("")) + saveKVHelper(t, kv, ctx, testSection, emptyKey, strings.NewReader("")) // Verify it was saved with empty data - reader, err := kv.Get(ctx, section, "empty-key") + reader, err := kv.Get(ctx, testSection, emptyKey) require.NoError(t, err) value, err := io.ReadAll(reader) @@ -474,128 +505,134 @@ func runTestKVKeysWithSort(t *testing.T, kv resource.KV, nsPrefix string) { func runTestKVConcurrent(t *testing.T, kv resource.KV, nsPrefix string) { ctx := testutil.NewTestContext(t, time.Now().Add(60*time.Second)) - section := nsPrefix + "-concurrent" + nsPrefix += "-concurrent" - t.Run("concurrent save and get operations", func(t *testing.T) { - const numGoroutines = 10 - const numOperations = 20 + // Test concurrent operations for both sections, as they have different behaviours + // in the sqlkv implementation. + for _, testSection := range []string{"unified/data", "unified/events"} { + t.Run(testSection, func(t *testing.T) { + t.Run("concurrent save and get operations", func(t *testing.T) { + const numGoroutines = 10 + const numOperations = 20 - done := make(chan error, numGoroutines) + done := make(chan error, numGoroutines) - for i := 0; i < numGoroutines; i++ { - go func(goroutineID int) { - var err error - defer func() { done <- err }() + for goroutineID := range numGoroutines { + go func() { + var err error + defer func() { done <- err }() - for j := 0; j < numOperations; j++ { - key := fmt.Sprintf("concurrent-key-%d-%d", goroutineID, j) - value := fmt.Sprintf("concurrent-value-%d-%d", goroutineID, j) + for j := range numOperations { + key := namespacedKey(nsPrefix, fmt.Sprintf("concurrent-key-%d-%d", goroutineID, j)) + value := fmt.Sprintf("concurrent-value-%d-%d", goroutineID, j) - // Save - writer, err := kv.Save(ctx, section, key) - if err != nil { - return - } - defer func() { - err := writer.Close() - require.NoError(t, err) + // Save + writer, err := kv.Save(ctx, testSection, key) + if err != nil { + return + } + defer func() { + err := writer.Close() + require.NoError(t, err) + }() + _, err = io.Copy(writer, strings.NewReader(value)) + if err != nil { + return + } + err = writer.Close() + if err != nil { + return + } + + // Get immediately + reader, err := kv.Get(ctx, testSection, key) + if err != nil { + return + } + + readValue, err := io.ReadAll(reader) + require.NoError(t, err) + err = reader.Close() + require.NoError(t, err) + assert.Equal(t, value, string(readValue)) + } }() - _, err = io.Copy(writer, strings.NewReader(value)) - if err != nil { - return - } - err = writer.Close() - if err != nil { - return - } + } - // Get immediately - reader, err := kv.Get(ctx, section, key) - if err != nil { - return - } - - readValue, err := io.ReadAll(reader) + // Wait for all goroutines to complete + for range numGoroutines { + err := <-done require.NoError(t, err) - err = reader.Close() + } + }) + + t.Run("concurrent save, delete, and list operations", func(t *testing.T) { + const numGoroutines = 5 + done := make(chan error, numGoroutines) + + for i := range numGoroutines { + go func(goroutineID int) { + var err error + defer func() { done <- err }() + + key := namespacedKey(nsPrefix, fmt.Sprintf("concurrent-ops-key-%d", goroutineID)) + value := fmt.Sprintf("concurrent-ops-value-%d", goroutineID) + + // Save + writer, err := kv.Save(ctx, testSection, key) + if err != nil { + return + } + defer func() { + err := writer.Close() + require.NoError(t, err) + }() + _, err = io.Copy(writer, strings.NewReader(value)) + if err != nil { + return + } + err = writer.Close() + if err != nil { + return + } + + // List to verify it exists + found := false + for k, err := range kv.Keys(ctx, testSection, resource.ListOptions{}) { + if err != nil { + return + } + if k == key { + found = true + break + } + } + if !found { + err = fmt.Errorf("key %s not found in list", key) + return + } + + // Delete + err = kv.Delete(ctx, testSection, key) + if err != nil { + return + } + + // Verify it's deleted + _, err = kv.Get(ctx, testSection, key) + require.ErrorIs(t, resource.ErrNotFound, err) + err = nil // Expected error, so clear it + }(i) + } + + // Wait for all goroutines to complete + for range numGoroutines { + err := <-done require.NoError(t, err) - assert.Equal(t, value, string(readValue)) } - }(i) - } - - // Wait for all goroutines to complete - for i := 0; i < numGoroutines; i++ { - err := <-done - require.NoError(t, err) - } - }) - - t.Run("concurrent save, delete, and list operations", func(t *testing.T) { - const numGoroutines = 5 - done := make(chan error, numGoroutines) - - for i := 0; i < numGoroutines; i++ { - go func(goroutineID int) { - var err error - defer func() { done <- err }() - - key := fmt.Sprintf("concurrent-ops-key-%d", goroutineID) - value := fmt.Sprintf("concurrent-ops-value-%d", goroutineID) - - // Save - writer, err := kv.Save(ctx, section, key) - if err != nil { - return - } - defer func() { - err := writer.Close() - require.NoError(t, err) - }() - _, err = io.Copy(writer, strings.NewReader(value)) - if err != nil { - return - } - err = writer.Close() - if err != nil { - return - } - - // List to verify it exists - found := false - for k, err := range kv.Keys(ctx, section, resource.ListOptions{}) { - if err != nil { - return - } - if k == key { - found = true - break - } - } - if !found { - err = fmt.Errorf("key %s not found in list", key) - return - } - - // Delete - err = kv.Delete(ctx, section, key) - if err != nil { - return - } - - // Verify it's deleted - _, err = kv.Get(ctx, section, key) - require.ErrorIs(t, resource.ErrNotFound, err) - err = nil // Expected error, so clear it - }(i) - } - - // Wait for all goroutines to complete - for i := 0; i < numGoroutines; i++ { - err := <-done - require.NoError(t, err) - } - }) + }) + }) + } } func runTestKVUnixTimestamp(t *testing.T, kv resource.KV, nsPrefix string) { @@ -786,35 +823,35 @@ func runTestKVBatchGet(t *testing.T, kv resource.KV, nsPrefix string) { func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { ctx := testutil.NewTestContext(t, time.Now().Add(30*time.Second)) - section := nsPrefix + "-batchdelete" + nsPrefix += "-batchdelete" t.Run("batch delete existing keys", func(t *testing.T) { // Setup test data testData := map[string]string{ - "key1": "value1", - "key2": "value2", - "key3": "value3", + namespacedKey(nsPrefix, "key1"): "value1", + namespacedKey(nsPrefix, "key2"): "value2", + namespacedKey(nsPrefix, "key3"): "value3", } // Save test data for key, value := range testData { - saveKVHelper(t, kv, ctx, section, key, strings.NewReader(value)) + saveKVHelper(t, kv, ctx, testSection, key, strings.NewReader(value)) } // Verify keys exist before deletion for key := range testData { - _, err := kv.Get(ctx, section, key) + _, err := kv.Get(ctx, testSection, key) require.NoError(t, err) } // Batch delete all keys - keys := []string{"key1", "key2", "key3"} - err := kv.BatchDelete(ctx, section, keys) + keys := slices.Collect(maps.Keys(testData)) + err := kv.BatchDelete(ctx, testSection, keys) require.NoError(t, err) // Verify all keys are deleted for _, key := range keys { - _, err := kv.Get(ctx, section, key) + _, err := kv.Get(ctx, testSection, key) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) } @@ -822,39 +859,40 @@ func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { t.Run("batch delete with non-existent keys", func(t *testing.T) { // Setup some test data - saveKVHelper(t, kv, ctx, section, "existing-key-1", strings.NewReader("value1")) - saveKVHelper(t, kv, ctx, section, "existing-key-2", strings.NewReader("value2")) + key1, key2 := namespacedKey(nsPrefix, "existing-key-1"), namespacedKey(nsPrefix, "existing-key-2") + saveKVHelper(t, kv, ctx, testSection, key1, strings.NewReader("value1")) + saveKVHelper(t, kv, ctx, testSection, key2, strings.NewReader("value2")) // Batch delete with mix of existing and non-existent keys - keys := []string{"existing-key-1", "non-existent-1", "existing-key-2", "non-existent-2"} - err := kv.BatchDelete(ctx, section, keys) + keys := []string{key1, namespacedKey(nsPrefix, "non-existent-1"), key2, namespacedKey(nsPrefix, "non-existent-2")} + err := kv.BatchDelete(ctx, testSection, keys) require.NoError(t, err) // Verify existing keys are deleted - _, err = kv.Get(ctx, section, "existing-key-1") - assert.Error(t, err) + _, err = kv.Get(ctx, testSection, key1) + require.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) - _, err = kv.Get(ctx, section, "existing-key-2") - assert.Error(t, err) + _, err = kv.Get(ctx, testSection, key2) + require.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) }) t.Run("batch delete with all non-existent keys", func(t *testing.T) { // Batch delete keys that don't exist - keys := []string{"non-existent-1", "non-existent-2", "non-existent-3"} - err := kv.BatchDelete(ctx, section, keys) + keys := namespacedKeys(nsPrefix, []string{"non-existent-1", "non-existent-2", "non-existent-3"}) + err := kv.BatchDelete(ctx, testSection, keys) require.NoError(t, err) }) t.Run("batch delete with empty keys list", func(t *testing.T) { keys := []string{} - err := kv.BatchDelete(ctx, section, keys) + err := kv.BatchDelete(ctx, testSection, keys) require.NoError(t, err) }) t.Run("batch delete with empty section", func(t *testing.T) { - keys := []string{"some-key"} + keys := namespacedKeys(nsPrefix, []string{"some-key"}) err := kv.BatchDelete(ctx, "", keys) assert.Error(t, err) assert.Contains(t, err.Error(), "section is required") @@ -862,27 +900,27 @@ func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { t.Run("batch delete preserves other keys", func(t *testing.T) { // Setup test data - saveKVHelper(t, kv, ctx, section, "keep-key-1", strings.NewReader("keep-value-1")) - saveKVHelper(t, kv, ctx, section, "delete-key-1", strings.NewReader("delete-value-1")) - saveKVHelper(t, kv, ctx, section, "keep-key-2", strings.NewReader("keep-value-2")) - saveKVHelper(t, kv, ctx, section, "delete-key-2", strings.NewReader("delete-value-2")) + saveKVHelper(t, kv, ctx, testSection, namespacedKey(nsPrefix, "keep-key-1"), strings.NewReader("keep-value-1")) + saveKVHelper(t, kv, ctx, testSection, namespacedKey(nsPrefix, "delete-key-1"), strings.NewReader("delete-value-1")) + saveKVHelper(t, kv, ctx, testSection, namespacedKey(nsPrefix, "keep-key-2"), strings.NewReader("keep-value-2")) + saveKVHelper(t, kv, ctx, testSection, namespacedKey(nsPrefix, "delete-key-2"), strings.NewReader("delete-value-2")) // Batch delete specific keys - keys := []string{"delete-key-1", "delete-key-2"} - err := kv.BatchDelete(ctx, section, keys) + keys := namespacedKeys(nsPrefix, []string{"delete-key-1", "delete-key-2"}) + err := kv.BatchDelete(ctx, testSection, keys) require.NoError(t, err) // Verify deleted keys are gone - _, err = kv.Get(ctx, section, "delete-key-1") + _, err = kv.Get(ctx, testSection, namespacedKey(nsPrefix, "delete-key-1")) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) - _, err = kv.Get(ctx, section, "delete-key-2") + _, err = kv.Get(ctx, testSection, namespacedKey(nsPrefix, "delete-key-2")) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) // Verify kept keys still exist - reader, err := kv.Get(ctx, section, "keep-key-1") + reader, err := kv.Get(ctx, testSection, namespacedKey(nsPrefix, "keep-key-1")) require.NoError(t, err) value, err := io.ReadAll(reader) require.NoError(t, err) @@ -890,7 +928,7 @@ func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { err = reader.Close() require.NoError(t, err) - reader, err = kv.Get(ctx, section, "keep-key-2") + reader, err = kv.Get(ctx, testSection, namespacedKey(nsPrefix, "keep-key-2")) require.NoError(t, err) value, err = io.ReadAll(reader) require.NoError(t, err) @@ -904,18 +942,6 @@ func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { func saveKVHelper(t *testing.T, kv resource.KV, ctx context.Context, section, key string, value io.Reader) { t.Helper() - // TODO: remove this check once the sqlkv implementation supports `Save`. - type testingSaver interface { - TestingSave(context.Context, string, []byte) error - } - - if saver, ok := kv.(testingSaver); ok { - blob, err := io.ReadAll(value) - require.NoError(t, err) - require.NoError(t, saver.TestingSave(ctx, key, blob)) - return - } - writer, err := kv.Save(ctx, section, key) require.NoError(t, err) _, err = io.Copy(writer, value) diff --git a/pkg/storage/unified/testing/kv_test.go b/pkg/storage/unified/testing/kv_test.go index dafefc15ed2..af7de65e52c 100644 --- a/pkg/storage/unified/testing/kv_test.go +++ b/pkg/storage/unified/testing/kv_test.go @@ -44,13 +44,5 @@ func TestSQLKV(t *testing.T) { kv, err := resource.NewSQLKV(eDB) require.NoError(t, err) return kv - }, &KVTestOptions{ - NSPrefix: "sql-kv-test", - SkipTests: map[string]bool{ - TestKVSave: true, - TestKVConcurrent: true, - TestKVUnixTimestamp: true, - TestKVBatchDelete: true, - }, - }) + }, &KVTestOptions{NSPrefix: "sql-kv-test"}) } diff --git a/pkg/tests/apis/provisioning/connection_status_auth_test.go b/pkg/tests/apis/provisioning/connection_status_auth_test.go new file mode 100644 index 00000000000..fbddd85999a --- /dev/null +++ b/pkg/tests/apis/provisioning/connection_status_auth_test.go @@ -0,0 +1,88 @@ +package provisioning + +import ( + "context" + "net/http" + "testing" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/grafana/grafana/pkg/util/testutil" +) + +func TestIntegrationProvisioning_ConnectionStatusAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + createOptions := metav1.CreateOptions{FieldValidation: "Strict"} + + // Create a connection for testing + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection-status-test", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "123456", + "installationID": "454545", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.NoError(t, err, "failed to create connection") + + t.Run("admin can GET connection status", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("connections"). + Name("connection-status-test"). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET connection status") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot GET connection status", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("connections"). + Name("connection-status-test"). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET connection status") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET connection status", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("connections"). + Name("connection-status-test"). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET connection status") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) +} diff --git a/pkg/tests/apis/provisioning/exportjob_test.go b/pkg/tests/apis/provisioning/exportjob_test.go index 2218e87ef77..5d4348d23cb 100644 --- a/pkg/tests/apis/provisioning/exportjob_test.go +++ b/pkg/tests/apis/provisioning/exportjob_test.go @@ -44,6 +44,7 @@ func TestIntegrationProvisioning_ExportUnifiedToRepository(t *testing.T) { const repo = "local-repository" testRepo := TestRepo{ Name: repo, + Target: "instance", // Export is only supported for instance sync Copies: map[string]string{}, // No initial files needed for export test ExpectedDashboards: 4, // 4 dashboards created above (v0, v1, v2alpha1, v2beta1) ExpectedFolders: 0, // No folders expected after sync @@ -177,6 +178,7 @@ func TestIntegrationProvisioning_ExportDashboardsWithStoredVersions(t *testing.T const repo = "version-test-repository" testRepo := TestRepo{ Name: repo, + Target: "instance", // Export is only supported for instance sync Copies: map[string]string{}, ExpectedDashboards: len(tests), ExpectedFolders: 0, diff --git a/pkg/tests/apis/provisioning/helper_test.go b/pkg/tests/apis/provisioning/helper_test.go index 65669c0172e..a77b422ab8d 100644 --- a/pkg/tests/apis/provisioning/helper_test.go +++ b/pkg/tests/apis/provisioning/helper_test.go @@ -695,6 +695,9 @@ func runGrafana(t *testing.T, options ...grafanaOption) *provisioningTestHelper }, }, PermittedProvisioningPaths: ".|" + provisioningPath, + // Allow both folder and instance sync targets for tests + // (instance is needed for export jobs, folder for most operations) + ProvisioningAllowedTargets: []string{"folder", "instance"}, } for _, o := range options { o(&opts) diff --git a/pkg/tests/apis/provisioning/historicjobs_auth_test.go b/pkg/tests/apis/provisioning/historicjobs_auth_test.go new file mode 100644 index 00000000000..fc11f8d00b3 --- /dev/null +++ b/pkg/tests/apis/provisioning/historicjobs_auth_test.go @@ -0,0 +1,95 @@ +package provisioning + +import ( + "context" + "net/http" + "testing" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/pkg/util/testutil" +) + +func TestIntegrationProvisioning_HistoricJobsAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + const repo = "historicjobs-auth-test" + testRepo := TestRepo{ + Name: repo, + Target: "folder", + Copies: map[string]string{}, // No files needed for this test + ExpectedDashboards: 0, + ExpectedFolders: 1, // Repository creates a folder + } + helper.CreateRepo(t, testRepo) + + // Trigger a job to create a historic job entry + jobSpec := provisioning.JobSpec{ + Action: provisioning.JobActionPull, + Pull: &provisioning.SyncJobOptions{}, + } + body := asJSON(jobSpec) + + // Create a job as admin + var statusCode int + result := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("jobs"). + Body(body). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + require.NoError(t, result.Error(), "should be able to create job") + require.Equal(t, http.StatusAccepted, statusCode) + + // Wait for job to complete and become historic + helper.AwaitJobs(t, repo) + historicJob := helper.AwaitLatestHistoricJob(t, repo) + require.NotNil(t, historicJob, "should have a historic job") + + historicJobName := historicJob.GetName() + + t.Run("admin can GET historic job", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("historicjobs"). + Name(historicJobName). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET historic job") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot GET historic job", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("historicjobs"). + Name(historicJobName). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET historic job") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET historic job", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("historicjobs"). + Name(historicJobName). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET historic job") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) +} diff --git a/pkg/tests/apis/provisioning/job_validation_test.go b/pkg/tests/apis/provisioning/job_validation_test.go index c54ad58500c..4c1947693f1 100644 --- a/pkg/tests/apis/provisioning/job_validation_test.go +++ b/pkg/tests/apis/provisioning/job_validation_test.go @@ -24,10 +24,10 @@ func TestIntegrationProvisioning_JobValidation(t *testing.T) { const repo = "job-validation-test-repo" testRepo := TestRepo{ Name: repo, - Target: "instance", + Target: "folder", Copies: map[string]string{}, ExpectedDashboards: 0, - ExpectedFolders: 0, + ExpectedFolders: 1, // folder sync creates a folder } helper.CreateRepo(t, testRepo) diff --git a/pkg/tests/apis/provisioning/movejob_test.go b/pkg/tests/apis/provisioning/movejob_test.go index 85d227996fd..9cd298711a9 100644 --- a/pkg/tests/apis/provisioning/movejob_test.go +++ b/pkg/tests/apis/provisioning/movejob_test.go @@ -24,14 +24,15 @@ func TestIntegrationProvisioning_MoveJob(t *testing.T) { ctx := context.Background() const repo = "move-test-repo" testRepo := TestRepo{ - Name: repo, + Name: repo, + Target: "folder", Copies: map[string]string{ "testdata/all-panels.json": "dashboard1.json", "testdata/text-options.json": "dashboard2.json", "testdata/timeline-demo.json": "folder/dashboard3.json", }, ExpectedDashboards: 3, - ExpectedFolders: 1, + ExpectedFolders: 2, // folder sync creates a folder for the repo + one nested folder } helper.CreateRepo(t, testRepo) @@ -236,6 +237,7 @@ func TestIntegrationProvisioning_MoveJob(t *testing.T) { const refRepo = "move-ref-test-repo" helper.CreateRepo(t, TestRepo{ Name: refRepo, + Target: "folder", SkipResourceAssertions: true, // HACK: I am not sure why sometimes it's 6 or 3 dashbaords. }) diff --git a/pkg/tests/apis/provisioning/repository_subresources_auth_test.go b/pkg/tests/apis/provisioning/repository_subresources_auth_test.go new file mode 100644 index 00000000000..54a2f173b51 --- /dev/null +++ b/pkg/tests/apis/provisioning/repository_subresources_auth_test.go @@ -0,0 +1,236 @@ +package provisioning + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + "github.com/grafana/grafana/pkg/util/testutil" +) + +func TestIntegrationProvisioning_RepositorySubresourcesAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + const repo = "subresources-auth-test" + testRepo := TestRepo{ + Name: repo, + Target: "folder", + Copies: map[string]string{}, // No files needed for this test + ExpectedDashboards: 0, + ExpectedFolders: 1, // Repository creates a folder + } + helper.CreateRepo(t, testRepo) + + t.Run("test subresource", func(t *testing.T) { + newRepoConfig := map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Repository", + "spec": map[string]any{ + "title": "Test Configuration", + "type": "local", + "local": map[string]any{ + "path": helper.ProvisioningPath, + }, + "workflows": []string{"write"}, + "sync": map[string]any{ + "enabled": true, + "target": "folder", + "intervalSeconds": 10, + }, + }, + } + configBytes, err := json.Marshal(newRepoConfig) + require.NoError(t, err) + + t.Run("admin can POST test", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name("test-config-auth"). + SubResource("test"). + Body(configBytes). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to POST test") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot POST test", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Post(). + Namespace("default"). + Resource("repositories"). + Name("test-config-auth"). + SubResource("test"). + Body(configBytes). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to POST test") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot POST test", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Post(). + Namespace("default"). + Resource("repositories"). + Name("test-config-auth"). + SubResource("test"). + Body(configBytes). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to POST test") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + }) + + t.Run("resources subresource", func(t *testing.T) { + t.Run("admin can GET resources", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("resources"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET resources") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot GET resources", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("resources"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET resources") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET resources", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("resources"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET resources") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + }) + + t.Run("history subresource", func(t *testing.T) { + t.Run("admin can GET history (or BadRequest if not supported)", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("history"). + Do(ctx).StatusCode(&statusCode) + + // Admin should pass authorization - may get BadRequest if repo doesn't support history + // but should NOT get Forbidden (which would indicate authorization failure) + if result.Error() != nil { + require.False(t, apierrors.IsForbidden(result.Error()), "admin should not get Forbidden error") + // Local repos don't support history, so BadRequest is expected + require.True(t, apierrors.IsBadRequest(result.Error()) || statusCode == http.StatusBadRequest, + "should get BadRequest if history not supported, not Forbidden") + } else { + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK if history is supported") + } + }) + + t.Run("editor cannot GET history", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("history"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET history") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET history", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("history"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET history") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + }) + + t.Run("status subresource", func(t *testing.T) { + t.Run("admin can GET status", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET status") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot GET status", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET status") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET status", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("status"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET status") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + }) +} diff --git a/pkg/tests/apis/provisioning/repository_test.go b/pkg/tests/apis/provisioning/repository_test.go index 877ed0d5f98..f2447e71d23 100644 --- a/pkg/tests/apis/provisioning/repository_test.go +++ b/pkg/tests/apis/provisioning/repository_test.go @@ -578,7 +578,13 @@ func TestIntegrationProvisioning_RunLocalRepository(t *testing.T) { const targetPath = "all-panels.json" // Set up the repository. - helper.CreateRepo(t, TestRepo{Name: repo}) + helper.CreateRepo(t, TestRepo{ + Name: repo, + Target: "folder", + ExpectedDashboards: 0, + ExpectedFolders: 1, // folder sync creates a folder for the repo + SkipResourceAssertions: false, + }) // Write a file -- this will create it *both* in the local file system, and in grafana t.Run("write all panels", func(t *testing.T) { @@ -744,10 +750,10 @@ func TestIntegrationProvisioning_ImportAllPanelsFromLocalRepository(t *testing.T // Set up the repository and the file to import. testRepo := TestRepo{ Name: repo, - Target: "instance", + Target: "folder", Copies: map[string]string{"testdata/all-panels.json": "all-panels.json"}, ExpectedDashboards: 1, - ExpectedFolders: 0, + ExpectedFolders: 1, // folder sync creates a folder } // We create the repository helper.CreateRepo(t, testRepo) @@ -950,3 +956,66 @@ func TestIntegrationProvisioning_JobPermissions(t *testing.T) { require.Equal(t, http.StatusAccepted, statusCode, "should return 202 Accepted") }) } + +func TestIntegrationProvisioning_RefsPermissions(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + const repo = "refs-permissions-test" + testRepo := TestRepo{ + Name: repo, + Template: "testdata/github-readonly.json.tmpl", + Target: "folder", + ExpectedDashboards: 3, + ExpectedFolders: 3, // Repository creates folders + } + helper.CreateRepo(t, testRepo) + + t.Run("editor can GET refs", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("refs"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to GET refs") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + + // Verify we can parse the refs and it contains at least main branch + refs := &provisioning.RefList{} + err := result.Into(refs) + require.NoError(t, err, "should parse refs response") + require.NotEmpty(t, refs.Items, "should have at least one ref") + }) + + t.Run("viewer cannot GET refs", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("refs"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET refs") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("admin can GET refs", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("refs"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET refs") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) +} diff --git a/pkg/tests/apis/provisioning/settings_stats_auth_test.go b/pkg/tests/apis/provisioning/settings_stats_auth_test.go new file mode 100644 index 00000000000..d438066235a --- /dev/null +++ b/pkg/tests/apis/provisioning/settings_stats_auth_test.go @@ -0,0 +1,104 @@ +package provisioning + +import ( + "context" + "net/http" + "testing" + + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + "github.com/grafana/grafana/pkg/util/testutil" +) + +func TestIntegrationProvisioning_SettingsAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + t.Run("viewer can GET settings", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("settings"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "viewer should be able to GET settings") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor can GET settings", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("settings"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to GET settings") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("admin can GET settings", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("settings"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET settings") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) +} + +func TestIntegrationProvisioning_StatsAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + // Create a repository to ensure stats endpoint has data + const repo = "stats-auth-test" + helper.CreateRepo(t, TestRepo{ + Name: repo, + Target: "folder", + Copies: map[string]string{}, + ExpectedDashboards: 0, + ExpectedFolders: 1, + }) + + t.Run("admin can GET stats", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("stats"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET stats") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor cannot GET stats", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("stats"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "editor should not be able to GET stats") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("viewer cannot GET stats", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("stats"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to GET stats") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) +} diff --git a/pkg/tests/apis/provisioning/stats_test.go b/pkg/tests/apis/provisioning/stats_test.go index eae3cbf7531..25ecd5c8f7c 100644 --- a/pkg/tests/apis/provisioning/stats_test.go +++ b/pkg/tests/apis/provisioning/stats_test.go @@ -21,13 +21,14 @@ func TestIntegrationProvisioning_Stats(t *testing.T) { const repo = "stats-test-repo1" testRepo := TestRepo{ - Name: repo, + Name: repo, + Target: "folder", Copies: map[string]string{ "testdata/all-panels.json": "dashboard1.json", "testdata/text-options.json": "folder/dashboard2.json", }, ExpectedDashboards: 2, - ExpectedFolders: 1, + ExpectedFolders: 2, // folder sync creates a folder for the repo + one nested folder } helper.CreateRepo(t, testRepo) @@ -94,7 +95,7 @@ func TestIntegrationProvisioning_Stats(t *testing.T) { require.Equal(t, int64(2), count, "repo should manage 2 dashboards") } else if group == "folder.grafana.app" && resource == "folders" { count, _, _ := unstructured.NestedInt64(stat, "count") - require.Equal(t, int64(1), count, "repo should manage 1 folder") + require.Equal(t, int64(2), count, "repo should manage 2 folders (repo folder + nested folder)") } } } diff --git a/pkg/tests/testinfra/testinfra.go b/pkg/tests/testinfra/testinfra.go index c84ddd6fb40..6e2f0660c32 100644 --- a/pkg/tests/testinfra/testinfra.go +++ b/pkg/tests/testinfra/testinfra.go @@ -580,6 +580,12 @@ func CreateGrafDir(t *testing.T, opts GrafanaOpts) (string, string) { _, err = pathsSect.NewKey("permitted_provisioning_paths", opts.PermittedProvisioningPaths) require.NoError(t, err) } + if len(opts.ProvisioningAllowedTargets) > 0 { + provisioningSect, err := getOrCreateSection("provisioning") + require.NoError(t, err) + _, err = provisioningSect.NewKey("allowed_targets", strings.Join(opts.ProvisioningAllowedTargets, "|")) + require.NoError(t, err) + } if opts.EnableSCIM { scimSection, err := getOrCreateSection("auth.scim") require.NoError(t, err) @@ -669,6 +675,7 @@ type GrafanaOpts struct { UnifiedStorageEnableSearch bool UnifiedStorageMaxPageSizeBytes int PermittedProvisioningPaths string + ProvisioningAllowedTargets []string GrafanaComSSOAPIToken string LicensePath string EnableRecordingRules bool diff --git a/public/app/api/clients/provisioning/utils/createOnCacheEntryAdded.ts b/public/app/api/clients/provisioning/utils/createOnCacheEntryAdded.ts index c3c44ede267..0d39d4fa402 100644 --- a/public/app/api/clients/provisioning/utils/createOnCacheEntryAdded.ts +++ b/public/app/api/clients/provisioning/utils/createOnCacheEntryAdded.ts @@ -58,6 +58,7 @@ export function createOnCacheEntryAdded(resourceName: string) { }); } catch (error) { console.error('Error in onCacheEntryAdded:', error); + return; } await cacheEntryRemoved; diff --git a/public/app/features/alerting/unified/CLAUDE.md b/public/app/features/alerting/unified/CLAUDE.md index 124b9da622f..35ea0486876 100644 --- a/public/app/features/alerting/unified/CLAUDE.md +++ b/public/app/features/alerting/unified/CLAUDE.md @@ -1,3 +1,10 @@ +--- +title: Alerting Squad Guidelines +description: Alerting-specific patterns and conventions for Grafana +globs: + - 'public/app/features/alerting/**' +--- + # Alerting Squad - Claude Code Configuration This file provides context for Claude Code when working on the Grafana Alerting codebase. It contains alerting-specific patterns and references to Grafana's coding standards. diff --git a/public/app/features/alerting/unified/components/rule-viewer/AlertRuleMenu.test.tsx b/public/app/features/alerting/unified/components/rule-viewer/AlertRuleMenu.test.tsx new file mode 100644 index 00000000000..e95b321c02c --- /dev/null +++ b/public/app/features/alerting/unified/components/rule-viewer/AlertRuleMenu.test.tsx @@ -0,0 +1,1612 @@ +import { render, screen, testWithFeatureToggles, userEvent, waitFor } from 'test/test-utils'; +import { byLabelText, byRole } from 'testing-library-selector'; + +import { useAssistant } from '@grafana/assistant'; +import { GrafanaEdition } from '@grafana/data/internal'; +import { config, setPluginLinksHook } from '@grafana/runtime'; +import AlertRuleMenu from 'app/features/alerting/unified/components/rule-viewer/AlertRuleMenu'; +import { mockFolderApi, setupMswServer } from 'app/features/alerting/unified/mockApi'; +import { + getCloudRule, + getGrafanaRule, + grantUserPermissions, + mockDataSource, + mockFolder, + mockGrafanaRulerRule, + mockPromAlertingRule, + mockPromRecordingRule, + mockRulerGrafanaRecordingRule, +} from 'app/features/alerting/unified/mocks'; +import { setFolderAccessControl } from 'app/features/alerting/unified/mocks/server/configure'; +import { setupDataSources } from 'app/features/alerting/unified/testSetup/datasources'; +import * as miscUtils from 'app/features/alerting/unified/utils/misc'; +import { fromCombinedRule } from 'app/features/alerting/unified/utils/rule-id'; +import { AccessControlAction } from 'app/types/accessControl'; +import { PromAlertingRuleState, PromRuleType } from 'app/types/unified-alerting-dto'; + +import { AlertRuleAction } from '../../hooks/useAbilities'; + +const mockOpenAssistant = jest.fn(); +jest.mock('@grafana/assistant', () => ({ + useAssistant: jest.fn(), + createAssistantContextItem: jest.fn((type: string, data: T) => ({ + type, + ...data, + })), +})); + +const mockUseAssistant = jest.mocked(useAssistant); + +const mockPauseExecute = jest.fn().mockResolvedValue(undefined); +jest.mock('../../hooks/ruleGroup/usePauseAlertRule', () => ({ + usePauseRuleInGroup: () => [ + { + execute: mockPauseExecute, + }, + { loading: false, error: undefined }, + ], +})); + +const server = setupMswServer(); + +setPluginLinksHook(() => ({ + links: [], + isLoading: false, +})); + +setupDataSources(); + +const user = userEvent.setup(); +const handleSilence = jest.fn(); +const handleDelete = jest.fn(); +const handleDuplicateRule = jest.fn(); + +const ui = { + moreButton: byLabelText(/More/), + menu: byRole('menu'), + menuItems: { + pause: byRole('menuitem', { name: /Pause evaluation/i }), + resume: byRole('menuitem', { name: /Resume evaluation/i }), + silence: byRole('menuitem', { name: /Silence notifications/i }), + duplicate: byRole('menuitem', { name: /Duplicate/i }), + copyLink: byRole('menuitem', { name: /Copy link/i }), + export: byRole('menuitem', { name: /Export/i }), + delete: byRole('menuitem', { name: /Delete/i }), + manageEnrichments: byRole('menuitem', { name: /Manage enrichments/i }), + declareIncident: byRole('link', { name: /Declare incident/i }), + analyzeRule: byRole('menuitem', { name: /Analyze rule/i }), + }, +}; + +const getMenuContents = async () => { + await screen.findByRole('menu'); + const allMenuItems = screen.queryAllByRole('menuitem').map((el) => el.textContent); + const allLinkItems = screen.queryAllByRole('link').map((el) => el.textContent); + + return [...allMenuItems, ...allLinkItems]; +}; + +const openMenu = async () => { + await user.click(await ui.moreButton.find()); + await waitFor(() => { + expect(ui.menu.query()).toBeInTheDocument(); + }); +}; + +// Helper function to create a default rule setup +const createDefaultRuleSetup = () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + return { mockRule, identifier, groupIdentifier }; +}; + +describe('AlertRuleMenu', () => { + const originalBuildInfo = config.buildInfo; + + beforeEach(() => { + jest.clearAllMocks(); + mockPauseExecute.mockResolvedValue(undefined); + mockOpenAssistant.mockClear(); + // Default: assistant unavailable + mockUseAssistant.mockReturnValue({ + isAvailable: false, + openAssistant: mockOpenAssistant, + } as unknown as ReturnType); + + // Reset config to defaults + config.buildInfo = { ...originalBuildInfo }; + + // Set up default folder mock for Grafana rules (namespace-uid is the default folder UID) + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + // Set up default permissions (no permissions granted by default) + grantUserPermissions([]); + setFolderAccessControl({}); + }); + + afterEach(() => { + config.buildInfo = originalBuildInfo; + }); + + describe('Basic Rendering', () => { + it('renders MoreButton correctly', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + expect(await ui.moreButton.find()).toBeInTheDocument(); + }); + + it('opens menu when MoreButton is clicked', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + + expect(ui.menu.query()).toBeInTheDocument(); + }); + + it('closes menu when clicking outside', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menu.query()).toBeInTheDocument(); + + // Click outside the menu + await user.click(document.body); + + await waitFor(() => { + expect(ui.menu.query()).not.toBeInTheDocument(); + }); + }); + + it('menu contains expected structure', async () => { + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + + const menuContents = await getMenuContents(); + expect(menuContents).toHaveLength(1); + expect(menuContents).toContain('Copy link'); + }); + }); + + describe('Permissions', () => { + // Generalized test to reduce repetition for menu item visibility + type MenuItemTestCase = { + description: string; + action: AlertRuleAction; + menuItem: keyof typeof ui.menuItems; + granted: boolean; + shouldShow: boolean; + }; + + const testMenuItemVisibility = ({ description, action, menuItem, granted, shouldShow }: MenuItemTestCase) => { + it(description, async () => { + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + // Grant permissions based on action + const permissions: AccessControlAction[] = []; + const folderAccessControl: Record = {}; + + if (granted) { + switch (action) { + case AlertRuleAction.Pause: + case AlertRuleAction.Update: + permissions.push(AccessControlAction.AlertingRuleUpdate); + folderAccessControl[AccessControlAction.AlertingRuleUpdate] = true; + break; + case AlertRuleAction.Delete: + permissions.push(AccessControlAction.AlertingRuleDelete); + folderAccessControl[AccessControlAction.AlertingRuleDelete] = true; + break; + case AlertRuleAction.Duplicate: + permissions.push(AccessControlAction.AlertingRuleCreate); + break; + case AlertRuleAction.Silence: + permissions.push(AccessControlAction.AlertingInstanceCreate, AccessControlAction.AlertingSilenceCreate); + break; + case AlertRuleAction.ModifyExport: + permissions.push(AccessControlAction.AlertingRuleRead); + break; + } + } + + grantUserPermissions(permissions); + setFolderAccessControl(folderAccessControl); + + // Set up folder mock for Grafana rules with matching access control + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: folderAccessControl, + }) + ); + + render( + + ); + + await openMenu(); + if (shouldShow) { + expect(await ui.menuItems[menuItem].find()).toBeInTheDocument(); + } else { + expect(ui.menuItems[menuItem].query()).not.toBeInTheDocument(); + } + }); + }; + + describe('Pause/Resume visibility', () => { + testMenuItemVisibility({ + description: 'shows Pause when pause permission is granted', + action: AlertRuleAction.Pause, + menuItem: 'pause', + granted: true, + shouldShow: true, + }); + + testMenuItemVisibility({ + description: 'hides Pause when pause permission is denied', + action: AlertRuleAction.Pause, + menuItem: 'pause', + granted: false, + shouldShow: false, + }); + }); + + describe('Delete visibility', () => { + testMenuItemVisibility({ + description: 'shows Delete when delete permission is granted', + action: AlertRuleAction.Delete, + menuItem: 'delete', + granted: true, + shouldShow: true, + }); + + testMenuItemVisibility({ + description: 'hides Delete when delete permission is denied', + action: AlertRuleAction.Delete, + menuItem: 'delete', + granted: false, + shouldShow: false, + }); + }); + + describe('Duplicate visibility', () => { + testMenuItemVisibility({ + description: 'shows Duplicate when duplicate permission is granted', + action: AlertRuleAction.Duplicate, + menuItem: 'duplicate', + granted: true, + shouldShow: true, + }); + + testMenuItemVisibility({ + description: 'hides Duplicate when duplicate permission is denied', + action: AlertRuleAction.Duplicate, + menuItem: 'duplicate', + granted: false, + shouldShow: false, + }); + }); + + describe('Silence visibility', () => { + testMenuItemVisibility({ + description: 'shows Silence when silence permission is granted', + action: AlertRuleAction.Silence, + menuItem: 'silence', + granted: true, + shouldShow: true, + }); + + testMenuItemVisibility({ + description: 'hides Silence when silence permission is denied', + action: AlertRuleAction.Silence, + menuItem: 'silence', + granted: false, + shouldShow: false, + }); + }); + + describe('Export visibility', () => { + testMenuItemVisibility({ + description: 'shows Export when export permission is granted', + action: AlertRuleAction.ModifyExport, + menuItem: 'export', + granted: true, + shouldShow: true, + }); + + testMenuItemVisibility({ + description: 'hides Export when export permission is denied', + action: AlertRuleAction.ModifyExport, + menuItem: 'export', + granted: false, + shouldShow: false, + }); + }); + + describe('Copy Link visibility', () => { + it('shows Copy Link when shareUrl exists', async () => { + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.copyLink.find()).toBeInTheDocument(); + }); + }); + }); + + describe('Rule Types', () => { + beforeEach(() => { + // Grant all permissions for testing rule type differences + grantUserPermissions([ + AccessControlAction.AlertingRuleRead, + AccessControlAction.AlertingRuleUpdate, + AccessControlAction.AlertingRuleDelete, + AccessControlAction.AlertingRuleCreate, + AccessControlAction.AlertingInstanceCreate, + AccessControlAction.AlertingSilenceCreate, + ]); + setFolderAccessControl({ + [AccessControlAction.AlertingRuleUpdate]: true, + [AccessControlAction.AlertingRuleDelete]: true, + }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { + [AccessControlAction.AlertingRuleUpdate]: true, + [AccessControlAction.AlertingRuleDelete]: true, + }, + }) + ); + }); + + describe('Grafana-managed rules', () => { + it('shows Pause option for Grafana-managed alerting rules', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.pause.find()).toBeInTheDocument(); + }); + + it('does not show Pause option for datasource-managed rules', async () => { + const datasource = mockDataSource({ uid: 'mimir', name: 'Mimir' }); + const mockRule = getCloudRule({}, { rulesSource: datasource }); + const identifier = fromCombinedRule(datasource.name, mockRule); + const groupIdentifier = { + groupOrigin: 'datasource' as const, + rulesSource: { uid: datasource.uid, name: datasource.name, ruleSourceType: 'datasource' as const }, + namespace: { name: 'namespace-name' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.pause.query()).not.toBeInTheDocument(); + }); + }); + + describe('Alerting vs Recording rules', () => { + it('shows Silence option for alerting rules', async () => { + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ type: PromRuleType.Alerting }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.silence.find()).toBeInTheDocument(); + }); + + it('does not show Silence option for recording rules', async () => { + const mockRule = getGrafanaRule({ + promRule: mockPromRecordingRule({ type: PromRuleType.Recording }), + }); + // Override the rulerRule to be a recording rule + mockRule.rulerRule = mockRulerGrafanaRecordingRule( + {}, + { + uid: 'mock-rule-uid-123', + namespace_uid: 'namespace-uid', + } + ); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + }) + ); + + render( + + ); + + await openMenu(); + expect(ui.menuItems.silence.query()).not.toBeInTheDocument(); + }); + }); + + describe('Provisioned rules', () => { + it('hides Delete option for provisioned rules', async () => { + const mockRule = getGrafanaRule({ + rulerRule: mockGrafanaRulerRule({ provenance: 'file' }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.delete.query()).not.toBeInTheDocument(); + }); + + it('hides Pause option for provisioned rules', async () => { + const mockRule = getGrafanaRule({ + rulerRule: mockGrafanaRulerRule({ provenance: 'file' }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.pause.query()).not.toBeInTheDocument(); + }); + }); + + describe('Mixed data scenarios', () => { + it('works with only promRule available', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menu.query()).toBeInTheDocument(); + }); + + it('works with only rulerRule available', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menu.query()).toBeInTheDocument(); + }); + + it('works with both promRule and rulerRule available', async () => { + const mockRule = getGrafanaRule(); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menu.query()).toBeInTheDocument(); + }); + }); + }); + + describe('Handler Callbacks', () => { + describe('handleSilence', () => { + it('calls handleSilence when Silence menu item is clicked', async () => { + grantUserPermissions([AccessControlAction.AlertingInstanceCreate, AccessControlAction.AlertingSilenceCreate]); + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.silence.find()); + + expect(handleSilence).toHaveBeenCalledTimes(1); + }); + }); + + describe('handleManageEnrichments', () => { + testWithFeatureToggles({ + enable: ['alertEnrichment', 'alertingEnrichmentPerRule'], + }); + + it('calls handleManageEnrichments when Manage enrichments menu item is clicked', async () => { + // Both toggles need to be enabled: alertEnrichment for the hook, alertingEnrichmentPerRule for the component + grantUserPermissions([AccessControlAction.AlertingEnrichmentsRead]); + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const handleManageEnrichments = jest.fn(); + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.manageEnrichments.find()); + + expect(handleManageEnrichments).toHaveBeenCalledTimes(1); + }); + }); + + describe('handleDelete', () => { + it('calls handleDelete with correct identifier and groupIdentifier when Delete menu item is clicked', async () => { + grantUserPermissions([AccessControlAction.AlertingRuleDelete]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleDelete]: true }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { [AccessControlAction.AlertingRuleDelete]: true }, + }) + ); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.delete.find()); + + expect(handleDelete).toHaveBeenCalledTimes(1); + expect(handleDelete).toHaveBeenCalledWith(identifier, groupIdentifier); + }); + + it('does not call handleDelete when identifier is not editable', async () => { + grantUserPermissions([AccessControlAction.AlertingRuleDelete]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleDelete]: true }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { [AccessControlAction.AlertingRuleDelete]: true }, + }) + ); + + const { mockRule, groupIdentifier } = createDefaultRuleSetup(); + // Create a non-editable identifier (e.g., Prometheus rule identifier without rulerRule) + // For external rules without rulerRule, the delete button should not appear + const identifier = fromCombinedRule('prometheus', { + ...mockRule, + rulerRule: undefined, + }); + + render( + + ); + + await openMenu(); + expect(ui.menuItems.delete.query()).not.toBeInTheDocument(); + expect(handleDelete).not.toHaveBeenCalled(); + }); + }); + + describe('handleDuplicateRule', () => { + it('calls handleDuplicateRule with correct identifier when Duplicate menu item is clicked', async () => { + grantUserPermissions([AccessControlAction.AlertingRuleCreate]); + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.duplicate.find()); + + expect(handleDuplicateRule).toHaveBeenCalledTimes(1); + expect(handleDuplicateRule).toHaveBeenCalledWith(identifier); + }); + }); + + describe('onPauseChange', () => { + it('calls onPauseChange after pause state change when Pause menu item is clicked', async () => { + const onPauseChange = jest.fn(); + grantUserPermissions([AccessControlAction.AlertingRuleUpdate]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleUpdate]: true }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { [AccessControlAction.AlertingRuleUpdate]: true }, + }) + ); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.pause.find()); + + await waitFor(() => { + expect(mockPauseExecute).toHaveBeenCalledTimes(1); + }); + + await waitFor(() => { + expect(onPauseChange).toHaveBeenCalledTimes(1); + }); + expect(onPauseChange).toHaveBeenCalledWith(); + }); + + it('calls onPauseChange after resume state change when Resume menu item is clicked', async () => { + const onPauseChange = jest.fn(); + grantUserPermissions([AccessControlAction.AlertingRuleUpdate]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleUpdate]: true }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { [AccessControlAction.AlertingRuleUpdate]: true }, + }) + ); + + const mockRule = getGrafanaRule({ + rulerRule: mockGrafanaRulerRule({ is_paused: true }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.resume.find()); + + await waitFor(() => { + expect(mockPauseExecute).toHaveBeenCalledTimes(1); + }); + + await waitFor(() => { + expect(onPauseChange).toHaveBeenCalledTimes(1); + }); + expect(onPauseChange).toHaveBeenCalledWith(); + }); + }); + }); + + describe('Feature Flags', () => { + describe('alertingEnrichmentPerRule', () => { + describe('when feature flag is disabled', () => { + testWithFeatureToggles({ + disable: ['alertingEnrichmentPerRule'], + }); + + it('hides Manage enrichments when feature flag is disabled', async () => { + grantUserPermissions([AccessControlAction.AlertingEnrichmentsRead]); + + const handleManageEnrichments = jest.fn(); + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + expect(ui.menuItems.manageEnrichments.query()).not.toBeInTheDocument(); + }); + }); + + describe('when feature flag is enabled', () => { + testWithFeatureToggles({ + enable: ['alertEnrichment', 'alertingEnrichmentPerRule'], + }); + + it('shows Manage enrichments when feature flag is enabled and all conditions are met', async () => { + // Both toggles need to be enabled: alertEnrichment for the hook, alertingEnrichmentPerRule for the component + grantUserPermissions([AccessControlAction.AlertingEnrichmentsRead]); + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const handleManageEnrichments = jest.fn(); + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.manageEnrichments.find()).toBeInTheDocument(); + }); + }); + + describe('when feature flags are enabled but permission is missing', () => { + testWithFeatureToggles({ + enable: ['alertEnrichment', 'alertingEnrichmentPerRule'], + }); + + it('hides Manage enrichments when enrichment ability is not allowed', async () => { + // Enable both toggles to ensure we're testing the permission check, not the toggles + grantUserPermissions([]); + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const handleManageEnrichments = jest.fn(); + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + expect(ui.menuItems.manageEnrichments.query()).not.toBeInTheDocument(); + }); + }); + }); + + describe('Open-source vs Enterprise', () => { + it('hides Declare Incident in open-source edition for firing alerting rules', async () => { + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'production'; + + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Firing }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.declareIncident.query()).not.toBeInTheDocument(); + }); + + it('shows Declare Incident in enterprise edition for firing alerting rules', async () => { + config.buildInfo.edition = GrafanaEdition.Enterprise; + config.buildInfo.env = 'production'; + + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Firing }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.declareIncident.find()).toBeInTheDocument(); + }); + + it('shows Declare Incident in dev mode even for open-source edition', async () => { + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'development'; + + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Firing }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.declareIncident.find()).toBeInTheDocument(); + }); + + it('hides Declare Incident for non-firing alerting rules in enterprise', async () => { + config.buildInfo.edition = GrafanaEdition.Enterprise; + config.buildInfo.env = 'production'; + + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.declareIncident.query()).not.toBeInTheDocument(); + }); + + it('hides Declare Incident for recording rules', async () => { + config.buildInfo.edition = GrafanaEdition.Enterprise; + config.buildInfo.env = 'production'; + + const mockRule = getGrafanaRule({ + promRule: mockPromRecordingRule({ type: PromRuleType.Recording }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.declareIncident.query()).not.toBeInTheDocument(); + }); + }); + + describe('Assistant availability', () => { + beforeEach(() => { + // Reset config to ensure clean state for assistant tests + config.buildInfo = { ...originalBuildInfo }; + config.buildInfo.env = 'production'; + config.buildInfo.edition = GrafanaEdition.OpenSource; + // Reset assistant mock to default (unavailable) for each test + mockUseAssistant.mockReturnValue({ + isAvailable: false, + openAssistant: mockOpenAssistant, + } as unknown as ReturnType); + }); + + it('shows Analyze Rule when assistant is available for Grafana-managed rules', async () => { + // Override mock to return available + mockUseAssistant.mockReturnValue({ + isAvailable: true, + openAssistant: mockOpenAssistant, + } as unknown as ReturnType); + + // Create a Grafana rule with promRule that has uid and folderUid + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ + uid: 'test-rule-uid', + folderUid: 'test-folder-uid', + }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(await ui.menuItems.analyzeRule.find()).toBeInTheDocument(); + }); + + it('hides Analyze Rule when assistant is unavailable', async () => { + // Mock already set to unavailable in beforeEach, but be explicit + mockUseAssistant.mockReturnValue({ + isAvailable: false, + openAssistant: mockOpenAssistant, + } as unknown as ReturnType); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + expect(ui.menuItems.analyzeRule.query()).not.toBeInTheDocument(); + }); + + it('hides Analyze Rule for datasource-managed rules even when assistant is available', async () => { + mockUseAssistant.mockReturnValue({ + isAvailable: true, + openAssistant: mockOpenAssistant, + } as unknown as ReturnType); + + const datasource = mockDataSource({ uid: 'mimir', name: 'Mimir' }); + const mockRule = getCloudRule({}, { rulesSource: datasource }); + const identifier = fromCombinedRule(datasource.name, mockRule); + const groupIdentifier = { + groupOrigin: 'datasource' as const, + rulesSource: { uid: datasource.uid, name: datasource.name, ruleSourceType: 'datasource' as const }, + namespace: { name: 'namespace-name' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.analyzeRule.query()).not.toBeInTheDocument(); + }); + }); + }); + + describe('Edge Cases', () => { + describe('Missing Data', () => { + describe('with enrichment feature flags enabled', () => { + testWithFeatureToggles({ + enable: ['alertEnrichment', 'alertingEnrichmentPerRule'], + }); + + it('hides Manage enrichments when ruleUid is missing even if all other conditions are met', async () => { + grantUserPermissions([AccessControlAction.AlertingEnrichmentsRead]); + // Note: Cloud rules typically don't have a ruleUid, so this tests that case + mockFolderApi(server).folder('namespace-uid', mockFolder({ uid: 'namespace-uid', title: 'Test Folder' })); + + const handleManageEnrichments = jest.fn(); + const datasource = mockDataSource({ uid: 'prometheus', name: 'Prometheus' }); + const mockRule = getCloudRule({}, { rulesSource: datasource }); + const identifier = fromCombinedRule(datasource.name, mockRule); + const groupIdentifier = { + groupOrigin: 'datasource' as const, + rulesSource: { uid: datasource.uid, name: datasource.name, ruleSourceType: 'datasource' as const }, + namespace: { name: 'namespace-name' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.manageEnrichments.query()).not.toBeInTheDocument(); + }); + }); + + it('hides Pause option when ruleUid is missing even if pause permission is granted', async () => { + grantUserPermissions([AccessControlAction.AlertingRuleUpdate]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleUpdate]: true }); + + const datasource = mockDataSource({ uid: 'prometheus', name: 'Prometheus' }); + const mockRule = getCloudRule({}, { rulesSource: datasource }); + const identifier = fromCombinedRule(datasource.name, mockRule); + const groupIdentifier = { + groupOrigin: 'datasource' as const, + rulesSource: { uid: datasource.uid, name: datasource.name, ruleSourceType: 'datasource' as const }, + namespace: { name: 'namespace-name' }, + groupName: 'group-name', + }; + + render( + + ); + + await openMenu(); + expect(ui.menuItems.pause.query()).not.toBeInTheDocument(); + }); + + it('pause still works when onPauseChange is not provided', async () => { + grantUserPermissions([AccessControlAction.AlertingRuleUpdate]); + setFolderAccessControl({ [AccessControlAction.AlertingRuleUpdate]: true }); + mockFolderApi(server).folder( + 'namespace-uid', + mockFolder({ + uid: 'namespace-uid', + title: 'Test Folder', + accessControl: { [AccessControlAction.AlertingRuleUpdate]: true }, + }) + ); + + const { mockRule, identifier, groupIdentifier } = createDefaultRuleSetup(); + + render( + + ); + + await openMenu(); + await user.click(await ui.menuItems.pause.find()); + + // Pause should still execute even without callback + await waitFor(() => { + expect(mockPauseExecute).toHaveBeenCalledTimes(1); + }); + }); + }); + + describe('Empty States', () => { + it('shows minimal menu with only Copy Link when no permissions are granted', async () => { + // Use a non-firing rule to avoid Declare Incident showing + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'production'; + + render( + + ); + + await openMenu(); + + expect(await ui.menuItems.copyLink.find()).toBeInTheDocument(); + expect(ui.menuItems.pause.query()).not.toBeInTheDocument(); + expect(ui.menuItems.silence.query()).not.toBeInTheDocument(); + expect(ui.menuItems.duplicate.query()).not.toBeInTheDocument(); + expect(ui.menuItems.export.query()).not.toBeInTheDocument(); + expect(ui.menuItems.delete.query()).not.toBeInTheDocument(); + expect(ui.menuItems.manageEnrichments.query()).not.toBeInTheDocument(); + expect(ui.menuItems.declareIncident.query()).not.toBeInTheDocument(); + expect(ui.menuItems.analyzeRule.query()).not.toBeInTheDocument(); + }); + + it('menu still opens even when no applicable items are available', async () => { + // All abilities denied and no shareUrl + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'production'; + + // Mock createShareLink to return undefined + const createShareLinkSpy = jest.spyOn(miscUtils, 'createShareLink'); + createShareLinkSpy.mockReturnValue(undefined); + + render( + + ); + + await openMenu(); + + expect(ui.menu.query()).toBeInTheDocument(); + const menuItems = screen.queryAllByRole('menuitem'); + const linkItems = screen.queryAllByRole('link'); + expect(menuItems.length).toBe(0); + expect(linkItems.length).toBe(0); + + createShareLinkSpy.mockRestore(); + }); + }); + + describe('Error Handling', () => { + it('handles gracefully when clipboard API is unavailable', async () => { + const originalClipboard = navigator.clipboard; + // Mock clipboard as undefined to simulate unavailable API + Object.defineProperty(navigator, 'clipboard', { + value: undefined, + writable: true, + configurable: true, + }); + + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'production'; + + render( + + ); + + await openMenu(); + const copyLinkItem = await ui.menuItems.copyLink.find(); + + await expect(user.click(copyLinkItem)).resolves.not.toThrow(); + + // Restore clipboard + Object.defineProperty(navigator, 'clipboard', { + value: originalClipboard, + writable: true, + configurable: true, + }); + }); + + it('handles gracefully when shareUrl is undefined', async () => { + // Use a non-firing rule to avoid Declare Incident showing + const mockRule = getGrafanaRule({ + promRule: mockPromAlertingRule({ state: PromAlertingRuleState.Inactive }), + }); + const identifier = fromCombinedRule('grafana', mockRule); + const groupIdentifier = { + groupOrigin: 'grafana' as const, + namespace: { uid: 'namespace-uid' }, + groupName: 'group-name', + }; + + config.buildInfo.edition = GrafanaEdition.OpenSource; + config.buildInfo.env = 'production'; + + // Mock createShareLink to return undefined + const createShareLinkSpy = jest.spyOn(require('app/features/alerting/unified/utils/misc'), 'createShareLink'); + createShareLinkSpy.mockReturnValue(undefined); + + render( + + ); + + await openMenu(); + + expect(ui.menuItems.copyLink.query()).not.toBeInTheDocument(); + expect(ui.menu.query()).toBeInTheDocument(); + + createShareLinkSpy.mockRestore(); + }); + }); + }); +}); diff --git a/public/app/features/alerting/unified/featureToggles.ts b/public/app/features/alerting/unified/featureToggles.ts index 7ca1747a8c5..15fa8e11fd8 100644 --- a/public/app/features/alerting/unified/featureToggles.ts +++ b/public/app/features/alerting/unified/featureToggles.ts @@ -26,3 +26,8 @@ export const shouldUseBackendFilters = () => config.featureToggles.alertingUIUse export const shouldUseFullyCompatibleBackendFilters = () => config.featureToggles.alertingUIUseFullyCompatBackendFilters ?? false; + +/** + * Saved searches feature - allows users to save and apply search queries on the Alert Rules page. + */ +export const shouldUseSavedSearches = () => config.featureToggles.alertingSavedSearches ?? false; diff --git a/public/app/features/alerting/unified/mockApi.ts b/public/app/features/alerting/unified/mockApi.ts index 614c8235dd0..67053ade5f6 100644 --- a/public/app/features/alerting/unified/mockApi.ts +++ b/public/app/features/alerting/unified/mockApi.ts @@ -9,6 +9,7 @@ import { setupAlertmanagerStatusMapDefaultState, } from 'app/features/alerting/unified/mocks/server/entities/alertmanagers'; import { resetRoutingTreeMap } from 'app/features/alerting/unified/mocks/server/entities/k8s/routingtrees'; +import { resetUserStorage } from 'app/features/alerting/unified/mocks/server/handlers/userStorage'; import { DashboardDTO } from 'app/types/dashboard'; import { FolderDTO } from 'app/types/folders'; import { @@ -256,6 +257,7 @@ export function setupMswServer() { setupAlertmanagerConfigMapDefaultState(); setupAlertmanagerStatusMapDefaultState(); resetRoutingTreeMap(); + resetUserStorage(); }); return server; diff --git a/public/app/features/alerting/unified/mocks/server/all-handlers.ts b/public/app/features/alerting/unified/mocks/server/all-handlers.ts index 4b0b0ac7249..c3a9db4ac5c 100644 --- a/public/app/features/alerting/unified/mocks/server/all-handlers.ts +++ b/public/app/features/alerting/unified/mocks/server/all-handlers.ts @@ -19,6 +19,7 @@ import allPluginHandlers from 'app/features/alerting/unified/mocks/server/handle import provisioningHandlers from 'app/features/alerting/unified/mocks/server/handlers/provisioning'; import searchHandlers from 'app/features/alerting/unified/mocks/server/handlers/search'; import silenceHandlers from 'app/features/alerting/unified/mocks/server/handlers/silences'; +import userStorageHandlers from 'app/features/alerting/unified/mocks/server/handlers/userStorage'; /** * All alerting-specific handlers that are required across tests @@ -55,6 +56,7 @@ const allHandlers = [ ...datasourcesHandlers, ...evalHandlers, ...pluginsHandlers, + ...userStorageHandlers, ]; export default allHandlers; diff --git a/public/app/features/alerting/unified/mocks/server/handlers/userStorage.ts b/public/app/features/alerting/unified/mocks/server/handlers/userStorage.ts new file mode 100644 index 00000000000..b2a162ea898 --- /dev/null +++ b/public/app/features/alerting/unified/mocks/server/handlers/userStorage.ts @@ -0,0 +1,171 @@ +import { HttpResponse, http } from 'msw'; + +import { config } from '@grafana/runtime'; + +/** + * UserStorage spec type matching the backend API response. + */ +interface UserStorageSpec { + data: { [key: string]: string }; +} + +/** + * In-memory storage for UserStorage mock data. + * This allows tests to set up and verify storage state. + */ +let userStorageData: Record = {}; + +/** + * Get the base URL for UserStorage API. + * Uses config.namespace which defaults to 'default' in tests. + */ +const getBaseUrl = () => `/apis/userstorage.grafana.app/v0alpha1/namespaces/${config.namespace}/user-storage`; + +/** + * Reset the in-memory storage. Call this in beforeEach to ensure clean test state. + */ +export function resetUserStorage(): void { + userStorageData = {}; +} + +/** + * Get the resource name for a given service, matching how UserStorage constructs it. + * This uses config.bootData.user to determine the user identifier. + * + * @param service - The service name (e.g., 'alerting') + * @returns The resource name in format `{service}:{userUID}` + * + * @example + * // In a test with config.bootData.user = { uid: '', id: 123 } + * const resourceName = getResourceName('alerting'); // 'alerting:123' + * + * // In a test with config.bootData.user = { uid: 'abc-123', id: 456 } + * const resourceName = getResourceName('alerting'); // 'alerting:abc-123' + */ +export function getResourceName(service: string): string { + const user = config.bootData?.user; + const userUID = user?.uid === '' || !user?.uid ? String(user?.id ?? 'anonymous') : user.uid; + return `${service}:${userUID}`; +} + +/** + * Convenience constant for the alerting service name. + * Use with getResourceName('alerting') or ALERTING_SERVICE directly. + */ +export const ALERTING_SERVICE = 'alerting'; + +/** + * Set up initial data in the UserStorage mock. + * @param resourceName - The resource name (e.g., 'alerting:123'). Use getResourceName() to construct this. + * @param key - The storage key + * @param value - The value to store + */ +export function setUserStorageItem(resourceName: string, key: string, value: string): void { + if (!userStorageData[resourceName]) { + userStorageData[resourceName] = { data: {} }; + } + userStorageData[resourceName].data[key] = value; +} + +/** + * Convenience function to set alerting storage items using the current config's user. + * This automatically constructs the resource name from config.bootData.user. + * + * @param key - The storage key (e.g., 'savedSearches') + * @param value - The value to store (will be stored as-is, caller should JSON.stringify if needed) + * + * @example + * // Set up saved searches for testing + * setAlertingStorageItem('savedSearches', JSON.stringify([{ id: '1', name: 'Test', query: 'state:firing', isDefault: false, createdAt: Date.now() }])); + */ +export function setAlertingStorageItem(key: string, value: string): void { + const resourceName = getResourceName(ALERTING_SERVICE); + setUserStorageItem(resourceName, key, value); +} + +/** + * Convenience function to get alerting storage items using the current config's user. + * + * @param key - The storage key (e.g., 'savedSearches') + * @returns The stored value or null if not found + */ +export function getAlertingStorageItem(key: string): string | null { + const resourceName = getResourceName(ALERTING_SERVICE); + return getUserStorageItem(resourceName, key); +} + +/** + * Get data from the UserStorage mock. + * @param resourceName - The resource name (e.g., 'alerting:123') + * @param key - The storage key + * @returns The stored value or null if not found + */ +export function getUserStorageItem(resourceName: string, key: string): string | null { + return userStorageData[resourceName]?.data[key] ?? null; +} + +/** + * Get the full storage spec for a resource. + * @param resourceName - The resource name + */ +export function getUserStorageSpec(resourceName: string): UserStorageSpec | null { + return userStorageData[resourceName] ?? null; +} + +/** + * MSW handler for GET UserStorage (retrieve stored data) + */ +const getUserStorageHandler = () => + http.get<{ resourceName: string }>(`${getBaseUrl()}/:resourceName`, ({ params }) => { + const spec = userStorageData[params.resourceName]; + + if (!spec) { + return HttpResponse.json({ message: 'Not found' }, { status: 404 }); + } + + return HttpResponse.json({ spec }); + }); + +/** + * MSW handler for POST UserStorage (create new storage) + */ +const createUserStorageHandler = () => + http.post(getBaseUrl(), async ({ request }) => { + const body = (await request.json()) as { + metadata: { name: string; labels: { user: string; service: string } }; + spec: UserStorageSpec; + }; + + const resourceName = body.metadata.name; + userStorageData[resourceName] = body.spec; + + return HttpResponse.json({ spec: body.spec }, { status: 201 }); + }); + +/** + * MSW handler for PATCH UserStorage (update existing storage) + */ +const patchUserStorageHandler = () => + http.patch<{ resourceName: string }>(`${getBaseUrl()}/:resourceName`, async ({ params, request }) => { + const body = (await request.json()) as { spec: UserStorageSpec }; + const resourceName = params.resourceName; + + if (!userStorageData[resourceName]) { + userStorageData[resourceName] = { data: {} }; + } + + // Merge the new data with existing data + userStorageData[resourceName].data = { + ...userStorageData[resourceName].data, + ...body.spec.data, + }; + + return HttpResponse.json({ spec: userStorageData[resourceName] }); + }); + +/** + * All UserStorage MSW handlers + */ +const handlers = [getUserStorageHandler(), createUserStorageHandler(), patchUserStorageHandler()]; + +export default handlers; diff --git a/public/app/features/alerting/unified/rule-list/RuleList.v2.test.tsx b/public/app/features/alerting/unified/rule-list/RuleList.v2.test.tsx index d4c445a2772..7985791cfa2 100644 --- a/public/app/features/alerting/unified/rule-list/RuleList.v2.test.tsx +++ b/public/app/features/alerting/unified/rule-list/RuleList.v2.test.tsx @@ -1,5 +1,5 @@ import { HttpResponse } from 'msw'; -import { render, testWithFeatureToggles } from 'test/test-utils'; +import { render, testWithFeatureToggles, waitFor } from 'test/test-utils'; import { byRole, byTestId } from 'testing-library-selector'; import { OrgRole } from '@grafana/data'; @@ -12,7 +12,8 @@ import { setGrafanaRuleGroupExportResolver } from '../mocks/server/configure'; import { alertingFactory } from '../mocks/server/db'; import { RulesFilter } from '../search/rulesSearchParser'; -import RuleList, { RuleListActions } from './RuleList.v2'; +import RuleListPage, { RuleListActions } from './RuleList.v2'; +import { loadDefaultSavedSearch } from './filter/useSavedSearches'; // This tests only checks if proper components are rendered, so we mock them // Both FilterView and GroupedView are tested in their own tests @@ -24,6 +25,30 @@ jest.mock('./GroupedView', () => ({ GroupedView: () =>
Grouped View
, })); +jest.mock('./filter/useSavedSearches', () => ({ + ...jest.requireActual('./filter/useSavedSearches'), + loadDefaultSavedSearch: jest.fn(), + useSavedSearches: jest.fn(() => ({ + savedSearches: [], + isLoading: false, + saveSearch: jest.fn(), + renameSearch: jest.fn(), + deleteSearch: jest.fn(), + setDefaultSearch: jest.fn(), + })), +})); + +const loadDefaultSavedSearchMock = loadDefaultSavedSearch as jest.MockedFunction; + +beforeEach(() => { + loadDefaultSavedSearchMock.mockResolvedValue(null); + // Clear session storage to ensure clean state for each test + // This prevents the "visited" flag from affecting subsequent tests + sessionStorage.clear(); + // Set the visited flag for non-default-search tests to prevent the hook from trying to load + sessionStorage.setItem('grafana.alerting.ruleList.visited', 'true'); +}); + const ui = { filterView: byTestId('filter-view'), groupedView: byTestId('grouped-view'), @@ -45,16 +70,16 @@ setupMswServer(); alertingFactory.dataSource.build({ name: 'Mimir', uid: 'mimir' }); alertingFactory.dataSource.build({ name: 'Prometheus', uid: 'prometheus' }); -describe('RuleList v2', () => { +describe('RuleListPage v2', () => { it('should show grouped view by default', () => { - render(); + render(); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); }); it('should show grouped view when invalid view parameter is provided', () => { - render(, { + render(, { historyOptions: { initialEntries: ['/?view=invalid'], }, @@ -65,35 +90,35 @@ describe('RuleList v2', () => { }); it('should show list view when "view=list" URL parameter is present', () => { - render(, { historyOptions: { initialEntries: ['/?view=list'] } }); + render(, { historyOptions: { initialEntries: ['/?view=list'] } }); expect(ui.filterView.get()).toBeInTheDocument(); expect(ui.groupedView.query()).not.toBeInTheDocument(); }); it('should show grouped view when only group filter is applied', () => { - render(, { historyOptions: { initialEntries: ['/?search=group:cpu-usage'] } }); + render(, { historyOptions: { initialEntries: ['/?search=group:cpu-usage'] } }); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); }); it('should show grouped view when only namespace filter is applied', () => { - render(, { historyOptions: { initialEntries: ['/?search=namespace:global'] } }); + render(, { historyOptions: { initialEntries: ['/?search=namespace:global'] } }); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); }); it('should show grouped view when both group and namespace filters are applied', () => { - render(, { historyOptions: { initialEntries: ['/?search=group:cpu-usage namespace:global'] } }); + render(, { historyOptions: { initialEntries: ['/?search=group:cpu-usage namespace:global'] } }); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); }); it('should show list view when group and namespace filters are combined with other filter types', () => { - render(, { + render(, { historyOptions: { initialEntries: ['/?search=group:cpu-usage namespace:global state:firing'] }, }); @@ -102,14 +127,14 @@ describe('RuleList v2', () => { }); it('should show grouped view when view parameter is empty', () => { - render(, { historyOptions: { initialEntries: ['/?view='] } }); + render(, { historyOptions: { initialEntries: ['/?view='] } }); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); }); it('should show grouped view when search parameter is empty', () => { - render(, { historyOptions: { initialEntries: ['/?search='] } }); + render(, { historyOptions: { initialEntries: ['/?search='] } }); expect(ui.groupedView.get()).toBeInTheDocument(); expect(ui.filterView.query()).not.toBeInTheDocument(); @@ -125,28 +150,28 @@ describe('RuleList v2', () => { { filterType: 'ruleHealth', searchQuery: 'health:error' }, { filterType: 'contactPoint', searchQuery: 'contactPoint:slack' }, ])('should show list view when %s filter is applied', ({ filterType, searchQuery }) => { - render(, { historyOptions: { initialEntries: [`/?search=${encodeURIComponent(searchQuery)}`] } }); + render(, { historyOptions: { initialEntries: [`/?search=${encodeURIComponent(searchQuery)}`] } }); expect(ui.filterView.get()).toBeInTheDocument(); expect(ui.groupedView.query()).not.toBeInTheDocument(); }); it('should show list view when "view=list" URL parameter is present with group filter', () => { - render(, { historyOptions: { initialEntries: ['/?view=list&search=group:cpu-usage'] } }); + render(, { historyOptions: { initialEntries: ['/?view=list&search=group:cpu-usage'] } }); expect(ui.filterView.get()).toBeInTheDocument(); expect(ui.groupedView.query()).not.toBeInTheDocument(); }); it('should show list view when "view=list" URL parameter is present with namespace filter', () => { - render(, { historyOptions: { initialEntries: ['/?view=list&search=namespace:global'] } }); + render(, { historyOptions: { initialEntries: ['/?view=list&search=namespace:global'] } }); expect(ui.filterView.get()).toBeInTheDocument(); expect(ui.groupedView.query()).not.toBeInTheDocument(); }); it('should show list view when "view=list" URL parameter is present with both group and namespace filters', () => { - render(, { + render(, { historyOptions: { initialEntries: ['/?view=list&search=group:cpu-usage namespace:global'] }, }); @@ -342,10 +367,10 @@ describe('RuleListActions', () => { }); }); -describe('RuleList v2 - View switching', () => { +describe('RuleListPage v2 - View switching', () => { it('should preserve both group and namespace filters when switching from list view to grouped view', async () => { // Start with list view and both group and namespace filters - const { user } = render(, { + const { user } = render(, { historyOptions: { initialEntries: ['/?view=list&search=group:cpu-usage namespace:global'] }, }); expect(ui.filterView.get()).toBeInTheDocument(); @@ -365,7 +390,7 @@ describe('RuleList v2 - View switching', () => { it('should clear all filters when switching from list view to grouped view with group, namespace and other filters', async () => { // Start with list view with all types of filters - const { user } = render(, { + const { user } = render(, { historyOptions: { initialEntries: ['/?view=list&search=group:cpu-usage namespace:global state:firing rule:"test"'], }, @@ -385,3 +410,86 @@ describe('RuleList v2 - View switching', () => { expect(ui.modeSelector.list.query()).not.toBeChecked(); }); }); +describe('RuleListPage v2 - Default search auto-apply', () => { + // These tests verify that the default search is applied at the page level, + // BEFORE child components mount, preventing double API requests. + + testWithFeatureToggles({ enable: ['alertingListViewV2', 'alertingSavedSearches'] }); + + beforeEach(() => { + // Clear the visited flag so the hook detects this as a first visit + sessionStorage.removeItem('grafana.alerting.ruleList.visited'); + // Clear mock call history between tests + loadDefaultSavedSearchMock.mockClear(); + }); + + it('should apply default search before rendering child components', async () => { + const mockDefaultSearch = { + id: '1', + name: 'My Default', + query: 'state:firing', + isDefault: true, + createdAt: Date.now(), + }; + + // Mock loadDefaultSavedSearch to return a default search + loadDefaultSavedSearchMock.mockResolvedValue(mockDefaultSearch); + + render(); + + // Wait for loadDefaultSavedSearch to be called + await waitFor(() => { + expect(loadDefaultSavedSearchMock).toHaveBeenCalled(); + }); + + // Wait for the filter view to render with the applied search + await waitFor(() => { + expect(ui.filterView.get()).toBeInTheDocument(); + }); + + // Verify the search input shows the applied search query + expect(ui.searchInput.get()).toHaveValue('state:firing'); + }); + + it('should not apply default search when URL already has search parameter', async () => { + const mockDefaultSearch = { + id: '1', + name: 'My Default', + query: 'state:firing', + isDefault: true, + createdAt: Date.now(), + }; + + // loadDefaultSavedSearch should not be called when URL has search param + loadDefaultSavedSearchMock.mockResolvedValue(mockDefaultSearch); + + render(, { + historyOptions: { initialEntries: ['/?search=label:team=backend'] }, + }); + + // Wait for the component to render + await waitFor(() => { + expect(ui.searchInput.get()).toBeInTheDocument(); + }); + + // Should show the URL's search, not the default + expect(ui.searchInput.get()).toHaveValue('label:team=backend'); + + // Verify loadDefaultSavedSearch was not called because filters are already active + // The hook should not execute at all when hasActiveFilters is true + expect(loadDefaultSavedSearchMock).not.toHaveBeenCalled(); + }); + + it('should render normally when no default search exists', async () => { + loadDefaultSavedSearchMock.mockResolvedValue(null); + + render(); + + // Wait for the component to render after checking for default search + await waitFor(() => { + expect(ui.groupedView.get()).toBeInTheDocument(); + }); + + expect(ui.searchInput.get()).toHaveValue(''); + }); +}); diff --git a/public/app/features/alerting/unified/rule-list/RuleList.v2.tsx b/public/app/features/alerting/unified/rule-list/RuleList.v2.tsx index e828b00fa16..284bd6ad757 100644 --- a/public/app/features/alerting/unified/rule-list/RuleList.v2.tsx +++ b/public/app/features/alerting/unified/rule-list/RuleList.v2.tsx @@ -18,6 +18,7 @@ import { FilterView } from './FilterView'; import { GroupedView } from './GroupedView'; import { RuleListPageTitle } from './RuleListPageTitle'; import RulesFilter from './filter/RulesFilter'; +import { useApplyDefaultSearch } from './filter/useApplyDefaultSearch'; function RuleList() { const { filterState } = useRulesFilter(); @@ -117,14 +118,16 @@ export function RuleListActions() { } export default function RuleListPage() { + const { isApplying } = useApplyDefaultSearch(); + return ( } - isLoading={false} + isLoading={isApplying} actions={} > - + {!isApplying && } ); } diff --git a/public/app/features/alerting/unified/rule-list/filter/InlineRenameInput.tsx b/public/app/features/alerting/unified/rule-list/filter/InlineRenameInput.tsx new file mode 100644 index 00000000000..ae2db9e7264 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/InlineRenameInput.tsx @@ -0,0 +1,146 @@ +import { css } from '@emotion/css'; +import { useEffect } from 'react'; +import { useForm } from 'react-hook-form'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { t } from '@grafana/i18n'; +import { Box, IconButton, Input, Stack, Text, useStyles2 } from '@grafana/ui'; + +import { useAppNotification } from '../../../../../core/copy/appNotification'; + +import { SavedSearch, isValidationError, validateSearchName } from './savedSearchesSchema'; + +// ============================================================================ +// Inline Rename Input (compact input with icon buttons for renaming) +// ============================================================================ + +export interface InlineRenameInputProps { + initialValue: string; + /** Callback to save the renamed search. Throws ValidationError on validation failure. */ + onSave: (name: string) => Promise; + onCancel: () => void; + savedSearches: SavedSearch[]; + excludeId: string; +} + +interface FormValues { + name: string; +} + +export function InlineRenameInput({ + initialValue, + onSave, + onCancel, + savedSearches, + excludeId, +}: InlineRenameInputProps) { + const styles = useStyles2(getStyles); + const notifyApp = useAppNotification(); + + const { + register, + handleSubmit, + setFocus, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues: { name: initialValue }, + }); + + // Focus and select input on mount using react-hook-form's setFocus + useEffect(() => { + setFocus('name', { shouldSelect: true }); + }, [setFocus]); + + const onSubmit = async (data: FormValues) => { + try { + await onSave(data.name.trim()); + } catch (error) { + // Check if it's a validation error (has field and message) + if (isValidationError(error)) { + // Validation errors are shown inline in the form + // This is handled by react-hook-form validation, but we keep this + // as a fallback for server-side validation errors + return; + } + // For generic save operation errors, show a notification + notifyApp.error( + t('alerting.saved-searches.error-rename-title', 'Failed to rename'), + t('alerting.saved-searches.error-rename-description', 'Your changes could not be saved. Please try again.') + ); + } + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Escape') { + e.preventDefault(); + onCancel(); + } + }; + + return ( + +
+ + {/* Input area - flex=1 like the name area in list items */} + + { + const error = validateSearchName(value, savedSearches, excludeId); + return error ?? true; + }, + })} + onKeyDown={handleKeyDown} + placeholder={t('alerting.saved-searches.name-placeholder', 'Enter a name...')} + invalid={!!errors.name} + disabled={isSubmitting} + /> + + + {/* X icon - cancel */} + + + {/* Check icon - confirm rename */} + {/* Note: IconButton doesn't forward type="submit", so we use onClick with handleSubmit */} + + +
+ {errors.name?.message && ( + + {errors.name.message} + + )} +
+ ); +} + +// ============================================================================ +// Styles +// ============================================================================ + +function getStyles(theme: GrafanaTheme2) { + return { + successIcon: css({ + color: theme.colors.success.main, + }), + }; +} diff --git a/public/app/features/alerting/unified/rule-list/filter/InlineSaveInput.tsx b/public/app/features/alerting/unified/rule-list/filter/InlineSaveInput.tsx new file mode 100644 index 00000000000..9fd11151cd0 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/InlineSaveInput.tsx @@ -0,0 +1,139 @@ +import { css } from '@emotion/css'; +import { useEffect } from 'react'; +import { useForm } from 'react-hook-form'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { t } from '@grafana/i18n'; +import { Box, IconButton, Input, Stack, Text, useStyles2 } from '@grafana/ui'; + +import { useAppNotification } from '../../../../../core/copy/appNotification'; + +import { SavedSearch, isValidationError, validateSearchName } from './savedSearchesSchema'; + +// ============================================================================ +// Inline Save Input (compact input with icon buttons) +// ============================================================================ + +export interface InlineSaveInputProps { + /** Callback to save the search. Throws ValidationError on validation failure. */ + onSave: (name: string) => Promise; + onCancel: () => void; + savedSearches: SavedSearch[]; +} + +interface FormValues { + name: string; +} + +export function InlineSaveInput({ onSave, onCancel, savedSearches }: InlineSaveInputProps) { + const styles = useStyles2(getStyles); + const notifyApp = useAppNotification(); + + const { + register, + handleSubmit, + setFocus, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues: { name: '' }, + }); + + // Focus input on mount using react-hook-form's setFocus + useEffect(() => { + setFocus('name'); + }, [setFocus]); + + const onSubmit = async (data: FormValues) => { + try { + await onSave(data.name.trim()); + } catch (error) { + // Check if it's a validation error (has field and message) + if (isValidationError(error)) { + // Validation errors are shown inline in the form + // This is handled by react-hook-form validation, but we keep this + // as a fallback for server-side validation errors + return; + } + // For generic save operation errors, show a notification + notifyApp.error( + t('alerting.saved-searches.error-save-title', 'Failed to save'), + t('alerting.saved-searches.error-save-description', 'Your changes could not be saved. Please try again.') + ); + } + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Escape') { + e.preventDefault(); + onCancel(); + } + }; + + return ( + + {/* Match exact structure of SavedSearchItem: [flex-1 content] [icon] [icon] with gap={1} */} +
+ + {/* Input area - flex=1 like the name area in list items */} + + { + const error = validateSearchName(value, savedSearches); + return error ?? true; + }, + })} + onKeyDown={handleKeyDown} + placeholder={t('alerting.saved-searches.name-placeholder', 'Enter a name...')} + invalid={!!errors.name} + disabled={isSubmitting} + /> + + + {/* X icon - aligned with magnifying glass */} + + + {/* Check icon - aligned with action menu */} + {/* Note: IconButton doesn't forward type="submit", so we use onClick with handleSubmit */} + + +
+ {errors.name?.message && ( + + {errors.name.message} + + )} +
+ ); +} + +// ============================================================================ +// Styles +// ============================================================================ + +function getStyles(theme: GrafanaTheme2) { + return { + successIcon: css({ + color: theme.colors.success.main, + }), + }; +} diff --git a/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.test.tsx b/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.test.tsx index a8f6c91cbc3..8da5901a4b8 100644 --- a/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.test.tsx +++ b/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.test.tsx @@ -1,8 +1,8 @@ -import { render, screen } from 'test/test-utils'; +import { render, screen, testWithFeatureToggles, waitFor } from 'test/test-utils'; import { byRole, byTestId } from 'testing-library-selector'; import { ComponentTypeWithExtensionMeta, PluginExtensionComponentMeta, PluginExtensionTypes } from '@grafana/data'; -import { config, locationService, setPluginComponentsHook } from '@grafana/runtime'; +import { locationService, setPluginComponentsHook } from '@grafana/runtime'; import { setupMswServer } from 'app/features/alerting/unified/mockApi'; import { grantUserPermissions } from 'app/features/alerting/unified/mocks'; import { AccessControlAction } from 'app/types/accessControl'; @@ -15,6 +15,51 @@ import { setupPluginsExtensionsHook } from '../../testSetup/plugins'; import RulesFilter from './RulesFilter'; +// Mock config for UserStorage (namespace and user must be set before UserStorage module loads) +// This allows the real UserStorage class to work with MSW handlers +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + reportInteraction: jest.fn(), // Silence analytics calls from useSavedSearches + getDataSourceSrv: () => ({ + getList: jest.fn().mockReturnValue([ + { name: 'Prometheus', uid: 'prometheus-uid' }, + { name: 'Loki', uid: 'loki-uid' }, + ]), + }), + config: { + ...jest.requireActual('@grafana/runtime').config, + namespace: 'default', + bootData: { + ...jest.requireActual('@grafana/runtime').config.bootData, + navTree: [], + user: { + uid: 'test-user-123', + id: 123, + isSignedIn: true, + }, + }, + }, +})); + +// Set up contextSrv.user.id for useSavedSearches session storage key. +// The hook uses this ID to create a per-user session storage key. +// Note: hasPermission must be mocked here because RulesFilter.v1.tsx calls it at module load time, +// before grantUserPermissions can set up the spy. grantUserPermissions still works for runtime checks. +jest.mock('app/core/services/context_srv', () => { + const actual = jest.requireActual('app/core/services/context_srv'); + return { + ...actual, + contextSrv: { + ...actual.contextSrv, + user: { + ...actual.contextSrv.user, + id: 123, + }, + hasPermission: jest.fn().mockReturnValue(true), + }, + }; +}); + // Grant permission before importing the component since permission check happens at module level grantUserPermissions([AccessControlAction.AlertingReceiversRead]); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -46,6 +91,7 @@ jest.mock('../../hooks/useFilteredRules', () => ({ const useRulesFilterMock = useRulesFilter as jest.MockedFunction; +// Set up MSW server with UserStorage handlers setupMswServer(); jest.spyOn(analytics, 'trackFilterButtonClick'); @@ -54,16 +100,6 @@ jest.spyOn(analytics, 'trackFilterButtonClearClick'); jest.spyOn(analytics, 'trackAlertRuleFilterEvent'); jest.spyOn(analytics, 'trackRulesSearchInputCleared'); -jest.mock('@grafana/runtime', () => ({ - ...jest.requireActual('@grafana/runtime'), - getDataSourceSrv: () => ({ - getList: jest.fn().mockReturnValue([ - { name: 'Prometheus', uid: 'prometheus-uid' }, - { name: 'Loki', uid: 'loki-uid' }, - ]), - }), -})); - jest.mock('../../components/rules/MultipleDataSourcePicker', () => { const original = jest.requireActual('../../components/rules/MultipleDataSourcePicker'); return { @@ -113,6 +149,8 @@ const ui = { beforeEach(() => { locationService.replace({ search: '' }); jest.clearAllMocks(); + sessionStorage.clear(); + localStorage.clear(); mockFilterState = { ruleName: '', @@ -150,45 +188,46 @@ beforeEach(() => { }); describe('RulesFilter Feature Flag', () => { - const originalFeatureToggle = config.featureToggles.alertingFilterV2; + describe('with alertingFilterV2 enabled', () => { + testWithFeatureToggles({ enable: ['alertingFilterV2'] }); - afterEach(() => { - config.featureToggles.alertingFilterV2 = originalFeatureToggle; + it('Should render RulesFilterV2 when alertingFilterV2 feature flag is enabled', async () => { + render(); + + // Wait for suspense to resolve and check that the V2 filter button is present + await screen.findByRole('button', { name: 'Filter' }); + expect(ui.filterButton.get()).toBeInTheDocument(); + expect(ui.searchInput.get()).toBeInTheDocument(); + }); }); - it('Should render RulesFilterV2 when alertingFilterV2 feature flag is enabled', async () => { - config.featureToggles.alertingFilterV2 = true; + describe('with alertingFilterV2 disabled', () => { + testWithFeatureToggles({ disable: ['alertingFilterV2'] }); - render(); + it('Should render RulesFilterV1 when alertingFilterV2 feature flag is disabled', async () => { + render(); - // Wait for suspense to resolve and check that the V2 filter button is present - await screen.findByRole('button', { name: 'Filter' }); - expect(ui.filterButton.get()).toBeInTheDocument(); - expect(ui.searchInput.get()).toBeInTheDocument(); - }); + // Wait for suspense to resolve and check V1 structure + await screen.findByText('Search'); - it('Should render RulesFilterV1 when alertingFilterV2 feature flag is disabled', async () => { - config.featureToggles.alertingFilterV2 = false; + // V1 has search input but no V2-style filter button + expect(ui.searchInput.get()).toBeInTheDocument(); + expect(ui.filterButton.query()).not.toBeInTheDocument(); - render(); - - // Wait for suspense to resolve and check V1 structure - await screen.findByText('Search'); - - // V1 has search input but no V2-style filter button - expect(ui.searchInput.get()).toBeInTheDocument(); - expect(ui.filterButton.query()).not.toBeInTheDocument(); - - // V1 has a help icon next to the search input - expect(screen.getByText('Search')).toBeInTheDocument(); + // V1 has a help icon next to the search input + expect(screen.getByText('Search')).toBeInTheDocument(); + }); }); }); describe('RulesFilterV2', () => { - it('Should render component without crashing', () => { + it('Should render component without crashing', async () => { render(); - expect(ui.searchInput.get()).toBeInTheDocument(); + // Wait for async hook operations (useSavedSearches) to complete + await waitFor(() => { + expect(ui.searchInput.get()).toBeInTheDocument(); + }); expect(ui.filterButton.get()).toBeInTheDocument(); }); @@ -429,4 +468,6 @@ describe('RulesFilterV2', () => { expect(analytics.trackFilterButtonClick).toHaveBeenCalledTimes(1); }); }); + + // Auto-apply of default search is tested in RuleList.v2.test.tsx (behavior is in RuleListPage) }); diff --git a/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.tsx b/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.tsx index 0091cdddec9..eb2e368ad80 100644 --- a/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.tsx +++ b/public/app/features/alerting/unified/rule-list/filter/RulesFilter.v2.tsx @@ -39,10 +39,14 @@ import { useLabelOptions, useNamespaceAndGroupOptions, } from '../../components/rules/Filter/useRuleFilterAutocomplete'; +import { shouldUseSavedSearches } from '../../featureToggles'; import { useRulesFilter } from '../../hooks/useFilteredRules'; import { RuleHealth, RuleSource, getSearchFilterFromQuery } from '../../search/rulesSearchParser'; import { RulesFilterProps } from './RulesFilter'; +import { SavedSearches } from './SavedSearches'; +import { SavedSearch } from './savedSearchesSchema'; +import { trackSavedSearchApplied, useSavedSearches } from './useSavedSearches'; import { emptyAdvancedFilters, formAdvancedFiltersToRuleFilter, @@ -86,6 +90,19 @@ export default function RulesFilter({ viewMode, onViewModeChange }: RulesFilterP const popupRef = useRef(null); const { pluginsFilterEnabled } = usePluginsFilterStatus(); + // Feature toggle for saved searches + const savedSearchesEnabled = shouldUseSavedSearches(); + + // Saved searches hook with UserStorage persistence + const { + savedSearches, + isLoading: savedSearchesLoading, + saveSearch, + renameSearch, + deleteSearch, + setDefaultSearch, + } = useSavedSearches(); + // this form will managed the search query string, which is updated either by the user typing in the input or by the advanced filters const { control, setValue, handleSubmit } = useForm({ defaultValues: { @@ -97,6 +114,20 @@ export default function RulesFilter({ viewMode, onViewModeChange }: RulesFilterP setValue('query', searchQuery); }, [searchQuery, setValue]); + // Apply saved search - triggers filtering (which updates search input and URL) + const handleApplySearch = useCallback( + (search: SavedSearch) => { + const parsedFilter = getSearchFilterFromQuery(search.query); + updateFilters(parsedFilter); + + // Track analytics + trackSavedSearchApplied(search); + }, + [updateFilters] + ); + + // Auto-apply of default search is handled in RuleListPage (before FilterView mounts) + const submitHandler: SubmitHandler = (values: SearchQueryForm) => { const parsedFilter = getSearchFilterFromQuery(values.query); trackAlertRuleFilterEvent({ filterMethod: 'search-input', filter: parsedFilter, filterVariant: 'v2' }); @@ -240,7 +271,21 @@ export default function RulesFilter({ viewMode, onViewModeChange }: RulesFilterP {filterButtonLabel} - + {savedSearchesEnabled && ( + + )} + + +
diff --git a/public/app/features/alerting/unified/rule-list/filter/SavedSearchItem.tsx b/public/app/features/alerting/unified/rule-list/filter/SavedSearchItem.tsx new file mode 100644 index 00000000000..0fb92622b2d --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/SavedSearchItem.tsx @@ -0,0 +1,226 @@ +import { css } from '@emotion/css'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { t } from '@grafana/i18n'; +import { Dropdown, Icon, IconButton, Menu, Stack, Text, useStyles2 } from '@grafana/ui'; + +import { InlineRenameInput } from './InlineRenameInput'; +import { SavedSearch } from './savedSearchesSchema'; + +// ============================================================================ +// Saved Search Item +// ============================================================================ + +export interface SavedSearchItemProps { + search: SavedSearch; + isRenaming: boolean; + isDeleting: boolean; + isDisabled: boolean; + onApply: () => void; + onStartRename: () => void; + onCancelRename: () => void; + onRenameComplete: (newName: string) => Promise; + onStartDelete: () => void; + onCancelDelete: () => void; + onDeleteConfirm: () => Promise; + onSetDefault: () => void; + savedSearches: SavedSearch[]; + /** Portal root for the action menu - should be the outer dropdown container */ + menuPortalRoot?: HTMLElement | null; +} + +export function SavedSearchItem({ + search, + isRenaming, + isDeleting, + isDisabled, + onApply, + onStartRename, + onCancelRename, + onRenameComplete, + onStartDelete, + onCancelDelete, + onDeleteConfirm, + onSetDefault, + savedSearches, + menuPortalRoot, +}: SavedSearchItemProps) { + const styles = useStyles2(getStyles); + + // Rename mode - inline form matching the save form + // Stop propagation to prevent parent Dropdown from closing when interacting with form + if (isRenaming) { + return ( + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions +
e.stopPropagation()}> + +
+ ); + } + + // Delete confirm mode - inline with name visible + // Stop propagation to prevent parent Dropdown from closing when interacting with delete confirmation + if (isDeleting) { + return ( + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions +
e.stopPropagation()}> + + {/* Name remains visible */} + + {search.name} + + + {/* X icon - cancel delete */} + + + {/* Trash icon - confirm delete */} + + +
+ ); + } + + // Default display mode + return ( +
+ + {/* Name and default indicator */} + + {search.name} + {search.isDefault && ( + + )} + + + {/* Apply button (magnifying glass) */} + + + {/* Action menu - stop propagation to prevent parent Dropdown from closing */} + {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */} +
e.stopPropagation()}> + +
+
+
+ ); +} + +// ============================================================================ +// Action Menu (three-dot menu) +// ============================================================================ + +interface ActionMenuProps { + isDefault: boolean; + isDisabled: boolean; + onSetDefault: () => void; + onRename: () => void; + onDelete: () => void; + /** Portal root for the menu - renders inside the outer dropdown to prevent useDismiss issues */ + portalRoot?: HTMLElement | null; +} + +function ActionMenu({ isDefault, isDisabled, onSetDefault, onRename, onDelete, portalRoot }: ActionMenuProps) { + const menu = ( + + + + + + + ); + + return ( + + + + ); +} + +// ============================================================================ +// Styles +// ============================================================================ + +function getStyles(theme: GrafanaTheme2) { + return { + item: css({ + padding: theme.spacing(0.5), + borderRadius: theme.shape.radius.default, + '&:hover': { + backgroundColor: theme.colors.action.hover, + }, + }), + defaultIcon: css({ + color: theme.colors.warning.main, + flexShrink: 0, + }), + deleteIcon: css({ + color: theme.colors.error.main, + }), + actionMenuWrapper: css({ + display: 'flex', + alignItems: 'center', + }), + }; +} diff --git a/public/app/features/alerting/unified/rule-list/filter/SavedSearches.README.md b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.README.md new file mode 100644 index 00000000000..8935cecaaa1 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.README.md @@ -0,0 +1,404 @@ +# Saved Searches Feature + +The Saved Searches feature allows users to save, manage, and quickly apply search queries on the Alert Rules page. + +## Overview + +Users can: + +- **Save** the current search query with a custom name +- **Apply** a saved search to instantly filter rules +- **Rename** existing saved searches +- **Delete** saved searches they no longer need +- **Set a default** search that auto-applies when navigating to the page + +## Components + +### `` + +The main component that renders a button and dropdown for managing saved searches. + +```tsx +import { SavedSearches } from './SavedSearches'; + +; +``` + +#### Props + +| Prop | Type | Required | Description | +| -------------------- | ------------------------------------------------------------------- | -------- | ------------------------------------------- | +| `savedSearches` | `SavedSearch[]` | Yes | Array of saved search objects | +| `currentSearchQuery` | `string` | Yes | The current search query in the input field | +| `onSave` | `(name: string, query: string) => Promise` | Yes | Called when user saves a new search | +| `onRename` | `(id: string, newName: string) => Promise` | Yes | Called when user renames a search | +| `onDelete` | `(id: string) => Promise` | Yes | Called when user deletes a search | +| `onApply` | `(search: SavedSearch) => void` | Yes | Called when user applies a search | +| `onSetDefault` | `(id: string \| null) => Promise` | Yes | Called when user sets/clears default | + +#### Types + +```typescript +interface SavedSearch { + /** Unique identifier */ + id: string; + /** User-provided name */ + name: string; + /** The search query string */ + query: string; + /** Whether this is the default search */ + isDefault: boolean; + /** Unix timestamp of creation */ + createdAt: number; +} + +interface ValidationError { + /** The field with the error */ + field: string; + /** Error message to display */ + message: string; +} +``` + +### `useSavedSearches()` Hook + +A custom hook that manages saved searches with UserStorage persistence. + +```tsx +import { useSavedSearches, trackSavedSearchApplied } from './useSavedSearches'; + +const { savedSearches, isLoading, saveSearch, renameSearch, deleteSearch, setDefaultSearch, getAutoApplySearch } = + useSavedSearches(); + +// Track when a search is applied +const handleApply = (search: SavedSearch) => { + applySearchToFilter(search.query); + trackSavedSearchApplied(search); +}; +``` + +#### Return Value + +| Property | Type | Description | +| -------------------- | --------------------------------------------------- | ------------------------------------- | +| `savedSearches` | `SavedSearch[]` | Current list of saved searches | +| `isLoading` | `boolean` | Whether initial load is in progress | +| `saveSearch` | `(name, query) => Promise` | Save a new search | +| `renameSearch` | `(id, newName) => Promise` | Rename an existing search | +| `deleteSearch` | `(id) => Promise` | Delete a search | +| `setDefaultSearch` | `(id \| null) => Promise` | Set or clear the default search | +| `getAutoApplySearch` | `() => SavedSearch \| null` | Get the default search for auto-apply | + +## Integration + +### Basic Integration + +```tsx +import { SavedSearches, SavedSearch } from './SavedSearches'; +import { useSavedSearches, trackSavedSearchApplied } from './useSavedSearches'; + +function MyFilterComponent() { + const { filterState, updateFilters } = useMyFilter(); + + const { savedSearches, saveSearch, renameSearch, deleteSearch, setDefaultSearch, getAutoApplySearch } = + useSavedSearches(); + + // Handle applying a saved search + const handleApply = useCallback( + (search: SavedSearch) => { + // Update your filter state with the saved query + updateFilters(parseQuery(search.query)); + + // Track analytics + trackSavedSearchApplied(search); + }, + [updateFilters] + ); + + // Auto-apply default search on navigation + useEffect(() => { + const defaultSearch = getAutoApplySearch(); + if (defaultSearch) { + handleApply(defaultSearch); + } + }, [getAutoApplySearch, handleApply]); + + return ( + + ); +} +``` + +### Feature Toggle + +The feature is gated behind the `alertingSavedSearches` feature toggle: + +```tsx +import { shouldUseSavedSearches } from '../../featureToggles'; + +function MyComponent() { + const savedSearchesEnabled = shouldUseSavedSearches(); + + return ( + <> + {savedSearchesEnabled && } + + ); +} +``` + +To enable during development, set in Grafana config: + +```ini +[feature_toggles] +alertingSavedSearches = true +``` + +## Behavior + +### Dropdown States + +1. **List Mode** (default) + - Shows saved searches sorted: default first, then alphabetical + - Shows "Save current search" button when `currentSearchQuery` is non-empty + - Empty state when no saved searches exist + +2. **Save Mode** + - Name input with validation + - Save/Cancel buttons + - Triggered by clicking "Save current search" + +3. **Rename Mode** (per-item) + - Inline editing of search name + - Confirm with Enter, cancel with Escape + +4. **Delete Confirmation** (per-item) + - Inline confirmation prompt + - Delete/Cancel buttons + +### Validation Rules + +| Rule | Message | +| ------------------------------ | ---------------------------------------------- | +| Name required | "Name is required" | +| Max length 64 | "Name must be 64 characters or less" | +| Unique name (case-insensitive) | "A saved search with this name already exists" | + +### Auto-Apply Default Search + +The default search auto-applies when: + +1. User **navigates** to the Alert Rules page (not on refresh) +2. No search query is present in the URL +3. A default search is configured + +This is tracked via `sessionStorage` to distinguish navigation from refresh. + +### Persistence + +Saved searches are stored using `UserStorage`: + +- **Backend API**: `/apis/userstorage.grafana.app/v0alpha1/namespaces/{namespace}/user-storage` +- **Fallback**: `localStorage` (when user not signed in or API fails) +- **Storage key**: `alerting.savedSearches` + +## Analytics + +The feature tracks the following events via `reportInteraction`: + +| Event | Properties | When | +| ------------------------------------------- | -------------------------- | -------------------- | +| `grafana_alerting_saved_search_save` | `hasDefault`, `totalCount` | Search saved | +| `grafana_alerting_saved_search_apply` | `isDefault` | Search applied | +| `grafana_alerting_saved_search_delete` | - | Search deleted | +| `grafana_alerting_saved_search_rename` | - | Search renamed | +| `grafana_alerting_saved_search_set_default` | `action: 'set' \| 'clear'` | Default changed | +| `grafana_alerting_saved_search_auto_apply` | - | Default auto-applied | + +## Testing + +### Component Tests + +Location: `SavedSearches.test.tsx` + +```bash +yarn test SavedSearches.test.tsx +``` + +Test categories: + +- **Rendering**: Button, dropdown, list sorting, empty state +- **Save functionality**: Validation, errors, success flow +- **Apply functionality**: Click handling, dropdown close +- **Action menu**: Set default, rename, delete options +- **Delete confirmation**: Confirm/cancel flows +- **Keyboard navigation**: Escape key handling +- **Edge cases**: Empty queries, whitespace trimming + +### Hook Tests + +Location: `useSavedSearches.test.tsx` + +```bash +yarn test useSavedSearches.test.tsx +``` + +Test categories: + +- **Initial loading**: Loading state, storage load, empty storage +- **saveSearch**: New search, duplicate detection, analytics +- **renameSearch**: Rename flow, duplicate detection +- **deleteSearch**: Delete flow, analytics +- **setDefaultSearch**: Set/clear default, analytics +- **getAutoApplySearch**: Navigation detection, URL check +- **Error handling**: Storage errors, notifications + +### Mocking UserStorage API with MSW + +The hook and component tests use MSW to mock the UserStorage API endpoints. +The handlers are defined in `mocks/server/handlers/userStorage.ts` and included via `setupMswServer()`: + +```typescript +import { setupMswServer, setAlertingStorageItem, getAlertingStorageItem } from 'app/features/alerting/unified/mockApi'; + +// Set up MSW server with UserStorage handlers (call at module level) +setupMswServer(); + +// In tests, use helper functions to set up storage data: +it('should load saved searches', async () => { + setAlertingStorageItem('savedSearches', JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.savedSearches).toEqual(mockSavedSearches); +}); + +// Verify persisted data: +it('should save a new search', async () => { + // ... perform save action ... + + const storedData = getAlertingStorageItem('savedSearches'); + expect(storedData).toContain('"name":"New Search"'); +}); +``` + +**Important**: Tests must mock `config.namespace` and `config.bootData.user` before imports, +so that `UserStorage` constructs the correct API URLs: + +```typescript +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + config: { + ...jest.requireActual('@grafana/runtime').config, + namespace: 'default', + bootData: { + ...jest.requireActual('@grafana/runtime').config.bootData, + user: { uid: 'test-user-123', id: 123, isSignedIn: true }, + }, + }, +})); +``` + +### Verifying Notifications in UI + +Tests verify error notifications by rendering the `AppNotificationList` component: + +```typescript +import { AppNotificationList } from 'app/core/components/AppNotifications/AppNotificationList'; +import { getWrapper, screen } from 'test/test-utils'; + +function createWrapper() { + const Wrapper = getWrapper({ renderWithRouter: true }); + return function WrapperWithNotifications({ children }) { + return ( + + + {children} + + ); + }; +} + +// In tests (e.g., malformed JSON triggers error notification): +it('should handle malformed JSON gracefully', async () => { + setAlertingStorageItem('savedSearches', 'not valid json'); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(await screen.findByText(/failed to load saved searches/i)).toBeInTheDocument(); +}); +``` + +## Accessibility + +- Dropdown has `role="dialog"` for screen readers +- Action menu uses `@grafana/ui` `Dropdown` and `Menu` components +- Keyboard support: + - `Escape`: Close dropdown or cancel current operation + - `Tab`: Navigate through interactive elements + - `Enter`: Confirm inputs + +## File Structure + +``` +public/app/features/alerting/unified/rule-list/filter/ +├── SavedSearches.tsx # Main component +├── SavedSearches.test.tsx # Component tests +├── SavedSearches.README.md # This documentation +├── useSavedSearches.ts # Custom hook with persistence +└── useSavedSearches.test.tsx # Hook tests +``` + +## Dependencies + +- `@grafana/ui`: Button, Dropdown, Menu, Icon, Input, Stack, Box, Spinner, PopupCard +- `@grafana/i18n`: Trans, t (internationalization) +- `@grafana/runtime`: reportInteraction +- `@grafana/runtime/internal`: UserStorage +- `@emotion/css`: Styling via useStyles2 + +## E2E Tests + +Location: `e2e-playwright/alerting-suite/saved-searches.spec.ts` + +```bash +yarn e2e:playwright --grep "saved-searches" +``` + +Test scenarios: + +- Display Saved searches button +- Open/close dropdown +- Empty state +- Save current search (enabled/disabled) +- Create new saved search +- Validation errors (duplicate name) +- Apply saved search +- Rename saved search +- Delete saved search +- Set as default +- Keyboard navigation (Escape to close/cancel) diff --git a/public/app/features/alerting/unified/rule-list/filter/SavedSearches.test.tsx b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.test.tsx new file mode 100644 index 00000000000..7e3604c5eec --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.test.tsx @@ -0,0 +1,348 @@ +import { render, screen, waitFor } from 'test/test-utils'; +import { byPlaceholderText, byRole, byText } from 'testing-library-selector'; + +import { SavedSearches } from './SavedSearches'; +import { SavedSearch } from './savedSearchesSchema'; + +/** + * UI selectors for SavedSearches component tests. + * Using testing-library-selector for reusable, consistent selectors. + */ +const ui = { + // Main trigger button + savedSearchesButton: byRole('button', { name: /saved searches/i }), + // Dropdown dialog + dropdown: byRole('dialog'), + // Save functionality + saveButton: byRole('button', { name: /save current search/i }), + saveConfirmButton: byRole('button', { name: /save$/i }), + saveInput: byPlaceholderText(/enter a name/i), + // Action buttons + cancelButton: byRole('button', { name: /cancel/i }), + applyButtons: byRole('button', { name: /apply this search/i }), + actionMenuButtons: byRole('button', { name: /actions/i }), + deleteButton: byRole('button', { name: /delete/i }), + // Menu items (using byRole for proper accessibility testing) + setAsDefaultMenuItem: byRole('menuitem', { name: /set as default/i }), + removeDefaultMenuItem: byRole('menuitem', { name: /remove default/i }), + renameMenuItem: byRole('menuitem', { name: /rename/i }), + deleteMenuItem: byRole('menuitem', { name: /^delete$/i }), + // Messages + emptyStateMessage: byText(/no saved searches/i), + nameRequiredError: byText(/name is required/i), + duplicateNameError: byText(/a saved search with this name already exists/i), +}; + +// Mock data is ordered as it will appear after sorting by useSavedSearches: +// default search first, then alphabetically by name +const mockSavedSearches: SavedSearch[] = [ + { + id: '2', + name: 'Default Search', + query: 'label:team=A', + isDefault: true, + createdAt: Date.now() - 2000, + }, + { + id: '3', + name: 'Critical Alerts', + query: 'label:severity=critical state:firing', + isDefault: false, + createdAt: Date.now() - 3000, + }, + { + id: '1', + name: 'My Firing Rules', + query: 'state:firing', + isDefault: false, + createdAt: Date.now() - 1000, + }, +]; + +const defaultProps = { + savedSearches: mockSavedSearches, + currentSearchQuery: '', + onSave: jest.fn(), + onRename: jest.fn(), + onDelete: jest.fn(), + onApply: jest.fn(), + onSetDefault: jest.fn(), +}; + +describe('SavedSearches', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('Displaying saved searches', () => { + it('shows empty state when no saved searches exist', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + + expect(ui.emptyStateMessage.get()).toBeInTheDocument(); + }); + + it('displays saved searches with default search marked with star icon', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + + // Verify searches are displayed + const applyButtons = await ui.applyButtons.findAll(); + expect(applyButtons).toHaveLength(3); + + // Verify the default search has a star icon + expect(screen.getByText('Default Search')).toBeInTheDocument(); + expect(screen.getByTitle('Default search')).toBeInTheDocument(); + }); + }); + + describe('Saving a search', () => { + it('saves current search with the provided name', async () => { + defaultProps.onSave.mockResolvedValue(undefined); + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + await user.type(await ui.saveInput.find(), 'My New Search'); + await user.click(ui.saveConfirmButton.get()); + + expect(defaultProps.onSave).toHaveBeenCalledWith('My New Search', 'state:pending'); + }); + + it('disables save button when currentSearchQuery is empty', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + + // Use findByText + closest because findByRole fails to find disabled Grafana Button + // (due to aria-disabled="false" + disabled="" attribute mismatch in Grafana UI) + const saveButtonText = await screen.findByText(/save current search/i); + // eslint-disable-next-line testing-library/no-node-access + const saveButton = saveButtonText.closest('button'); + expect(saveButton).toBeDisabled(); + }); + + it('shows validation error when name is empty', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + await user.click(await ui.saveConfirmButton.find()); + + expect(await ui.nameRequiredError.find()).toBeInTheDocument(); + }); + + it('shows validation error for duplicate name', async () => { + defaultProps.onSave.mockResolvedValue({ + field: 'name', + message: 'A saved search with this name already exists', + }); + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + await user.type(await ui.saveInput.find(), 'My Firing Rules'); + await user.click(ui.saveConfirmButton.get()); + + expect(await ui.duplicateNameError.find()).toBeInTheDocument(); + }); + + it('trims whitespace from search name before saving', async () => { + defaultProps.onSave.mockResolvedValue(undefined); + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + await user.type(await ui.saveInput.find(), ' My Search '); + await user.click(ui.saveConfirmButton.get()); + + expect(defaultProps.onSave).toHaveBeenCalledWith('My Search', 'state:pending'); + }); + + it('cancels save when cancel button is clicked', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + await user.click(await ui.cancelButton.find()); + + expect(defaultProps.onSave).not.toHaveBeenCalled(); + expect(ui.saveInput.query()).not.toBeInTheDocument(); + }); + }); + + describe('Applying a search', () => { + it('applies the selected search and closes dropdown', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + const applyButtons = await ui.applyButtons.findAll(); + // Click the apply button for "My Firing Rules" (third in list: Default, Critical, My Firing) + await user.click(applyButtons[2]); + + expect(defaultProps.onApply).toHaveBeenCalledWith( + expect.objectContaining({ + id: '1', + name: 'My Firing Rules', + query: 'state:firing', + }) + ); + + await waitFor(() => { + expect(ui.dropdown.query()).not.toBeInTheDocument(); + }); + }); + }); + + describe('Setting default search', () => { + it('sets a search as default', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + // Use a non-default search's menu (second item: "Critical Alerts") + const menuButtons = await ui.actionMenuButtons.findAll(); + await user.click(menuButtons[1]); + await user.click(await ui.setAsDefaultMenuItem.find()); + + expect(defaultProps.onSetDefault).toHaveBeenCalledWith('3'); + }); + + it('removes default from a search', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + // Default Search is first item (index 0) + const menuButtons = await ui.actionMenuButtons.findAll(); + await user.click(menuButtons[0]); + await user.click(await ui.removeDefaultMenuItem.find()); + + expect(defaultProps.onSetDefault).toHaveBeenCalledWith(null); + }); + }); + + describe('Renaming a search', () => { + it('renames a search successfully', async () => { + defaultProps.onRename.mockResolvedValue(undefined); + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + const menuButtons = await ui.actionMenuButtons.findAll(); + await user.click(menuButtons[0]); + await user.click(await ui.renameMenuItem.find()); + + const input = await screen.findByDisplayValue('Default Search'); + await user.clear(input); + await user.type(input, 'Renamed Search'); + await user.keyboard('{Enter}'); + + expect(defaultProps.onRename).toHaveBeenCalledWith('2', 'Renamed Search'); + }); + + it('shows validation error for duplicate name when renaming', async () => { + defaultProps.onRename.mockResolvedValue({ + field: 'name', + message: 'A saved search with this name already exists', + }); + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + const menuButtons = await ui.actionMenuButtons.findAll(); + await user.click(menuButtons[0]); + await user.click(await ui.renameMenuItem.find()); + + const input = await screen.findByDisplayValue('Default Search'); + await user.clear(input); + await user.type(input, 'My Firing Rules'); + await user.keyboard('{Enter}'); + + await waitFor(() => { + expect(ui.duplicateNameError.get()).toBeInTheDocument(); + }); + }); + }); + + describe('Deleting a search', () => { + it('deletes a search after confirmation', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + const menuButtons = await ui.actionMenuButtons.findAll(); + // Delete the first item (Default Search, id: '2') + await user.click(menuButtons[0]); + await user.click(await ui.deleteMenuItem.find()); + + // Confirm delete + const deleteButtons = await ui.deleteButton.findAll(); + await user.click(deleteButtons[deleteButtons.length - 1]); + + expect(defaultProps.onDelete).toHaveBeenCalledWith('2'); + }); + + it('cancels delete when cancel is clicked', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + const menuButtons = await ui.actionMenuButtons.findAll(); + await user.click(menuButtons[0]); + await user.click(await ui.deleteMenuItem.find()); + + await user.click(await ui.cancelButton.find()); + + expect(defaultProps.onDelete).not.toHaveBeenCalled(); + expect(screen.getByText('Default Search')).toBeInTheDocument(); + }); + }); + + describe('Keyboard navigation', () => { + it('closes dropdown when Escape is pressed', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + expect(await ui.dropdown.find()).toBeInTheDocument(); + + await user.keyboard('{Escape}'); + + await waitFor(() => { + expect(ui.dropdown.query()).not.toBeInTheDocument(); + }); + }); + + it('cancels save mode when Escape is pressed without closing dropdown', async () => { + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + await user.click(await ui.saveButton.find()); + expect(await ui.saveInput.find()).toBeInTheDocument(); + + await user.keyboard('{Escape}'); + + await waitFor(() => { + expect(ui.saveInput.query()).not.toBeInTheDocument(); + }); + // Dropdown should still be open + expect(ui.dropdown.get()).toBeInTheDocument(); + }); + }); + + describe('Edge cases', () => { + it('handles empty search query display gracefully', async () => { + const searchesWithEmptyQuery: SavedSearch[] = [ + { + id: '1', + name: 'Empty Search', + query: '', + isDefault: false, + createdAt: Date.now(), + }, + ]; + + const { user } = render(); + + await user.click(ui.savedSearchesButton.get()); + + expect(await screen.findByText('Empty Search')).toBeInTheDocument(); + }); + }); +}); diff --git a/public/app/features/alerting/unified/rule-list/filter/SavedSearches.tsx b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.tsx new file mode 100644 index 00000000000..0d4391642f0 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/SavedSearches.tsx @@ -0,0 +1,556 @@ +/** + * SavedSearches Component + * + * Allows users to save, manage, and quickly apply search queries on the Alert Rules page. + * + * ## Features + * - Save current search query with a custom name + * - Mark one search as "default" (auto-applied on navigation) + * - Rename, delete, and apply saved searches + * - Alphabetical sorting with default search pinned first + * + * ## Props + * @param savedSearches - Array of saved search objects + * @param currentSearchQuery - The current search query string from the filter state + * @param onSave - Callback to save a new search. Throws ValidationError on failure. + * @param onRename - Callback to rename an existing search. Throws ValidationError on failure. + * @param onDelete - Callback to delete a search + * @param onApply - Callback when a saved search is applied + * @param onSetDefault - Callback to set/unset default search (pass null to unset) + * @param disabled - Disables all interactions + * @param className - Additional CSS class name + * + * ## Internal States + * - Dropdown open/closed + * - Save mode (inputting new search name) + * - Rename mode (editing existing search name, by item ID) + * - Delete confirm mode (confirming deletion, by item ID) + * + * ## Accessibility + * - Uses role="dialog" for the dropdown panel + * - Basic keyboard navigation (Escape to close, Tab to navigate) + * - Focus moves to "Save current search" button when dropdown opens + * + * @example + * ```tsx + * + * ``` + */ + +import { css } from '@emotion/css'; +import { useCallback, useEffect, useReducer, useRef } from 'react'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { Trans, t } from '@grafana/i18n'; +import { Box, Button, Spinner, Stack, Text, useStyles2 } from '@grafana/ui'; + +import { PopupCard } from '../../components/HoverCard'; + +import { InlineSaveInput } from './InlineSaveInput'; +import { SavedSearchItem } from './SavedSearchItem'; +import { SavedSearch } from './savedSearchesSchema'; + +// ============================================================================ +// Types +// ============================================================================ + +export interface SavedSearchesProps { + /** Array of saved search objects */ + savedSearches: SavedSearch[]; + /** The current search query string from the filter state */ + currentSearchQuery: string; + /** Callback to save a new search. Throws ValidationError on failure. */ + onSave: (name: string, query: string) => Promise; + /** Callback to rename an existing search. Throws ValidationError on failure. */ + onRename: (id: string, newName: string) => Promise; + /** Callback to delete a search */ + onDelete: (id: string) => Promise; + /** Callback when a saved search is applied */ + onApply: (search: SavedSearch) => void; + /** Callback to set/unset default search. Pass null to remove default. */ + onSetDefault: (id: string | null) => Promise; + /** Whether saved searches are still loading from storage */ + isLoading?: boolean; + /** Additional CSS class name */ + className?: string; +} + +// ============================================================================ +// State Management (Reducer) +// ============================================================================ + +// Active action type - represents the current action in progress +type ActiveAction = 'idle' | { type: 'saving' } | { type: 'renaming'; id: string } | { type: 'deleting'; id: string }; + +// Component state +interface DropdownState { + isOpen: boolean; + activeAction: ActiveAction; +} + +// Action types for the reducer +type DropdownAction = + | { type: 'OPEN' } + | { type: 'CLOSE' } + | { type: 'SET_VISIBLE'; visible: boolean } + | { type: 'START_SAVE' } + | { type: 'START_RENAME'; id: string } + | { type: 'START_DELETE'; id: string } + | { type: 'CANCEL_ACTION' } + | { type: 'COMPLETE_ACTION' } + | { type: 'APPLY_AND_CLOSE' }; + +const initialState: DropdownState = { + isOpen: false, + activeAction: 'idle', +}; + +/** + * Reducer for managing dropdown state and active actions. + * Centralizes all state transitions for easier reasoning and testing. + */ +function dropdownReducer(state: DropdownState, action: DropdownAction): DropdownState { + switch (action.type) { + case 'OPEN': + return { ...state, isOpen: true }; + + case 'CLOSE': + // Reset action when closing + return { isOpen: false, activeAction: 'idle' }; + + case 'SET_VISIBLE': + // When visibility changes, reset action if closing + return action.visible ? { ...state, isOpen: true } : { isOpen: false, activeAction: 'idle' }; + + case 'START_SAVE': + // Only start save if no action is active + return state.activeAction === 'idle' ? { ...state, activeAction: { type: 'saving' } } : state; + + case 'START_RENAME': + // Only start rename if no action is active + return state.activeAction === 'idle' ? { ...state, activeAction: { type: 'renaming', id: action.id } } : state; + + case 'START_DELETE': + // Only start delete if no action is active + return state.activeAction === 'idle' ? { ...state, activeAction: { type: 'deleting', id: action.id } } : state; + + case 'CANCEL_ACTION': + case 'COMPLETE_ACTION': + // Return to idle state + return { ...state, activeAction: 'idle' }; + + case 'APPLY_AND_CLOSE': + // Only apply if no action is active, then close + return state.activeAction === 'idle' ? { isOpen: false, activeAction: 'idle' } : state; + + default: + return state; + } +} + +// ============================================================================ +// Main Component +// ============================================================================ + +export function SavedSearches({ + savedSearches, + currentSearchQuery, + onSave, + onRename, + onDelete, + onApply, + onSetDefault, + isLoading = false, + className, +}: SavedSearchesProps) { + const styles = useStyles2(getStyles); + + // Centralized state management via reducer + const [state, dispatch] = useReducer(dropdownReducer, initialState); + const { isOpen, activeAction } = state; + + // Refs + const saveButtonRef = useRef(null); + const dialogRef = useRef(null); + + // Focus dialog when dropdown opens to enable keyboard navigation + useEffect(() => { + if (isOpen && activeAction === 'idle') { + // Small delay to ensure the dropdown is rendered + const timer = setTimeout(() => { + // Focus the dialog to capture keyboard events (like Escape) + // We focus the dialog instead of the save button because the button may be disabled + dialogRef.current?.focus(); + }, 50); + return () => clearTimeout(timer); + } + return undefined; + }, [isOpen, activeAction]); + + // Handle click outside to close dropdown - excludes portal elements (like action menu) + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if (isOpen && dialogRef.current && event.target instanceof Node && !dialogRef.current.contains(event.target)) { + // Check if click is on a portal element (action menu dropdown) + if (event.target instanceof Element) { + const isPortalClick = + event.target.closest('[data-popper-placement]') || event.target.closest('[role="menu"]'); + + if (!isPortalClick) { + dispatch({ type: 'CLOSE' }); + } + } else { + dispatch({ type: 'CLOSE' }); + } + } + }; + + if (isOpen) { + document.addEventListener('mousedown', handleClickOutside); + } + + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [isOpen]); + + // Handle Escape key: cancel active action first, or close dropdown if no action is active + useEffect(() => { + const handleEscapeKey = (event: KeyboardEvent) => { + if (event.key === 'Escape' && isOpen) { + if (activeAction !== 'idle') { + dispatch({ type: 'CANCEL_ACTION' }); + } else { + dispatch({ type: 'CLOSE' }); + } + } + }; + + document.addEventListener('keydown', handleEscapeKey); + return () => document.removeEventListener('keydown', handleEscapeKey); + }, [isOpen, activeAction]); + + // Handlers + const handleToggle = useCallback(() => { + dispatch({ type: isOpen ? 'CLOSE' : 'OPEN' }); + }, [isOpen]); + + const handleClose = useCallback(() => { + dispatch({ type: 'CLOSE' }); + }, []); + + const handleStartSave = useCallback(() => { + dispatch({ type: 'START_SAVE' }); + }, []); + + const handleCancelSave = useCallback(() => { + dispatch({ type: 'CANCEL_ACTION' }); + }, []); + + const handleSaveComplete = useCallback( + async (name: string): Promise => { + await onSave(name, currentSearchQuery); + dispatch({ type: 'COMPLETE_ACTION' }); + }, + [onSave, currentSearchQuery] + ); + + const handleStartRename = useCallback((id: string) => { + dispatch({ type: 'START_RENAME', id }); + }, []); + + const handleCancelRename = useCallback(() => { + dispatch({ type: 'CANCEL_ACTION' }); + }, []); + + const handleRenameComplete = useCallback( + async (id: string, newName: string): Promise => { + await onRename(id, newName); + dispatch({ type: 'COMPLETE_ACTION' }); + }, + [onRename] + ); + + const handleStartDelete = useCallback((id: string) => { + dispatch({ type: 'START_DELETE', id }); + }, []); + + const handleCancelDelete = useCallback(() => { + dispatch({ type: 'CANCEL_ACTION' }); + }, []); + + const handleDeleteConfirm = useCallback( + async (id: string) => { + await onDelete(id); + dispatch({ type: 'COMPLETE_ACTION' }); + }, + [onDelete] + ); + + const handleApply = useCallback( + (search: SavedSearch) => { + // Only allow apply when no action is active (handled by reducer) + if (activeAction !== 'idle') { + return; + } + onApply(search); + dispatch({ type: 'APPLY_AND_CLOSE' }); + }, + [onApply, activeAction] + ); + + const handleSetDefault = useCallback( + async (id: string | null) => { + // Only allow set default when no action is active + if (activeAction !== 'idle') { + return; + } + await onSetDefault(id); + }, + [onSetDefault, activeAction] + ); + + const buttonLabel = t('alerting.saved-searches.button-label', 'Saved searches'); + const hasSearches = savedSearches.length > 0; + const canSave = currentSearchQuery.trim().length > 0; + + const content = ( +
+ +
+ ); + + return ( + + + + ); +} + +// ============================================================================ +// List Mode (shows saved searches or empty state) +// ============================================================================ + +interface ListModeProps { + searches: SavedSearch[]; + hasSearches: boolean; + canSave: boolean; + activeAction: ActiveAction; + saveButtonRef: React.RefObject; + isLoading: boolean; + onStartSave: () => void; + /** Callback to complete save. Throws ValidationError on validation failure. */ + onSaveComplete: (name: string) => Promise; + onCancelSave: () => void; + onApply: (search: SavedSearch) => void; + onStartRename: (id: string) => void; + onCancelRename: () => void; + /** Callback to complete rename. Throws ValidationError on validation failure. */ + onRenameComplete: (id: string, newName: string) => Promise; + onStartDelete: (id: string) => void; + onCancelDelete: () => void; + onDeleteConfirm: (id: string) => Promise; + onSetDefault: (id: string | null) => Promise; + savedSearches: SavedSearch[]; + /** Portal root for action menus - renders inside the dropdown to prevent useDismiss issues */ + menuPortalRoot: HTMLElement | null; +} + +function ListMode({ + searches, + hasSearches, + canSave, + activeAction, + saveButtonRef, + isLoading, + onStartSave, + onSaveComplete, + onCancelSave, + onApply, + onStartRename, + onCancelRename, + onRenameComplete, + onStartDelete, + onCancelDelete, + onDeleteConfirm, + onSetDefault, + savedSearches, + menuPortalRoot, +}: ListModeProps) { + const styles = useStyles2(getStyles); + + // Derived states from activeAction + const isSaveMode = typeof activeAction === 'object' && activeAction.type === 'saving'; + const isActionActive = activeAction !== 'idle'; + + // Show loading state + if (isLoading) { + return ( + + + + ); + } + + return ( + + {/* Save current search - button or inline input */} + {/* Stop propagation to prevent Dropdown from closing when interacting with save form */} + {isSaveMode ? ( + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions +
e.stopPropagation()}> + +
+ ) : ( + + + + )} + + {/* Empty state or list */} + {!hasSearches ? ( + + ) : ( + +
+ {searches.map((search) => { + const isRenaming = + typeof activeAction === 'object' && activeAction.type === 'renaming' && activeAction.id === search.id; + const isDeleting = + typeof activeAction === 'object' && activeAction.type === 'deleting' && activeAction.id === search.id; + // Item is disabled if any action is active and this item is not the one being acted upon + const isItemDisabled = isActionActive && !isRenaming && !isDeleting; + + return ( + onApply(search)} + onStartRename={() => onStartRename(search.id)} + onCancelRename={onCancelRename} + onRenameComplete={(newName) => onRenameComplete(search.id, newName)} + onStartDelete={() => onStartDelete(search.id)} + onCancelDelete={onCancelDelete} + onDeleteConfirm={() => onDeleteConfirm(search.id)} + onSetDefault={() => onSetDefault(search.isDefault ? null : search.id)} + savedSearches={savedSearches} + menuPortalRoot={menuPortalRoot} + /> + ); + })} +
+
+ )} +
+ ); +} + +// ============================================================================ +// Empty State +// ============================================================================ + +function EmptyState() { + return ( + + + No saved searches yet + + + ); +} + +// ============================================================================ +// Styles +// ============================================================================ + +function getStyles(theme: GrafanaTheme2) { + return { + dropdown: css({ + width: '320px', + padding: theme.spacing(0.5), + }), + list: css({ + maxHeight: '300px', + overflowY: 'auto', + }), + item: css({ + padding: theme.spacing(0.5), + borderRadius: theme.shape.radius.default, + '&:hover': { + backgroundColor: theme.colors.action.hover, + }, + }), + }; +} diff --git a/public/app/features/alerting/unified/rule-list/filter/savedSearchesSchema.ts b/public/app/features/alerting/unified/rule-list/filter/savedSearchesSchema.ts new file mode 100644 index 00000000000..807ce421957 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/savedSearchesSchema.ts @@ -0,0 +1,87 @@ +/** + * Shared types and utilities for SavedSearches feature. + * + * This module is extracted to avoid circular dependencies between: + * - SavedSearches.tsx (main component) + * - InlineSaveInput.tsx, InlineRenameInput.tsx, SavedSearchItem.tsx (sub-components) + * - useSavedSearches.ts (hook) + */ + +import z from 'zod'; + +import { t } from '@grafana/i18n'; + +// ============================================================================ +// Schemas +// ============================================================================ + +/** + * Zod schema for validating a saved search object. + * Used to validate data loaded from storage. + */ +export const savedSearchSchema = z.object({ + id: z.string(), + name: z.string(), + isDefault: z.boolean(), + query: z.string(), + createdAt: z.number().optional(), +}); + +/** + * Zod schema for validating an array of saved searches. + */ +export const savedSearchesArraySchema = z.array(savedSearchSchema); + +// ============================================================================ +// Types +// ============================================================================ + +export type SavedSearch = z.infer; + +export interface ValidationError { + field: 'name'; + message: string; +} + +/** + * Type guard to check if an error is a ValidationError. + */ +export function isValidationError(error: unknown): error is ValidationError { + return Boolean( + error && + typeof error === 'object' && + 'field' in error && + 'message' in error && + error.field === 'name' && + typeof error.message === 'string' + ); +} + +// ============================================================================ +// Validation Utilities +// ============================================================================ + +/** + * Validates a saved search name. + * @param name - The name to validate + * @param savedSearches - Existing saved searches for uniqueness check + * @param excludeId - Optional ID to exclude from uniqueness check (for rename) + * @returns Error message string or null if valid + */ +export function validateSearchName(name: string, savedSearches: SavedSearch[], excludeId?: string): string | null { + const trimmed = name.trim(); + + if (!trimmed) { + return t('alerting.saved-searches.error-name-required', 'Name is required'); + } + + const isDuplicate = savedSearches.some( + (s) => (excludeId ? s.id !== excludeId : true) && s.name.toLowerCase() === trimmed.toLowerCase() + ); + + if (isDuplicate) { + return t('alerting.saved-searches.error-name-duplicate', 'A saved search with this name already exists'); + } + + return null; +} diff --git a/public/app/features/alerting/unified/rule-list/filter/useApplyDefaultSearch.ts b/public/app/features/alerting/unified/rule-list/filter/useApplyDefaultSearch.ts new file mode 100644 index 00000000000..380702fed16 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/useApplyDefaultSearch.ts @@ -0,0 +1,86 @@ +import { useEffect } from 'react'; + +import { shouldUseSavedSearches } from '../../featureToggles'; +import { useAsync } from '../../hooks/useAsync'; +import { useRulesFilter } from '../../hooks/useFilteredRules'; +import { getSearchFilterFromQuery } from '../../search/rulesSearchParser'; + +import { loadDefaultSavedSearch, trackSavedSearchAutoApply } from './useSavedSearches'; + +/** + * Session storage key to track if user has visited this page in current session. + * Used to determine if we should auto-apply the default saved search. + */ +const SESSION_VISITED_KEY = 'grafana.alerting.ruleList.visited'; + +/** + * Hook that automatically applies the default saved search on first visit to the page. + * + * This hook: + * - Checks if saved searches feature is enabled + * - Detects if this is the first visit in the current session + * - Loads and applies the default saved search if one exists + * - Cleans up session storage on unmount + * + * @returns Object with isApplying boolean indicating if the default search is being loaded/applied + */ +export function useApplyDefaultSearch(): { isApplying: boolean } { + const savedSearchesEnabled = shouldUseSavedSearches(); + const { updateFilters, hasActiveFilters } = useRulesFilter(); + + // Use the internal useAsync hook which doesn't auto-execute + const [{ execute }, state] = useAsync(async () => { + const defaultSearch = await loadDefaultSavedSearch(); + if (defaultSearch) { + updateFilters(getSearchFilterFromQuery(defaultSearch.query)); + trackSavedSearchAutoApply(); + } + }); + + // Clear session storage on unmount + useEffect(() => { + return () => { + clearSessionVisitedFlag(); + }; + }, []); + + const isFirstVisit = isFirstVisitInSession(); + const shouldLoadDefault = savedSearchesEnabled && !hasActiveFilters && isFirstVisit; + + // Mark as visited on first visit, regardless of whether we load defaults + if (isFirstVisit && state.status === 'not-executed') { + markAsVisited(); + + // Execute only if we should load default + if (shouldLoadDefault) { + execute(); + } + } + + return { isApplying: state.status === 'loading' }; +} + +/** + * Check if this is a fresh navigation to the page (not a refresh or in-page URL change). + * Uses session storage which persists across refreshes but clears when tab is closed. + * + * @returns true if this is the first visit to the page in this session + */ +function isFirstVisitInSession(): boolean { + return !sessionStorage.getItem(SESSION_VISITED_KEY); +} + +/** + * Mark the page as visited in the current session. + */ +function markAsVisited(): void { + sessionStorage.setItem(SESSION_VISITED_KEY, 'true'); +} + +/** + * Clear the session visited flag. Call this when component unmounts + * so the next navigation to this page is detected as a fresh visit. + */ +function clearSessionVisitedFlag(): void { + sessionStorage.removeItem(SESSION_VISITED_KEY); +} diff --git a/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.test.tsx b/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.test.tsx new file mode 100644 index 00000000000..4ea83f1e38a --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.test.tsx @@ -0,0 +1,400 @@ +import { PropsWithChildren } from 'react'; +import { act, getWrapper, renderHook, screen, waitFor } from 'test/test-utils'; + +import * as runtime from '@grafana/runtime'; +import { AppNotificationList } from 'app/core/components/AppNotifications/AppNotificationList'; +import { setupMswServer } from 'app/features/alerting/unified/mockApi'; + +// Create mock UserStorage instance that can be configured per test +const mockUserStorage = { + getItem: jest.fn(), + setItem: jest.fn(), +}; + +// Mock UserStorage class from @grafana/runtime/internal +// This prevents the module-level instance from caching state across tests +jest.mock('@grafana/runtime/internal', () => ({ + ...jest.requireActual('@grafana/runtime/internal'), + UserStorage: jest.fn().mockImplementation(() => mockUserStorage), +})); + +// Mock config BEFORE any imports that use it (jest.mock is hoisted) +// This ensures config.namespace and config.bootData.user are set when UserStorage module loads +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + reportInteraction: jest.fn(), + config: { + ...jest.requireActual('@grafana/runtime').config, + namespace: 'default', + bootData: { + ...jest.requireActual('@grafana/runtime').config.bootData, + navTree: [], + user: { + uid: 'test-user-123', + id: 123, + isSignedIn: true, + }, + }, + }, +})); + +import { trackSavedSearchApplied, useSavedSearches } from './useSavedSearches'; + +// Set up MSW server for other handlers (not UserStorage - that's mocked directly) +setupMswServer(); + +// Mock data is ordered as it will appear after sorting by useSavedSearches: +// default search first, then alphabetically by name +const mockSavedSearches = [ + { + id: '2', + name: 'Default Search', + query: 'label:team=A', + isDefault: true, + createdAt: Date.now() - 2000, + }, + { + id: '1', + name: 'Test Search 1', + query: 'state:firing', + isDefault: false, + createdAt: Date.now() - 1000, + }, +]; + +// Wrapper that includes AppNotificationList to verify UI notifications +function createWrapper() { + const Wrapper = getWrapper({ renderWithRouter: true }); + return function WrapperWithNotifications({ children }: PropsWithChildren) { + return ( + + + {children} + + ); + }; +} + +describe('useSavedSearches', () => { + beforeEach(() => { + jest.clearAllMocks(); + sessionStorage.clear(); + localStorage.clear(); + // Reset mock UserStorage to default behavior (empty storage) + mockUserStorage.getItem.mockResolvedValue(null); + mockUserStorage.setItem.mockResolvedValue(undefined); + }); + + describe('Initial loading', () => { + it('should load saved searches from UserStorage', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.savedSearches).toEqual(mockSavedSearches); + }); + + it('should handle empty storage gracefully', async () => { + // Storage is empty by default after resetUserStorage() in afterEach + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.savedSearches).toEqual([]); + }); + + it('should handle 404 (no stored data) gracefully', async () => { + // When no data exists, UserStorage returns 404, which is handled as "not found" + // The hook should return an empty array without error + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + // UserStorage handles 404 gracefully - returns empty storage + expect(result.current.savedSearches).toEqual([]); + }); + + it('should filter out invalid saved search entries', async () => { + jest.spyOn(console, 'warn').mockImplementation(); + const mixedData = [ + mockSavedSearches[0], // Valid + { id: '3', name: 'Invalid', query: 123, isDefault: false }, // Invalid query type + { id: '4', name: null, query: 'valid', isDefault: false }, // Invalid name type + mockSavedSearches[1], // Valid + ]; + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mixedData)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + // Invalid entries are filtered out, valid ones are preserved + expect(result.current.savedSearches).toHaveLength(2); + expect(result.current.savedSearches[0].name).toBe('Default Search'); + expect(result.current.savedSearches[1].name).toBe('Test Search 1'); + }); + + it('should handle malformed JSON gracefully', async () => { + jest.spyOn(console, 'error').mockImplementation(); + mockUserStorage.getItem.mockResolvedValue('not valid json'); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + // Verify error notification appears in the UI + expect(await screen.findByText(/failed to load saved searches/i)).toBeInTheDocument(); + expect(result.current.savedSearches).toEqual([]); + }); + }); + + describe('saveSearch', () => { + it('should save a new search', async () => { + // Start with empty storage (default mock behavior) + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.saveSearch('New Search', 'state:pending'); + }); + + expect(result.current.savedSearches).toHaveLength(1); + expect(result.current.savedSearches[0].name).toBe('New Search'); + expect(result.current.savedSearches[0].query).toBe('state:pending'); + + // Verify data was persisted via UserStorage.setItem + expect(mockUserStorage.setItem).toHaveBeenCalledWith( + 'savedSearches', + expect.stringContaining('"name":"New Search"') + ); + }); + + it('should throw validation error for duplicate name (case-insensitive)', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await expect(result.current.saveSearch('TEST SEARCH 1', 'state:pending')).rejects.toEqual({ + field: 'name', + message: expect.stringContaining('already exists'), + }); + }); + }); + + it('should track analytics on save', async () => { + // Start with empty storage + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.saveSearch('New Search', 'state:pending'); + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith( + 'grafana_alerting_saved_search_save', + expect.objectContaining({ + hasDefault: false, + totalCount: 1, + }) + ); + }); + }); + + describe('renameSearch', () => { + it('should rename an existing search', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.renameSearch('1', 'Renamed Search'); + }); + + expect(result.current.savedSearches.find((s) => s.id === '1')?.name).toBe('Renamed Search'); + + // Verify data was persisted via UserStorage.setItem + expect(mockUserStorage.setItem).toHaveBeenCalledWith( + 'savedSearches', + expect.stringContaining('"name":"Renamed Search"') + ); + }); + + it('should throw validation error for duplicate name on rename', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await expect(result.current.renameSearch('1', 'Default Search')).rejects.toEqual({ + field: 'name', + message: expect.stringContaining('already exists'), + }); + }); + }); + }); + + describe('deleteSearch', () => { + it('should delete a search', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + expect(result.current.savedSearches).toHaveLength(2); + + await act(async () => { + await result.current.deleteSearch('1'); + }); + + expect(result.current.savedSearches).toHaveLength(1); + expect(result.current.savedSearches.find((s) => s.id === '1')).toBeUndefined(); + }); + + it('should track analytics on delete', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.deleteSearch('1'); + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith('grafana_alerting_saved_search_delete'); + }); + }); + + describe('setDefaultSearch', () => { + it('should set a search as default', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.setDefaultSearch('1'); + }); + + expect(result.current.savedSearches.find((s) => s.id === '1')?.isDefault).toBe(true); + expect(result.current.savedSearches.find((s) => s.id === '2')?.isDefault).toBe(false); + }); + + it('should clear default when null is passed', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.setDefaultSearch(null); + }); + + expect(result.current.savedSearches.every((s) => !s.isDefault)).toBe(true); + }); + + it('should track analytics with correct action', async () => { + mockUserStorage.getItem.mockResolvedValue(JSON.stringify(mockSavedSearches)); + + const { result } = renderHook(() => useSavedSearches(), { wrapper: createWrapper() }); + + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + }); + + await act(async () => { + await result.current.setDefaultSearch('1'); + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith('grafana_alerting_saved_search_set_default', { + action: 'set', + }); + + jest.clearAllMocks(); + + await act(async () => { + await result.current.setDefaultSearch(null); + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith('grafana_alerting_saved_search_set_default', { + action: 'clear', + }); + }); + }); +}); + +describe('trackSavedSearchApplied', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should track with isDefault true for default searches', () => { + trackSavedSearchApplied({ + id: '1', + name: 'Default', + query: 'state:firing', + isDefault: true, + createdAt: Date.now(), + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith('grafana_alerting_saved_search_apply', { isDefault: true }); + }); + + it('should track with isDefault false for non-default searches', () => { + trackSavedSearchApplied({ + id: '1', + name: 'Regular', + query: 'state:firing', + isDefault: false, + createdAt: Date.now(), + }); + + expect(runtime.reportInteraction).toHaveBeenCalledWith('grafana_alerting_saved_search_apply', { isDefault: false }); + }); +}); diff --git a/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.ts b/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.ts new file mode 100644 index 00000000000..5c81ce990b3 --- /dev/null +++ b/public/app/features/alerting/unified/rule-list/filter/useSavedSearches.ts @@ -0,0 +1,353 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { v4 as uuidv4 } from 'uuid'; + +import { t } from '@grafana/i18n'; +import { reportInteraction } from '@grafana/runtime'; +import { UserStorage } from '@grafana/runtime/internal'; + +import { useAppNotification } from '../../../../../core/copy/appNotification'; +import { logError, logWarning } from '../../Analytics'; +import { isLoading as isLoadingState, isUninitialized, useAsync } from '../../hooks/useAsync'; + +import { SavedSearch, savedSearchSchema, savedSearchesArraySchema, validateSearchName } from './savedSearchesSchema'; + +/** + * Storage key for saved searches in UserStorage. + */ +const SAVED_SEARCHES_STORAGE_KEY = 'savedSearches'; + +/** + * UserStorage instance for saved searches. + * Uses 'alerting' as the service namespace. + */ +const userStorage = new UserStorage('alerting'); + +/** + * Analytics tracking functions for saved search actions. + */ +function trackSavedSearchSave(props: { hasDefault: boolean; totalCount: number }) { + reportInteraction('grafana_alerting_saved_search_save', props); +} + +function trackSavedSearchApply(props: { isDefault: boolean }) { + reportInteraction('grafana_alerting_saved_search_apply', props); +} + +function trackSavedSearchDelete() { + reportInteraction('grafana_alerting_saved_search_delete'); +} + +function trackSavedSearchRename() { + reportInteraction('grafana_alerting_saved_search_rename'); +} + +function trackSavedSearchSetDefault(props: { action: 'set' | 'clear' }) { + reportInteraction('grafana_alerting_saved_search_set_default', props); +} + +export function trackSavedSearchAutoApply() { + reportInteraction('grafana_alerting_saved_search_auto_apply'); +} + +/** + * Validates and parses an array of saved searches using zod schema. + * Returns valid entries and logs warnings for invalid data. + */ +function validateSavedSearches(data: unknown): SavedSearch[] { + const result = savedSearchesArraySchema.safeParse(data); + + if (result.success) { + return result.data; + } + + // If the whole array failed, try to salvage individual valid entries + if (!Array.isArray(data)) { + logWarning('Saved searches data is not an array, returning empty array'); + return []; + } + + logWarning('Saved searches validation failed, filtering invalid entries', { + issues: JSON.stringify(result.error.issues), + }); + + const validEntries: SavedSearch[] = []; + for (const item of data) { + const itemResult = savedSearchSchema.safeParse(item); + if (itemResult.success) { + validEntries.push(itemResult.data); + } + } + return validEntries; +} + +/** + * Sorts saved searches: default search first, then others alphabetically. + * @param searches - Array of saved searches to sort + * @returns Sorted array with default first, then alphabetically by name + */ +function sortSavedSearches(searches: SavedSearch[]): SavedSearch[] { + const defaultSearch = searches.find((s) => s.isDefault); + const collator = new Intl.Collator(undefined, { sensitivity: 'base' }); + const others = searches.filter((s) => !s.isDefault).sort((a, b) => collator.compare(a.name, b.name)); + + return defaultSearch ? [defaultSearch, ...others] : others; +} + +/** + * Loads saved searches from UserStorage and validates the data. + * @returns Promise resolving to an array of valid saved searches + */ +async function loadSavedSearchesFromStorage(): Promise { + const stored = await userStorage.getItem(SAVED_SEARCHES_STORAGE_KEY); + if (!stored) { + return []; + } + + const parsed = JSON.parse(stored); + return validateSavedSearches(parsed); +} + +export async function loadDefaultSavedSearch(): Promise { + const savedSearches = await loadSavedSearchesFromStorage(); + return savedSearches.find((s) => s.isDefault) ?? null; +} + +/** + * Result of the useSavedSearches hook. + */ +export interface UseSavedSearchesResult { + /** List of saved searches */ + savedSearches: SavedSearch[]; + /** Whether the initial load from storage is complete */ + isLoading: boolean; + /** + * Save a new search with the given name and query. + * @param name - The display name for the saved search + * @param query - The search query string + * @throws ValidationError if name is not unique + */ + saveSearch: (name: string, query: string) => Promise; + /** + * Rename an existing saved search. + * @param id - The ID of the search to rename + * @param newName - The new display name + * @throws ValidationError if name is not unique + */ + renameSearch: (id: string, newName: string) => Promise; + /** + * Delete a saved search by ID. + * @param id - The ID of the search to delete + */ + deleteSearch: (id: string) => Promise; + /** + * Set or clear the default search. + * @param id - The ID to set as default, or null to clear + */ + setDefaultSearch: (id: string | null) => Promise; +} + +/** + * Hook for managing saved searches with UserStorage persistence. + * + * Features: + * - Persists saved searches to UserStorage (syncs across devices) + * - Validates data schema on load (filters invalid entries) + * - Validates name uniqueness (case-insensitive) + * - Tracks analytics for all actions + * - Shows error notifications on storage failures + * - Provides auto-apply logic for default search on navigation + * - Per-user session tracking to handle logout/login scenarios + * + * @example + * ```tsx + * const { savedSearches, saveSearch, isLoading } = useSavedSearches(); + * + * // Save current search + * const error = await saveSearch('My Search', currentQuery); + * if (error) { + * // Handle validation error + * } + * + * // Auto-apply default search on mount + * useEffect(() => { + * const defaultSearch = getAutoApplySearch(); + * if (defaultSearch) { + * applySearch(defaultSearch); + * } + * }, []); + * ``` + */ +export function useSavedSearches(): UseSavedSearchesResult { + const [savedSearches, setSavedSearches] = useState([]); + const notifyApp = useAppNotification(); + + // Track whether we've already loaded to prevent double-loading + const hasLoadedRef = useRef(false); + + // Use useAsync for loading state management + const [{ execute: executeLoad }, loadState] = useAsync(loadSavedSearchesFromStorage, []); + const isLoading = isLoadingState(loadState) || isUninitialized(loadState); + + // Load saved searches from storage on mount + useEffect(() => { + if (hasLoadedRef.current) { + return; + } + hasLoadedRef.current = true; + + // Load from UserStorage using async/await pattern + const loadSearches = async () => { + try { + const validated = await executeLoad(); + setSavedSearches(validated); + } catch (error) { + logError(error instanceof Error ? error : new Error('Failed to load saved searches from storage'), { + context: 'useSavedSearches.loadSearches', + }); + notifyApp.error( + t('alerting.saved-searches.error-load-title', 'Failed to load saved searches'), + t( + 'alerting.saved-searches.error-load-description', + 'Your saved searches could not be loaded. Please try refreshing the page.' + ) + ); + } + }; + + loadSearches(); + }, [executeLoad, notifyApp]); + + /** + * Persist saved searches to UserStorage. + */ + const persistSearches = useCallback( + async (searches: SavedSearch[]): Promise => { + try { + await userStorage.setItem(SAVED_SEARCHES_STORAGE_KEY, JSON.stringify(searches)); + } catch (error) { + logError(error instanceof Error ? error : new Error('Failed to save searches'), { + context: 'useSavedSearches.persistSearches', + }); + notifyApp.error( + t('alerting.saved-searches.error-save-title', 'Failed to save'), + t('alerting.saved-searches.error-save-description', 'Your changes could not be saved. Please try again.') + ); + throw error; + } + }, + [notifyApp] + ); + + /** + * Save a new search with the given name and query. + * @throws ValidationError if the name is not unique + */ + const saveSearch = useCallback( + async (name: string, query: string): Promise => { + // Validate name using shared validation function + const validationError = validateSearchName(name, savedSearches); + if (validationError) { + throw { field: 'name' as const, message: validationError }; + } + + const newSearch: SavedSearch = { + id: uuidv4(), + name, + query, + isDefault: false, + createdAt: Date.now(), + }; + + const newSearches = [...savedSearches, newSearch]; + + await persistSearches(newSearches); + setSavedSearches(newSearches); + + // Track analytics + trackSavedSearchSave({ + hasDefault: newSearches.some((s) => s.isDefault), + totalCount: newSearches.length, + }); + }, + [savedSearches, persistSearches] + ); + + /** + * Rename an existing saved search. + * @throws ValidationError if the new name is not unique + */ + const renameSearch = useCallback( + async (id: string, newName: string): Promise => { + // Validate name using shared validation function (excluding current item) + const validationError = validateSearchName(newName, savedSearches, id); + if (validationError) { + throw { field: 'name' as const, message: validationError }; + } + + const newSearches = savedSearches.map((s) => (s.id === id ? { ...s, name: newName } : s)); + + await persistSearches(newSearches); + setSavedSearches(newSearches); + + // Track analytics + trackSavedSearchRename(); + }, + [savedSearches, persistSearches] + ); + + /** + * Delete a saved search by ID. + */ + const deleteSearch = useCallback( + async (id: string): Promise => { + const newSearches = savedSearches.filter((s) => s.id !== id); + + await persistSearches(newSearches); + setSavedSearches(newSearches); + + // Track analytics + trackSavedSearchDelete(); + }, + [savedSearches, persistSearches] + ); + + /** + * Set or clear the default search. + * Pass null to clear the current default. + */ + const setDefaultSearch = useCallback( + async (id: string | null): Promise => { + const newSearches = savedSearches.map((s) => ({ + ...s, + isDefault: id === null ? false : s.id === id, + })); + + await persistSearches(newSearches); + setSavedSearches(newSearches); + + // Track analytics + trackSavedSearchSetDefault({ action: id === null ? 'clear' : 'set' }); + }, + [savedSearches, persistSearches] + ); + + // Sort saved searches: default first, then alphabetically by name + const sortedSavedSearches = useMemo(() => sortSavedSearches(savedSearches), [savedSearches]); + + return { + savedSearches: sortedSavedSearches, + isLoading, + saveSearch, + renameSearch, + deleteSearch, + setDefaultSearch, + }; +} + +/** + * Track when a saved search is applied (called from parent component). + * @param search - The search that was applied + */ +export function trackSavedSearchApplied(search: SavedSearch) { + trackSavedSearchApply({ isDefault: search.isDefault }); +} diff --git a/public/app/features/dashboard-scene/panel-edit/PanelEditor.tsx b/public/app/features/dashboard-scene/panel-edit/PanelEditor.tsx index 85813a99f6d..e656a39e6a1 100644 --- a/public/app/features/dashboard-scene/panel-edit/PanelEditor.tsx +++ b/public/app/features/dashboard-scene/panel-edit/PanelEditor.tsx @@ -120,7 +120,7 @@ export class PanelEditor extends SceneObjectBase { dataObject.subscribeToState(async () => { const { data } = dataObject.state; if (hasData(data) && panel.state.pluginId === UNCONFIGURED_PANEL_PLUGIN_ID) { - const suggestions = await getAllSuggestions(data); + const { suggestions } = await getAllSuggestions(data); if (suggestions.length > 0) { const defaultFirstSuggestion = suggestions[0]; diff --git a/public/app/features/dashboard-scene/scene/DashboardScene.tsx b/public/app/features/dashboard-scene/scene/DashboardScene.tsx index 82a20dbcd52..7ddd7c4e779 100644 --- a/public/app/features/dashboard-scene/scene/DashboardScene.tsx +++ b/public/app/features/dashboard-scene/scene/DashboardScene.tsx @@ -59,6 +59,7 @@ import { gridItemToGridLayoutItemKind } from '../serialization/layoutSerializers import { getElement } from '../serialization/layoutSerializers/utils'; import { buildGridItemForPanel, transformSaveModelToScene } from '../serialization/transformSaveModelToScene'; import { gridItemToPanel } from '../serialization/transformSceneToSaveModel'; +import { JsonModelEditView } from '../settings/JsonModelEditView'; import { DecoratedRevisionModel } from '../settings/VersionsEditView'; import { DashboardEditView } from '../settings/utils'; import { historySrv } from '../settings/version-history/HistorySrv'; @@ -855,30 +856,54 @@ export class DashboardScene extends SceneObjectBase impleme return this.serializer.getSaveModel(this); } - // Get the dashboard in native K8s form (using the appropriate apiVersion) - getSaveResource(options: SaveDashboardAsOptions): ResourceForCreate { + // Helper method to build K8s resource structure + private buildResourceForCreate(spec: Dashboard | DashboardV2Spec, isNew: boolean): ResourceForCreate { const { meta } = this.state; - const spec = this.getSaveAsModel(options); - - const apiVersion = this.serializer instanceof V2DashboardSerializer ? 'v2beta1' : 'v1beta1'; // get from the dashboard? + const apiVersion = this.serializer instanceof V2DashboardSerializer ? 'v2beta1' : 'v1beta1'; return { apiVersion: `dashboard.grafana.app/${apiVersion}`, kind: 'Dashboard', metadata: { ...meta.k8s, - name: options.isNew ? undefined : (meta.uid ?? meta.k8s?.name), - generateName: options.isNew ? 'd' : undefined, + name: isNew ? undefined : (meta.uid ?? meta.k8s?.name), + generateName: isNew ? 'd' : undefined, }, spec, }; } + // Get the dashboard in native K8s form (using the appropriate apiVersion) + getSaveResource(options: SaveDashboardAsOptions): ResourceForCreate { + const spec = this.getSaveAsModel(options); + return this.buildResourceForCreate(spec, options.isNew ?? false); + } + + // Wrap a raw dashboard spec in K8s resource format + // Used by JSON model editor for Git sync dashboards + getSaveResourceFromSpec(rawSpec: Dashboard | DashboardV2Spec): ResourceForCreate { + return this.buildResourceForCreate(rawSpec, false); + } + + // Get raw JSON from JSON model editor if currently active + // Returns undefined if not in JSON editor mode or if JSON is invalid + getRawJsonFromEditor(): Dashboard | DashboardV2Spec | undefined { + if (this.state.editview instanceof JsonModelEditView) { + try { + return JSON.parse(this.state.editview.state.jsonText); + } catch { + return undefined; + } + } + return undefined; + } + getSaveAsModel(options: SaveDashboardAsOptions): Dashboard | DashboardV2Spec { return this.serializer.getSaveAsModel(this, options); } getDashboardChanges(saveTimeRange?: boolean, saveVariables?: boolean, saveRefresh?: boolean): DashboardChangeInfo { - return this.serializer.getDashboardChangesFromScene(this, { saveTimeRange, saveVariables, saveRefresh }); + const rawJson = this.getRawJsonFromEditor(); + return this.serializer.getDashboardChangesFromScene(this, { saveTimeRange, saveVariables, saveRefresh, rawJson }); } getManagerKind(): ManagerKind | undefined { diff --git a/public/app/features/dashboard-scene/scene/dashboard-controls-menu/utils.tsx b/public/app/features/dashboard-scene/scene/dashboard-controls-menu/utils.tsx index 6514ea34ed9..04d0f7078c8 100644 --- a/public/app/features/dashboard-scene/scene/dashboard-controls-menu/utils.tsx +++ b/public/app/features/dashboard-scene/scene/dashboard-controls-menu/utils.tsx @@ -5,11 +5,7 @@ import { isDashboardDataLayerSetState } from '../DashboardDataLayerSet'; import { DashboardScene } from '../DashboardScene'; export function getDashboardControlsLinks(links: DashboardLink[]) { - // Dashboard links are not supported at the moment. - // Reason: nesting components causes issues since the inner dropdown is rendered in a portal, - // so clicking it closes the parent dropdown (the parent sees it as an overlay click, and the event cannot easily be intercepted, - // as it is in different HTML subtree). - return links.filter((link) => link.placement === 'inControlsMenu' && link.type !== 'dashboards'); + return links.filter((link) => link.placement === 'inControlsMenu'); } export function getDashboardControlsVariables(variables: SceneVariable[]) { diff --git a/public/app/features/dashboard-scene/serialization/DashboardSceneSerializer.ts b/public/app/features/dashboard-scene/serialization/DashboardSceneSerializer.ts index cede8f605a5..130c5450bf0 100644 --- a/public/app/features/dashboard-scene/serialization/DashboardSceneSerializer.ts +++ b/public/app/features/dashboard-scene/serialization/DashboardSceneSerializer.ts @@ -46,6 +46,7 @@ export interface DashboardSceneSerializerLike DashboardChangeInfo; onSaveComplete(saveModel: T, result: SaveDashboardResponseDTO): void; @@ -184,9 +185,15 @@ export class V1DashboardSerializer getDashboardChangesFromScene( scene: DashboardScene, - options: { saveTimeRange?: boolean; saveVariables?: boolean; saveRefresh?: boolean } + options: { + saveTimeRange?: boolean; + saveVariables?: boolean; + saveRefresh?: boolean; + rawJson?: Dashboard | DashboardV2Spec; + } ) { - const changedSaveModel = this.getSaveModel(scene); + const changedSaveModel = + options.rawJson && !isDashboardV2Spec(options.rawJson) ? options.rawJson : this.getSaveModel(scene); const changeInfo = getRawDashboardChanges( this.initialSaveModel!, changedSaveModel, @@ -396,9 +403,15 @@ export class V2DashboardSerializer getDashboardChangesFromScene( scene: DashboardScene, - options: { saveTimeRange?: boolean; saveVariables?: boolean; saveRefresh?: boolean } + options: { + saveTimeRange?: boolean; + saveVariables?: boolean; + saveRefresh?: boolean; + rawJson?: Dashboard | DashboardV2Spec; + } ) { - const changedSaveModel = this.getSaveModel(scene); + const changedSaveModel = + options.rawJson && isDashboardV2Spec(options.rawJson) ? options.rawJson : this.getSaveModel(scene); const changeInfo = getRawDashboardV2Changes( this.initialSaveModel!, changedSaveModel, diff --git a/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.test.ts b/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.test.ts index 6d0c450add3..4dcc732fb01 100644 --- a/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.test.ts +++ b/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.test.ts @@ -1,4 +1,4 @@ -import { VariableRefresh } from '@grafana/data'; +import { VariableRefresh, PanelData, LoadingState, toDataFrame, FieldType, getDefaultTimeRange } from '@grafana/data'; import { config } from '@grafana/runtime'; import { AdHocFiltersVariable, @@ -18,6 +18,8 @@ import { VizPanel, SceneDataQuery, SceneQueryRunner, + SceneDataTransformer, + SceneDataNode, sceneUtils, dataLayers, } from '@grafana/scenes'; @@ -33,6 +35,7 @@ import { TabsLayoutSpec, defaultDataQueryKind, } from '@grafana/schema/dist/esm/schema/dashboard/v2'; +import { GrafanaQueryType } from 'app/plugins/datasource/grafana/types'; import { DashboardEditPane } from '../edit-pane/DashboardEditPane'; import { DashboardAnnotationsDataLayer } from '../scene/DashboardAnnotationsDataLayer'; @@ -954,6 +957,103 @@ describe('getVizPanelQueries', () => { expect(result[1].spec.query.group).toBe('prometheus'); expect(result[1].spec.query.version).toBe('v0'); }); + + describe('snapshot mode', () => { + it('should return empty queries when isSnapshot is true but panel has no data provider', () => { + const vizPanel = new VizPanel({ + key: 'panel-1', + pluginId: 'timeseries', + // No $data provider + }); + + const result = getVizPanelQueries(vizPanel, undefined, true); + expect(result).toEqual([]); + }); + + it('should create snapshot query from SceneQueryRunner data when isSnapshot is true', () => { + const mockDataFrame = toDataFrame({ + name: 'test-series', + fields: [ + { name: 'time', type: FieldType.time, values: [1000, 2000, 3000] }, + { name: 'value', type: FieldType.number, values: [1, 2, 3] }, + ], + }); + + const panelData: PanelData = { + series: [mockDataFrame], + state: LoadingState.Done, + timeRange: getDefaultTimeRange(), + }; + + const queryRunner = new SceneQueryRunner({ + queries: [], + data: panelData, + }); + + const vizPanel = new VizPanel({ + key: 'panel-1', + pluginId: 'timeseries', + $data: queryRunner, + }); + + const result = getVizPanelQueries(vizPanel, undefined, true); + + expect(result).toHaveLength(1); + expect(result[0].kind).toBe('PanelQuery'); + expect(result[0].spec.refId).toBe('A'); + expect(result[0].spec.hidden).toBe(false); + expect(result[0].spec.query.kind).toBe('DataQuery'); + expect(result[0].spec.query.version).toBe(defaultDataQueryKind().version); + expect(result[0].spec.query.group).toBe('grafana'); + expect(result[0].spec.query.datasource).toEqual({ name: 'grafana' }); + expect(result[0].spec.query.spec.queryType).toBe(GrafanaQueryType.Snapshot); + expect(result[0].spec.query.spec.snapshot).toBeDefined(); + expect(result[0].spec.query.spec.snapshot).toHaveLength(1); + expect(result[0].spec.query.spec.snapshot[0].schema?.fields).toBeDefined(); + }); + + it('should create snapshot query from SceneDataTransformer data when isSnapshot is true', () => { + const mockDataFrame = toDataFrame({ + name: 'transformed-series', + fields: [ + { name: 'time', type: FieldType.time, values: [1000, 2000] }, + { name: 'transformed', type: FieldType.number, values: [10, 20] }, + ], + }); + + const panelData: PanelData = { + series: [mockDataFrame], + state: LoadingState.Done, + timeRange: getDefaultTimeRange(), + }; + + const dataNode = new SceneDataNode({ + data: panelData, + }); + + const dataTransformer = new SceneDataTransformer({ + $data: dataNode, + transformations: [], + }); + + const vizPanel = new VizPanel({ + key: 'panel-1', + pluginId: 'timeseries', + $data: dataTransformer, + }); + + const result = getVizPanelQueries(vizPanel, undefined, true); + + expect(result).toHaveLength(1); + expect(result[0].kind).toBe('PanelQuery'); + expect(result[0].spec.query.kind).toBe('DataQuery'); + expect(result[0].spec.query.spec.queryType).toBe(GrafanaQueryType.Snapshot); + expect(result[0].spec.query.spec.snapshot).toBeDefined(); + expect(result[0].spec.query.spec.snapshot).toHaveLength(1); + // Verify it gets data from the nested $data (SceneDataNode) not the transformer + expect(result[0].spec.query.spec.snapshot[0].schema?.fields).toBeDefined(); + }); + }); }); function getMinimalSceneState(body: DashboardLayoutManager): Partial { diff --git a/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.ts b/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.ts index 4a63c62af93..0ef2a5e5f05 100644 --- a/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.ts +++ b/public/app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2.ts @@ -13,8 +13,10 @@ import { SceneVariableSet, VizPanel, } from '@grafana/scenes'; -import { DataSourceRef, VariableRefresh } from '@grafana/schema'; +import { DataSourceRef } from '@grafana/schema'; import { sortedDeepCloneWithoutNulls } from 'app/core/utils/object'; +import { getPanelDataFrames } from 'app/features/dashboard/components/HelpWizard/utils'; +import { GrafanaQueryType } from 'app/plugins/datasource/grafana/types'; import { Spec as DashboardV2Spec, @@ -127,7 +129,7 @@ export function transformSceneToSaveModelSchemaV2(scene: DashboardScene, isSnaps // EOF variables // elements - elements: getElements(scene, dsReferencesMapping), + elements: getElements(scene, dsReferencesMapping, isSnapshot), // EOF elements // annotations @@ -170,17 +172,18 @@ function getLiveNow(state: DashboardSceneState) { return Boolean(liveNow); } -function getElements(scene: DashboardScene, dsReferencesMapping?: DSReferencesMapping) { +function getElements(scene: DashboardScene, dsReferencesMapping?: DSReferencesMapping, isSnapshot = false) { const panels = scene.state.body.getVizPanels() ?? []; const panelsArray = panels.map((vizPanel) => { - return vizPanelToSchemaV2(vizPanel, dsReferencesMapping); + return vizPanelToSchemaV2(vizPanel, dsReferencesMapping, isSnapshot); }); return createElements(panelsArray, scene); } export function vizPanelToSchemaV2( vizPanel: VizPanel, - dsReferencesMapping?: DSReferencesMapping + dsReferencesMapping?: DSReferencesMapping, + isSnapshot = false ): PanelKind | LibraryPanelKind { if (isLibraryPanel(vizPanel)) { const behavior = getLibraryPanelBehavior(vizPanel)!; @@ -216,7 +219,7 @@ export function vizPanelToSchemaV2( data: { kind: 'QueryGroup', spec: { - queries: getVizPanelQueries(vizPanel, dsReferencesMapping), + queries: getVizPanelQueries(vizPanel, dsReferencesMapping, isSnapshot), transformations: getVizPanelTransformations(vizPanel), queryOptions: getVizPanelQueryOptions(vizPanel), }, @@ -290,9 +293,51 @@ function getPanelLinks(panel: VizPanel): DataLink[] { return []; } -export function getVizPanelQueries(vizPanel: VizPanel, dsReferencesMapping?: DSReferencesMapping): PanelQueryKind[] { +export function getVizPanelQueries( + vizPanel: VizPanel, + dsReferencesMapping?: DSReferencesMapping, + isSnapshot = false +): PanelQueryKind[] { const queries: PanelQueryKind[] = []; const queryRunner = getQueryRunnerFor(vizPanel); + + if (isSnapshot) { + const dataProvider = vizPanel.state.$data; + if (!dataProvider) { + return queries; + } + + let snapshotData = getPanelDataFrames(dataProvider.state.data); + if (dataProvider instanceof SceneDataTransformer) { + snapshotData = getPanelDataFrames(dataProvider.state.$data!.state.data); + } + + const snapshotQuery: DataQueryKind = { + kind: 'DataQuery', + version: defaultDataQueryKind().version, + group: 'grafana', + datasource: { + name: 'grafana', + }, + spec: { + queryType: GrafanaQueryType.Snapshot, + snapshot: snapshotData, + }, + }; + + queries.push({ + kind: 'PanelQuery', + spec: { + query: snapshotQuery, + refId: 'A', + hidden: false, + }, + }); + + return queries; + } + + // Regular query handling (non-snapshot) const vizPanelQueries = queryRunner?.state.queries; if (vizPanelQueries) { @@ -631,15 +676,16 @@ export function trimDashboardForSnapshot(title: string, time: TimeRange, dash: D if (spec.variables) { spec.variables.forEach((variable) => { - if ('query' in variable) { - variable.query = ''; + if ('query' in variable.spec) { + variable.spec.query = ''; } - if ('options' in variable && 'current' in variable) { - variable.options = variable.current && !isEmptyObject(variable.current) ? [variable.current] : []; + if ('options' in variable.spec && 'current' in variable.spec) { + variable.spec.options = + variable.spec.current && !isEmptyObject(variable.spec.current) ? [variable.spec.current] : []; } - if ('refresh' in variable) { - variable.refresh = VariableRefresh.never; + if ('refresh' in variable.spec) { + variable.spec.refresh = 'never'; } }); } diff --git a/public/app/features/dashboard-scene/settings/JsonModelEditView.tsx b/public/app/features/dashboard-scene/settings/JsonModelEditView.tsx index 30979075d2a..99522077ae3 100644 --- a/public/app/features/dashboard-scene/settings/JsonModelEditView.tsx +++ b/public/app/features/dashboard-scene/settings/JsonModelEditView.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { GrafanaTheme2, PageLayoutType } from '@grafana/data'; import { Trans, t } from '@grafana/i18n'; -import { SceneComponentProps, SceneObjectBase, sceneUtils } from '@grafana/scenes'; +import { SceneComponentProps, SceneObjectBase, SceneObjectRef, sceneUtils } from '@grafana/scenes'; import { Dashboard } from '@grafana/schema'; import { Spec as DashboardV2Spec } from '@grafana/schema/dist/esm/schema/dashboard/v2'; import { Alert, Box, Button, CodeEditor, Stack, useStyles2 } from '@grafana/ui'; @@ -11,8 +11,10 @@ import { Page } from 'app/core/components/Page/Page'; import { getDashboardAPI } from 'app/features/dashboard/api/dashboard_api'; import { isDashboardV2Spec } from 'app/features/dashboard/api/utils'; import { getPrettyJSON } from 'app/features/inspector/utils/utils'; +import { useIsProvisionedNG } from 'app/features/provisioning/hooks/useIsProvisionedNG'; import { DashboardDataDTO, SaveDashboardResponseDTO } from 'app/types/dashboard'; +import { SaveDashboardDrawer } from '../saving/SaveDashboardDrawer'; import { NameAlreadyExistsError, isNameExistsError, @@ -105,12 +107,21 @@ function JsonModelEditViewComponent({ model }: SceneComponentProps { + if (isProvisionedNG) { + const drawer = new SaveDashboardDrawer({ + dashboardRef: new SceneObjectRef(dashboard), + }); + dashboard.setState({ overlay: drawer }); + return; + } + const result = await onSaveDashboard(dashboard, { folderUid: dashboard.state.meta.folderUid, overwrite, @@ -136,7 +147,7 @@ function JsonModelEditViewComponent({ model }: SceneComponentProps {overwrite ? ( - 'Save and overwrite' + Save and overwrite ) : ( Save changes )} diff --git a/public/app/features/dashboard-scene/settings/variables/editors/QueryVariableEditor.tsx b/public/app/features/dashboard-scene/settings/variables/editors/QueryVariableEditor.tsx index c32bc8eda8d..3f0583d3245 100644 --- a/public/app/features/dashboard-scene/settings/variables/editors/QueryVariableEditor.tsx +++ b/public/app/features/dashboard-scene/settings/variables/editors/QueryVariableEditor.tsx @@ -265,7 +265,7 @@ export function Editor({ variable }: { variable: QueryVariable }) { htmlFor="data-source-picker" noMargin > - + {selectedDatasource && VariableQueryEditor && ( diff --git a/public/app/features/expressions/components/SqlExpressions/SchemaInspector/SchemaInspectorPanel.tsx b/public/app/features/expressions/components/SqlExpressions/SchemaInspector/SchemaInspectorPanel.tsx index c84bf0d4223..a065bbc779f 100644 --- a/public/app/features/expressions/components/SqlExpressions/SchemaInspector/SchemaInspectorPanel.tsx +++ b/public/app/features/expressions/components/SqlExpressions/SchemaInspector/SchemaInspectorPanel.tsx @@ -1,25 +1,24 @@ import { css } from '@emotion/css'; -import { useState, useMemo } from 'react'; +import { useMemo, useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { t, Trans } from '@grafana/i18n'; import { - Stack, - Tab, - TabsBar, - TabContent, - Icon, + Alert, Badge, - Text, - useStyles2, + Icon, InteractiveTable, ScrollContainer, - Alert, Spinner, - IconButton, + Stack, + Tab, + TabContent, + TabsBar, + Text, + useStyles2, } from '@grafana/ui'; -import { SQLSchemas, SQLSchemaField, SQLSchemaData } from '../hooks/useSQLSchemas'; +import { SQLSchemaData, SQLSchemaField, SQLSchemas } from '../hooks/useSQLSchemas'; import { getFieldTypeIcon } from './utils'; @@ -33,10 +32,9 @@ interface SchemaInspectorPanelProps { schemas: SQLSchemas | null; loading: boolean; error: Error | null; - onClose: () => void; } -export const SchemaInspectorPanel = ({ schemas, loading, error, onClose }: SchemaInspectorPanelProps) => { +export const SchemaInspectorPanel = ({ schemas, loading, error }: SchemaInspectorPanelProps) => { const styles = useStyles2(getStyles); const schemaResponse: SQLSchemas = schemas ?? {}; @@ -192,32 +190,21 @@ export const SchemaInspectorPanel = ({ schemas, loading, error, onClose }: Schem }; return ( -
-
- {refIds.length > 0 && ( - - {refIds.map((refId) => ( - setSelectedTab(refId)} - /> - ))} - - )} - -
+ <> + {refIds.length > 0 && ( + + {refIds.map((refId) => ( + setSelectedTab(refId)} + /> + ))} + + )} {renderContent()} -
+ ); }; @@ -225,21 +212,6 @@ const getStyles = (theme: GrafanaTheme2) => ({ schemaInfoContainer: css({ padding: theme.spacing(1), }), - schemaInspector: css({ - height: '100%', - display: 'flex', - flexDirection: 'column', - }), - // Unfortunate hack to get the close button to align with the tabs since we need to - // override the default styles of the TabsBar component. - tabsBarWrapper: css({ - flexShrink: 0, - display: 'flex', - alignItems: 'center', - justifyContent: 'space-between', - width: '100%', - padding: `0 ${theme.spacing(1)}`, - }), tableCell: css({ fontSize: theme.typography.bodySmall.fontSize, fontWeight: theme.typography.fontWeightMedium, @@ -247,10 +219,8 @@ const getStyles = (theme: GrafanaTheme2) => ({ }), tableContainer: css({ margin: theme.spacing(1), - flex: 1, overflowY: 'auto', overflowX: 'auto', - minHeight: 0, // Allow flex child to shrink border: `1px solid ${theme.colors.border.medium}`, borderRadius: theme.shape.radius.default, backgroundColor: theme.colors.background.primary, diff --git a/public/app/features/expressions/components/SqlExpressions/SqlExpr.test.tsx b/public/app/features/expressions/components/SqlExpressions/SqlExpr.test.tsx index b7acc586447..9e2cfd50b75 100644 --- a/public/app/features/expressions/components/SqlExpressions/SqlExpr.test.tsx +++ b/public/app/features/expressions/components/SqlExpressions/SqlExpr.test.tsx @@ -1,4 +1,4 @@ -import { render, waitFor, fireEvent, act, testWithFeatureToggles } from 'test/test-utils'; +import { act, fireEvent, render, testWithFeatureToggles } from 'test/test-utils'; import { ExpressionQuery, ExpressionQueryType } from '../../types'; @@ -127,78 +127,6 @@ describe('SqlExpr with GenAI features', () => { queries: [], }; - it('renders GenAI buttons with empty expression', async () => { - const customProps = { ...defaultProps, query: { ...defaultProps.query, expression: '' } }; - const { findByText } = render(); - expect(await findByText('Generate suggestion')).toBeInTheDocument(); - expect(await findByText('Explain query')).toBeInTheDocument(); - }); - - it('renders GenAI buttons with non-empty expression', async () => { - const { findByText } = render(); - expect(await findByText('Improve query')).toBeInTheDocument(); - expect(await findByText('Explain query')).toBeInTheDocument(); - }); - - it('renders "Improve query" when currentQuery differs from initialQuery', async () => { - const customProps = { - ...defaultProps, - query: { ...defaultProps.query, expression: 'SELECT * FROM A WHERE value > 10' }, - }; - const { findByText } = render(); - expect(await findByText('Improve query')).toBeInTheDocument(); - }); - - it('renders View explanation button when shouldShowViewExplanation is true', async () => { - const { useSQLExplanations } = require('./GenAI/hooks/useSQLExplanations'); - useSQLExplanations.mockImplementation((currentExpression: string) => ({ - shouldShowViewExplanation: true, - })); - - const { findByText } = render(); - expect(await findByText('View explanation')).toBeInTheDocument(); - }); - - it('renders Explain query button when shouldShowViewExplanation is false', async () => { - const { useSQLExplanations } = require('./GenAI/hooks/useSQLExplanations'); - useSQLExplanations.mockImplementation((currentExpression: string) => ({ - shouldShowViewExplanation: false, - })); - - const { findByText } = render(); - expect(await findByText('Explain query')).toBeInTheDocument(); - }); - - it('renders SuggestionsDrawerButton when there are suggestions', async () => { - const { useSQLSuggestions } = require('./GenAI/hooks/useSQLSuggestions'); - useSQLSuggestions.mockImplementation(() => ({ suggestions: ['suggestion1', 'suggestion2'] })); - - const { findByTestId } = render(); - expect(await findByTestId('suggestions-badge')).toBeInTheDocument(); - }); - - it('does not render SuggestionsDrawerButton when there are no suggestions', async () => { - const { useSQLSuggestions } = require('./GenAI/hooks/useSQLSuggestions'); - useSQLSuggestions.mockImplementation(() => ({ suggestions: [] })); - - const { queryByTestId } = render(); - expect(await waitFor(() => queryByTestId('suggestions-badge'))).not.toBeInTheDocument(); - }); - - it('calls handleOpenExplanation when View explanation is clicked', async () => { - const { useSQLExplanations } = require('./GenAI/hooks/useSQLExplanations'); - const mockHandleOpen = jest.fn(); - useSQLExplanations.mockImplementation(() => ({ - shouldShowViewExplanation: true, - handleOpenExplanation: mockHandleOpen, - })); - - const { findByText } = render(); - const button = await findByText('View explanation'); - fireEvent.click(button); - expect(mockHandleOpen).toHaveBeenCalled(); - }); - it('renders suggestions drawer when isDrawerOpen is true', async () => { const { useSQLSuggestions } = require('./GenAI/hooks/useSQLSuggestions'); useSQLSuggestions.mockImplementation(() => ({ @@ -245,26 +173,26 @@ describe('Schema Inspector feature toggle', () => { }); it('closes panel and shows reopen button when close button clicked', async () => { - const { queryByText, getByLabelText, findByText } = render(); + const { queryByText, getByText, findByText } = render(); expect(queryByText('No schema information available')).toBeInTheDocument(); - const closeButton = getByLabelText('Close schema inspector'); + const closeButton = getByText('Schema inspector'); await act(async () => fireEvent.click(closeButton)); expect(queryByText('No schema information available')).not.toBeInTheDocument(); - expect(await findByText('Inspect schema')).toBeInTheDocument(); + expect(await findByText('Schema inspector')).toBeInTheDocument(); }); - it('reopens panel when inspect schema button clicked after closing', async () => { - const { queryByText, getByLabelText, getByText } = render(); + it('reopens panel when Open schema inspector button clicked after closing', async () => { + const { queryByText, getByText } = render(); - const closeButton = getByLabelText('Close schema inspector'); + const closeButton = getByText('Schema inspector'); await act(async () => fireEvent.click(closeButton)); expect(queryByText('No schema information available')).not.toBeInTheDocument(); - const reopenButton = getByText('Inspect schema'); + const reopenButton = getByText('Schema inspector'); await act(async () => fireEvent.click(reopenButton)); expect(queryByText('No schema information available')).toBeInTheDocument(); @@ -300,7 +228,7 @@ describe('Schema Inspector feature toggle', () => { it('does not render panel or button', () => { const { queryByText } = render(); - expect(queryByText('Inspect schema')).not.toBeInTheDocument(); + expect(queryByText('Schema inspector')).not.toBeInTheDocument(); expect(queryByText('No schema information available')).not.toBeInTheDocument(); }); }); diff --git a/public/app/features/expressions/components/SqlExpressions/SqlExpr.tsx b/public/app/features/expressions/components/SqlExpressions/SqlExpr.tsx index 361d748b716..a59b46b232b 100644 --- a/public/app/features/expressions/components/SqlExpressions/SqlExpr.tsx +++ b/public/app/features/expressions/components/SqlExpressions/SqlExpr.tsx @@ -1,15 +1,15 @@ import { css, cx } from '@emotion/css'; -import { useMemo, useRef, useEffect, useState, lazy, Suspense, useCallback } from 'react'; +import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from 'react'; import { useMeasure } from 'react-use'; import AutoSizer from 'react-virtualized-auto-sizer'; -import { SelectableValue, GrafanaTheme2 } from '@grafana/data'; -import { t, Trans } from '@grafana/i18n'; -import { SQLEditor, CompletionItemKind, LanguageDefinition, TableIdentifier } from '@grafana/plugin-ui'; +import { GrafanaTheme2, SelectableValue } from '@grafana/data'; +import { Trans } from '@grafana/i18n'; +import { CompletionItemKind, LanguageDefinition, SQLEditor, TableIdentifier } from '@grafana/plugin-ui'; import { reportInteraction } from '@grafana/runtime'; import { DataQuery } from '@grafana/schema/dist/esm/index'; import { formatSQL } from '@grafana/sql'; -import { useStyles2, Stack, Button, Modal } from '@grafana/ui'; +import { Button, Stack, useStyles2 } from '@grafana/ui'; import { ExpressionQueryEditorProps } from '../../ExpressionQueryEditor'; import { SqlExpressionQuery } from '../../types'; @@ -20,27 +20,10 @@ import { getSqlCompletionProvider } from './CompletionProvider/sqlCompletionProv import { useSQLExplanations } from './GenAI/hooks/useSQLExplanations'; import { useSQLSuggestions } from './GenAI/hooks/useSQLSuggestions'; import { SchemaInspectorPanel } from './SchemaInspector/SchemaInspectorPanel'; +import { SqlExprContextValue, SqlExprProvider } from './SqlExprContext'; +import { SqlQueryActions } from './SqlQueryActions'; import { useSQLSchemas } from './hooks/useSQLSchemas'; -// Lazy load the GenAI components to avoid circular dependencies -const GenAISQLSuggestionsButton = lazy(() => - import('./GenAI/GenAISQLSuggestionsButton').then((module) => ({ - default: module.GenAISQLSuggestionsButton, - })) -); - -const GenAISQLExplainButton = lazy(() => - import('./GenAI/GenAISQLExplainButton').then((module) => ({ - default: module.GenAISQLExplainButton, - })) -); - -const SuggestionsDrawerButton = lazy(() => - import('./GenAI/SuggestionsDrawerButton').then((module) => ({ - default: module.SuggestionsDrawerButton, - })) -); - const GenAISuggestionsDrawer = lazy(() => import('./GenAI/GenAISuggestionsDrawer').then((module) => ({ default: module.GenAISuggestionsDrawer, @@ -55,7 +38,6 @@ const GenAIExplanationDrawer = lazy(() => // Account for Monaco editor's border to prevent clipping const EDITOR_BORDER_ADJUSTMENT = 2; // 1px border on top and bottom -const EDITOR_HEIGHT = 300; export interface SqlExprProps { refIds: Array>; @@ -93,14 +75,10 @@ FROM LIMIT 10`; - const [dimensions, setDimensions] = useState({ height: 0 }); - const styles = useStyles2((theme) => getStyles(theme, dimensions.height || EDITOR_HEIGHT)); - const containerRef = useRef(null); const [toolboxRef, toolboxMeasure] = useMeasure(); - const [isExpanded, setIsExpanded] = useState(false); const [isSchemaInspectorOpen, setIsSchemaInspectorOpen] = useState(true); - - const { handleApplySuggestion, handleHistoryUpdate, handleCloseDrawer, handleOpenDrawer, isDrawerOpen, suggestions } = + const styles = useStyles2((theme) => getStyles(theme)); + const { handleApplySuggestion, handleCloseDrawer, handleHistoryUpdate, handleOpenDrawer, isDrawerOpen, suggestions } = useSQLSuggestions(); const { @@ -195,21 +173,6 @@ LIMIT } }, [onRunQuery, refetchSchemas, isSchemaInspectorOpen]); - // Set up resize observer to handle container resizing - useEffect(() => { - if (!containerRef.current) { - return; - } - - const resizeObserver = new ResizeObserver((entries) => { - const { height } = entries[0].contentRect; - setDimensions({ height }); - }); - - resizeObserver.observe(containerRef.current); - return () => resizeObserver.disconnect(); - }, []); - useEffect(() => { // Call the onChange method once so we have access to the initial query in consuming components // But only if expression is empty @@ -236,168 +199,122 @@ LIMIT return () => document.removeEventListener('keydown', handleKeyDown, true); }, [executeQuery]); - const renderToolbox = (formatQuery: () => void) => ( -
- -
- ); + const contextValue: SqlExprContextValue = { + // Explanations + explanation, + isExplanationOpen, + shouldShowViewExplanation, + handleExplain, + handleOpenExplanation, + handleCloseExplanation, + // Suggestions + suggestions, + isDrawerOpen, + handleHistoryUpdate, + handleApplySuggestion, + handleOpenDrawer, + handleCloseDrawer, + }; - const renderSQLButtons = () => ( -
- - {isSchemasFeatureEnabled && !isSchemaInspectorOpen && ( - - )} - - - {shouldShowViewExplanation ? ( - - ) : ( - - )} - - - {}} // Noop - history is managed via onHistoryUpdate - onHistoryUpdate={handleHistoryUpdate} - queryContext={queryContext} - refIds={vars} - errorContext={errorContext} // Will be added when error tracking is implemented - // schemas={schemas} // Will be added when schema extraction is implemented - /> - - - {suggestions.length > 0 && ( - - - - )} -
- ); - - const renderSQLEditor = (width?: number, height?: number) => ( - <> -
- {renderSQLButtons()} -
( + + + {isSchemasFeatureEnabled && ( + + )} + + ); + + const renderMainContent = () => ( +
+
+ + {({ width, height }) => ( - {({ formatQuery }) => renderToolbox(formatQuery)} + {({ formatQuery }) => ( +
+ +
+ )}
-
- {isSchemaInspectorOpen && isSchemasFeatureEnabled && ( -
- setIsSchemaInspectorOpen(false)} - /> -
)} -
+
- - - - - - - + {isSchemaInspectorOpen && isSchemasFeatureEnabled && ( +
+ +
+ )} +
); - const renderStandaloneEditor = () => ( - - {({ width, height }) => ( - - {({ formatQuery }) => renderToolbox(formatQuery)} - - )} - + const renderSQLEditor = () => ( + + {renderButtons()} + {renderMainContent()} + ); return ( - <> - {renderSQLEditor()} - {isExpanded && ( - setIsExpanded(false)} - > - {renderStandaloneEditor()} - - )} - + +
+ {renderSQLEditor()} + + + + + + +
+
); }; -const getStyles = (theme: GrafanaTheme2, editorHeight: number) => ({ - sqlContainer: css({ - display: 'grid', - gap: theme.spacing(1), - gridTemplateRows: 'auto 1fr', - gridTemplateAreas: ` - "buttons" - "content" - `, +const getStyles = (theme: GrafanaTheme2) => ({ + mainContainer: css({ + marginTop: theme.spacing(0.5), }), - contentContainer: css({ - gridArea: 'content', + minHeight: '250px', + height: '100%', + resize: 'vertical', + overflow: 'hidden', + display: 'grid', - gap: theme.spacing(1), gridTemplateColumns: '1fr 0fr', gridTemplateAreas: '"editor schema"', [theme.transitions.handleMotion('no-preference')]: { @@ -408,67 +325,22 @@ const getStyles = (theme: GrafanaTheme2, editorHeight: number) => ({ }), contentContainerWithSchema: css({ gridTemplateColumns: '1fr 1fr', + gap: theme.spacing(1), }), editorContainer: css({ gridArea: 'editor', - height: editorHeight, // Use dynamic height from ResizeObserver - resize: 'vertical', - overflow: 'auto', - minHeight: '100px', - }), - modal: css({ - width: '95vw', - height: '95vh', - }), - modalContent: css({ height: '100%', - paddingTop: 0, - }), - // This is NOT ideal. The alternative is to expose SQL buttons as a separate component, - // Then consume them in ExpressionQueryEditor. This requires a lot of refactoring and - // can be prioritized later. - sqlButtons: css({ - gridArea: 'buttons', - justifySelf: 'end', - transform: `translateY(${theme.spacing(-4)})`, - marginBottom: theme.spacing(-4), // Prevent affecting editor position - zIndex: 10, // Ensure buttons appear above other elements - position: 'relative', // Required for z-index to work - display: 'flex', - alignItems: 'center', - gap: theme.spacing(1), + width: '100%', + overflow: 'auto', }), schemaInspector: css({ gridArea: 'schema', - height: editorHeight, + height: '100%', overflow: 'hidden', minWidth: 0, - }), - schemaInspectorOpen: css({ border: `1px solid ${theme.colors.border.weak}`, borderRadius: theme.shape.radius.default, }), - schemaFields: css({ - display: 'flex', - flexWrap: 'wrap', - gap: theme.spacing(1), - padding: theme.spacing(1), - maxHeight: '120px', - overflowY: 'auto', - }), - fieldItem: css({ - display: 'flex', - alignItems: 'center', - gap: theme.spacing(0.5), - padding: theme.spacing(1), - backgroundColor: theme.colors.background.secondary, - borderRadius: theme.shape.radius.default, - border: `1px solid ${theme.colors.border.weak}`, - fontSize: theme.typography.bodySmall.fontSize, - }), - responseContainer: css({ - padding: theme.spacing(2), - }), }); async function fetchFields(identifier: TableIdentifier, queries: DataQuery[]) { diff --git a/public/app/features/expressions/components/SqlExpressions/SqlExprContext.test.tsx b/public/app/features/expressions/components/SqlExpressions/SqlExprContext.test.tsx new file mode 100644 index 00000000000..f95128b5af6 --- /dev/null +++ b/public/app/features/expressions/components/SqlExpressions/SqlExprContext.test.tsx @@ -0,0 +1,88 @@ +import { render, screen } from 'test/test-utils'; + +import { SqlExprContextValue, SqlExprProvider, useSqlExprContext } from './SqlExprContext'; + +describe('SqlExprContext', () => { + const mockContextValue: SqlExprContextValue = { + explanation: 'Test explanation', + isExplanationOpen: false, + shouldShowViewExplanation: false, + handleExplain: jest.fn(), + handleOpenExplanation: jest.fn(), + handleCloseExplanation: jest.fn(), + suggestions: ['suggestion1', 'suggestion2'], + isDrawerOpen: false, + handleHistoryUpdate: jest.fn(), + handleApplySuggestion: jest.fn(), + handleOpenDrawer: jest.fn(), + handleCloseDrawer: jest.fn(), + }; + + describe('SqlExprProvider', () => { + it('renders children correctly', () => { + render( + +
Test Child
+
+ ); + + expect(screen.getByText('Test Child')).toBeInTheDocument(); + }); + + it('provides context value to children', () => { + const TestConsumer = () => { + const context = useSqlExprContext(); + return
{context.explanation}
; + }; + + render( + + + + ); + + expect(screen.getByText('Test explanation')).toBeInTheDocument(); + }); + }); + + describe('useSqlExprContext', () => { + it('throws error when used outside provider', () => { + const TestComponent = () => { + useSqlExprContext(); + return
Should not render
; + }; + + // Suppress console.error for this test + const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + + expect(() => { + render(); + }).toThrow('useSqlExprContext must be used within SqlExprProvider'); + + consoleSpy.mockRestore(); + }); + + it('returns context value when used inside provider', () => { + const TestComponent = () => { + const context = useSqlExprContext(); + return ( +
+ Explanation: {context.explanation} + Suggestions: {context.suggestions.length} + Is Drawer Open: {context.isDrawerOpen.toString()} +
+ ); + }; + + render( + + + + ); + + expect(screen.getByText('Explanation: Test explanation')).toBeInTheDocument(); + expect(screen.getByText('Suggestions: 2')).toBeInTheDocument(); + expect(screen.getByText('Is Drawer Open: false')).toBeInTheDocument(); + }); + }); +}); diff --git a/public/app/features/expressions/components/SqlExpressions/SqlExprContext.tsx b/public/app/features/expressions/components/SqlExpressions/SqlExprContext.tsx new file mode 100644 index 00000000000..e05ccff80b6 --- /dev/null +++ b/public/app/features/expressions/components/SqlExpressions/SqlExprContext.tsx @@ -0,0 +1,38 @@ +import { createContext, useContext, ReactNode } from 'react'; + +export interface SqlExprContextValue { + // Explanations + explanation: string; + isExplanationOpen: boolean; + shouldShowViewExplanation: boolean; + handleExplain: (explanation: string) => void; + handleOpenExplanation: () => void; + handleCloseExplanation: () => void; + + // Suggestions + suggestions: string[]; + isDrawerOpen: boolean; + handleHistoryUpdate: (suggestions: string[]) => void; + handleApplySuggestion: (suggestion: string) => string; + handleOpenDrawer: () => void; + handleCloseDrawer: () => void; +} + +const SqlExprContext = createContext(null); + +export const useSqlExprContext = () => { + const context = useContext(SqlExprContext); + if (!context) { + throw new Error('useSqlExprContext must be used within SqlExprProvider'); + } + return context; +}; + +interface SqlExprProviderProps { + children: ReactNode; + value: SqlExprContextValue; +} + +export const SqlExprProvider = ({ children, value }: SqlExprProviderProps) => { + return {children}; +}; diff --git a/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.test.tsx b/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.test.tsx new file mode 100644 index 00000000000..93e3285ed83 --- /dev/null +++ b/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.test.tsx @@ -0,0 +1,137 @@ +import { fireEvent, render, waitFor } from 'test/test-utils'; + +import { SqlExprContextValue } from './SqlExprContext'; +import { SqlQueryActions, SqlQueryActionsProps } from './SqlQueryActions'; + +jest.mock('@grafana/ui', () => ({ + ...jest.requireActual('@grafana/ui'), + useStyles2: jest.fn().mockImplementation(() => ({})), +})); + +// Mock lazy loaded GenAI components +jest.mock('./GenAI/GenAISQLSuggestionsButton', () => ({ + GenAISQLSuggestionsButton: ({ currentQuery, initialQuery }: { currentQuery: string; initialQuery: string }) => { + const text = !currentQuery || currentQuery === initialQuery ? 'Generate suggestion' : 'Improve query'; + return
{text}
; + }, +})); + +jest.mock('./GenAI/GenAISQLExplainButton', () => ({ + GenAISQLExplainButton: () =>
Explain query
, +})); + +jest.mock('./GenAI/SuggestionsDrawerButton', () => ({ + SuggestionsDrawerButton: () =>
Suggestions Badge
, +})); + +// Mock SqlExprContext +const mockContextValue: SqlExprContextValue = { + handleOpenExplanation: jest.fn(), + shouldShowViewExplanation: false, + handleExplain: jest.fn(), + handleHistoryUpdate: jest.fn(), + handleOpenDrawer: jest.fn(), + suggestions: [], + explanation: '', + isExplanationOpen: false, + isDrawerOpen: false, + handleApplySuggestion: jest.fn(), + handleCloseDrawer: jest.fn(), + handleCloseExplanation: jest.fn(), +}; + +jest.mock('./SqlExprContext', () => ({ + useSqlExprContext: () => mockContextValue, + SqlExprProvider: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +describe('SqlQueryActions', () => { + const defaultProps: SqlQueryActionsProps = { + executeQuery: jest.fn(), + currentQuery: `SELECT * FROM A LIMIT 10`, + queryContext: {}, + refIds: ['A'], + initialQuery: `SELECT * FROM A LIMIT 10`, + errorContext: [], + }; + + beforeEach(() => { + jest.clearAllMocks(); + // Reset mock context to default values + Object.assign(mockContextValue, { + handleOpenExplanation: jest.fn(), + shouldShowViewExplanation: false, + handleExplain: jest.fn(), + handleHistoryUpdate: jest.fn(), + handleOpenDrawer: jest.fn(), + suggestions: [], + explanation: '', + isExplanationOpen: false, + isDrawerOpen: false, + handleApplySuggestion: jest.fn(), + handleCloseDrawer: jest.fn(), + handleCloseExplanation: jest.fn(), + }); + }); + + it('renders GenAI buttons with empty expression', async () => { + const customProps = { ...defaultProps, currentQuery: '' }; + const { findByText } = render(); + expect(await findByText('Generate suggestion')).toBeInTheDocument(); + expect(await findByText('Explain query')).toBeInTheDocument(); + }); + + it('renders GenAI buttons with non-empty expression', async () => { + const { findByText } = render(); + expect(await findByText('Generate suggestion')).toBeInTheDocument(); + expect(await findByText('Explain query')).toBeInTheDocument(); + }); + + it('renders "Improve query" when currentQuery differs from initialQuery', async () => { + const customProps = { + ...defaultProps, + currentQuery: 'SELECT * FROM A WHERE value > 10', + }; + const { findByText } = render(); + expect(await findByText('Improve query')).toBeInTheDocument(); + }); + + it('renders View explanation button when shouldShowViewExplanation is true', async () => { + mockContextValue.shouldShowViewExplanation = true; + + const { findByText } = render(); + expect(await findByText('View explanation')).toBeInTheDocument(); + }); + + it('renders Explain query button when shouldShowViewExplanation is false', async () => { + mockContextValue.shouldShowViewExplanation = false; + + const { findByText } = render(); + expect(await findByText('Explain query')).toBeInTheDocument(); + }); + + it('renders SuggestionsDrawerButton when there are suggestions', async () => { + mockContextValue.suggestions = ['suggestion1', 'suggestion2']; + + const { findByTestId } = render(); + expect(await findByTestId('suggestions-badge')).toBeInTheDocument(); + }); + + it('does not render SuggestionsDrawerButton when there are no suggestions', async () => { + mockContextValue.suggestions = []; + + const { queryByTestId } = render(); + expect(await waitFor(() => queryByTestId('suggestions-badge'))).not.toBeInTheDocument(); + }); + + it('calls handleOpenExplanation when View explanation is clicked', async () => { + const mockHandleOpen = jest.fn(); + mockContextValue.shouldShowViewExplanation = true; + mockContextValue.handleOpenExplanation = mockHandleOpen; + + const { findByText } = render(); + const button = await findByText('View explanation'); + fireEvent.click(button); + expect(mockHandleOpen).toHaveBeenCalled(); + }); +}); diff --git a/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.tsx b/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.tsx new file mode 100644 index 00000000000..a96a82a4e72 --- /dev/null +++ b/public/app/features/expressions/components/SqlExpressions/SqlQueryActions.tsx @@ -0,0 +1,91 @@ +import { lazy, Suspense } from 'react'; + +import { t, Trans } from '@grafana/i18n'; +import { Button, Stack } from '@grafana/ui'; + +import { useSqlExprContext } from './SqlExprContext'; + +// Lazy load the GenAI components to avoid circular dependencies +const GenAISQLSuggestionsButton = lazy(() => + import('./GenAI/GenAISQLSuggestionsButton').then((module) => ({ + default: module.GenAISQLSuggestionsButton, + })) +); + +const GenAISQLExplainButton = lazy(() => + import('./GenAI/GenAISQLExplainButton').then((module) => ({ + default: module.GenAISQLExplainButton, + })) +); + +const SuggestionsDrawerButton = lazy(() => + import('./GenAI/SuggestionsDrawerButton').then((module) => ({ + default: module.SuggestionsDrawerButton, + })) +); + +export interface SqlQueryActionsProps { + executeQuery: () => void; + currentQuery: string; + queryContext: Record; + refIds: string[]; + initialQuery: string; + errorContext: string[]; +} + +export const SqlQueryActions = ({ + executeQuery, + currentQuery, + queryContext, + refIds, + initialQuery, + errorContext, +}: SqlQueryActionsProps) => { + const { + handleOpenExplanation, + shouldShowViewExplanation, + handleExplain, + handleHistoryUpdate, + handleOpenDrawer, + suggestions, + } = useSqlExprContext(); + return ( + + + + {shouldShowViewExplanation ? ( + + ) : ( + + )} + + + {}} // Noop - history is managed via onHistoryUpdate + onHistoryUpdate={handleHistoryUpdate} + queryContext={queryContext} + refIds={refIds} + errorContext={errorContext} // Will be added when error tracking is implemented + // schemas={schemas} // Will be added when schema extraction is implemented + /> + + {suggestions.length > 0 && ( + + + + )} + + ); +}; diff --git a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx index 7248dbcc1e5..632c143fe3a 100644 --- a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx +++ b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx @@ -2,7 +2,7 @@ import { css, cx } from '@emotion/css'; import { cloneDeep } from 'lodash'; import { CSSProperties, HTMLAttributes, ReactNode } from 'react'; -import { colorManipulator, GrafanaTheme2, PanelData, PanelPluginVisualizationSuggestion } from '@grafana/data'; +import { GrafanaTheme2, PanelData, PanelPluginVisualizationSuggestion } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { config } from '@grafana/runtime'; import { Tooltip, useStyles2 } from '@grafana/ui'; @@ -31,7 +31,11 @@ export function VisualizationSuggestionCard({ const commonButtonProps = { 'aria-label': suggestion.name, - className: cx(className, styles.vizBox), + className: cx( + className, + styles.vizBox, + config.featureToggles.newVizSuggestions && isSelected && styles.selectedBox + ), 'data-testid': selectors.components.VisualizationPreview.card(suggestion.name), style: outerStyles, tabIndex: -1, // selection is handled by parent container @@ -56,7 +60,12 @@ export function VisualizationSuggestionCard({ content = ( ); @@ -82,22 +89,8 @@ export function VisualizationSuggestionCard({ const getStyles = (theme: GrafanaTheme2) => { return { - hoverPane: css({ - position: 'absolute', - top: -4, - left: -4, - right: -2, - bottom: -2, - borderRadius: theme.spacing(0.5), - background: 'transparent', - [theme.transitions.handleMotion('no-preference', 'reduce')]: { - transition: theme.transitions.create(['background'], { - duration: theme.transitions.duration.short, - }), - }, - }), - hoverPaneSelected: css({ - background: colorManipulator.alpha(theme.colors.text.primary, 0.1), + selectedSuggestion: css({ + filter: `blur(1px) ${theme.isDark ? 'brightness(0.5)' : 'opacity(0.3)'}`, }), vizBox: css({ position: 'relative', @@ -149,6 +142,10 @@ const getStyles = (theme: GrafanaTheme2) => { top: '6px', left: '6px', }), + selectedBox: css({ + border: `1px solid ${theme.colors.primary.border}`, + background: theme.colors.action.selected, + }), }; }; diff --git a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx index e93e74f358d..d1763ad835f 100644 --- a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx +++ b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx @@ -1,6 +1,6 @@ import { css } from '@emotion/css'; import { Fragment, useState, useEffect, useCallback, useMemo } from 'react'; -import { useAsync, useMeasure } from 'react-use'; +import { useAsyncRetry, useMeasure } from 'react-use'; import { GrafanaTheme2, @@ -28,19 +28,23 @@ export interface Props { panel?: PanelModel; } +const useSuggestions = (data: PanelData | undefined) => { + const [hasFetched, setHasFetched] = useState(false); + const { value, loading, error, retry } = useAsyncRetry(async () => { + await new Promise((resolve) => setTimeout(resolve, hasFetched ? 75 : 0)); + setHasFetched(true); + return await getAllSuggestions(data); + }, [hasFetched, data]); + return { value, loading, error, retry }; +}; + export function VisualizationSuggestions({ onChange, data, panel }: Props) { const styles = useStyles2(getStyles); - const { - value: suggestions, - loading, - error, - } = useAsync(async () => { - if (!hasData(data)) { - return []; - } - return await getAllSuggestions(data); - }, [data]); + const { value: result, loading, error, retry } = useSuggestions(data); + + const suggestions = result?.suggestions; + const hasLoadingErrors = result?.hasErrors ?? false; const [suggestionHash, setSuggestionHash] = useState(null); const [firstCardRef, { width }] = useMeasure(); const [firstCardHash, setFirstCardHash] = useState(null); @@ -131,80 +135,97 @@ export function VisualizationSuggestions({ onChange, data, panel }: Props) { } return ( -
- {isNewVizSuggestionsEnabled - ? suggestionsByVizType.map(([vizType, vizTypeSuggestions], groupIndex) => ( - -
- - {vizType?.info && } - {vizType?.name || t('panel.visualization-suggestions.unknown-viz-type', 'Unknown visualization type')} - -
- {vizTypeSuggestions?.map((suggestion, index) => { - const isCardSelected = suggestionHash === suggestion.hash; - return ( -
{ - if (ev.key === 'Enter' || ev.key === ' ') { - ev.preventDefault(); - applySuggestion(suggestion, isNewVizSuggestionsEnabled && !isCardSelected); - } - }} - ref={index === 0 ? firstCardRef : undefined} - > - {isCardSelected && ( - +
+ + )} +
+ {isNewVizSuggestionsEnabled + ? suggestionsByVizType.map(([vizType, vizTypeSuggestions], groupIndex) => ( + +
+ + {vizType?.info && } + {vizType?.name || + t('panel.visualization-suggestions.unknown-viz-type', 'Unknown visualization type')} + +
+ {vizTypeSuggestions?.map((suggestion, index) => { + const isCardSelected = suggestionHash === suggestion.hash; + return ( +
{ + if (ev.key === 'Enter' || ev.key === ' ') { + ev.preventDefault(); + applySuggestion(suggestion, isNewVizSuggestionsEnabled && !isCardSelected); } - > - {t('panel.visualization-suggestions.use-this-suggestion', 'Use this suggestion')} - - )} - applySuggestion(suggestion, true)} - /> -
- ); - })} -
- )) - : suggestions?.map((suggestion, index) => ( -
- applySuggestion(suggestion)} - /> -
- ))} -
+ }} + ref={index === 0 ? firstCardRef : undefined} + > + {isCardSelected && ( + + )} + applySuggestion(suggestion, true)} + /> +
+ ); + })} + + )) + : suggestions?.map((suggestion, index) => ( +
+ applySuggestion(suggestion)} + /> +
+ ))} +
+ ); } @@ -217,6 +238,11 @@ const getStyles = (theme: GrafanaTheme2) => { width: '100%', marginTop: theme.spacing(6), }), + alertContent: css({ + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + }), filterRow: css({ display: 'flex', flexDirection: 'row', diff --git a/public/app/features/panel/suggestions/consts.ts b/public/app/features/panel/suggestions/consts.ts index 76e012a7425..decdf8ac7b4 100644 --- a/public/app/features/panel/suggestions/consts.ts +++ b/public/app/features/panel/suggestions/consts.ts @@ -16,4 +16,5 @@ export const panelsToCheckFirst = [ 'heatmap', 'histogram', 'geomap', + 'text', ]; diff --git a/public/app/features/panel/suggestions/getAllSuggestions.test.ts b/public/app/features/panel/suggestions/getAllSuggestions.test.ts index e76a7df15e3..8657824cc27 100644 --- a/public/app/features/panel/suggestions/getAllSuggestions.test.ts +++ b/public/app/features/panel/suggestions/getAllSuggestions.test.ts @@ -1,4 +1,5 @@ import { + AppEvents, DataFrame, FieldType, getDefaultTimeRange, @@ -18,10 +19,20 @@ import { StackingMode, VizOrientation, } from '@grafana/schema'; +import { appEvents } from 'app/core/app_events'; import { config } from 'app/core/config'; +import { clearPanelPluginCache } from 'app/features/plugins/importPanelPlugin'; +import { pluginImporter } from 'app/features/plugins/importer/pluginImporter'; import { panelsToCheckFirst } from './consts'; -import { getAllSuggestions, sortSuggestions } from './getAllSuggestions'; +import { getAllSuggestions, loadPlugins, sortSuggestions } from './getAllSuggestions'; + +jest.mock('app/core/app_events', () => ({ + appEvents: { + subscribe: jest.fn(() => ({ unsubscribe: jest.fn() })), + publish: jest.fn(), + }, +})); config.featureToggles.externalVizSuggestions = true; @@ -52,28 +63,6 @@ for (const pluginId of panelsToCheckFirst) { }; } -config.panels.text = { - id: 'text', - module: 'core:plugin/text', - sort: idx++, - name: 'Text', - type: PluginType.panel, - baseUrl: 'public/app/plugins/panel', - skipDataQuery: true, - suggestions: false, - info: { - version: '1.0.0', - updated: '2025-01-01', - links: [], - screenshots: [], - author: { - name: 'Grafana Labs', - }, - description: 'Text panel', - logos: { small: 'small/logo', large: 'large/logo' }, - }, -}; - jest.mock('../state/util', () => { const originalModule = jest.requireActual('../state/util'); return { @@ -103,7 +92,8 @@ class ScenarioContext { timeRange: getDefaultTimeRange(), }; - this.suggestions = await getAllSuggestions(panelData); + const result = await getAllSuggestions(panelData); + this.suggestions = result.suggestions; } names() { @@ -554,6 +544,81 @@ describe('sortSuggestions', () => { }); }); +describe('Visualization suggestions error handling', () => { + it('returns result with hasErrors flag', async () => { + const result = await getAllSuggestions({ + series: [ + toDataFrame({ + fields: [ + { name: 'Time', type: FieldType.time, values: [1, 2] }, + { name: 'Max', type: FieldType.number, values: [1, 10] }, + ], + }), + ], + state: LoadingState.Done, + timeRange: getDefaultTimeRange(), + }); + + expect(result).toHaveProperty('suggestions'); + expect(result).toHaveProperty('hasErrors'); + expect(result.hasErrors).toBe(false); + }); +}); + +// this needs to happen before any +describe('loadPlugins', () => { + beforeEach(() => { + clearPanelPluginCache(); + }); + + afterEach(() => { + if (jest.isMockFunction(pluginImporter.importPanel)) { + jest.mocked(pluginImporter.importPanel).mockRestore(); + } + }); + + it('should swallow errors when failing to load core plugins', async () => { + jest.spyOn(console, 'error').mockImplementation(); + + const _importPanel = pluginImporter.importPanel; + jest.spyOn(pluginImporter, 'importPanel').mockImplementation(async (meta) => { + if (meta.id === 'timeseries') { + throw new Error('Failed to load core panel plugin'); + } + return await _importPanel(meta); + }); + + const panelIds = ['timeseries', 'table']; + const { plugins, hasErrors } = await loadPlugins(panelIds); + + expect(plugins).toEqual([expect.objectContaining({ meta: expect.objectContaining({ id: 'table' }) })]); + expect(hasErrors).toBe(true); + expect(appEvents.publish).not.toHaveBeenCalled(); + }); + + it('should swallow errors when failing to load external plugins', async () => { + jest.spyOn(console, 'error').mockImplementation(); + + const panelIds = ['non-existent-panel']; + const { plugins, hasErrors } = await loadPlugins(panelIds); + + expect(plugins).toEqual([]); + expect(hasErrors).toBe(false); + expect(appEvents.publish).toHaveBeenCalledWith({ + type: AppEvents.alertError.name, + payload: [expect.stringContaining('Failed to load panel plugin: non-existent-panel.')], + }); + }); + + it('should load panel plugins with suggestions', async () => { + const panelIds = ['timeseries', 'table']; + const { plugins, hasErrors } = await loadPlugins(panelIds); + + expect(plugins.map((p) => p.meta.id)).toEqual(expect.arrayContaining(['timeseries', 'table'])); + expect(hasErrors).toBe(false); + }); +}); + function repeatFrame(count: number, frame: DataFrame): DataFrame[] { const frames: DataFrame[] = []; for (let i = 0; i < count; i++) { diff --git a/public/app/features/panel/suggestions/getAllSuggestions.ts b/public/app/features/panel/suggestions/getAllSuggestions.ts index ea94add39ab..d0bb73dfb83 100644 --- a/public/app/features/panel/suggestions/getAllSuggestions.ts +++ b/public/app/features/panel/suggestions/getAllSuggestions.ts @@ -1,4 +1,5 @@ import { + AppEvents, getPanelDataSummary, PanelData, PanelDataSummary, @@ -7,41 +8,67 @@ import { PreferredVisualisationType, VisualizationSuggestionScore, } from '@grafana/data'; +import { t } from '@grafana/i18n'; import { config } from '@grafana/runtime'; +import { appEvents } from 'app/core/app_events'; import { importPanelPlugin, isBuiltInPlugin } from 'app/features/plugins/importPanelPlugin'; import { getAllPanelPluginMeta } from '../state/util'; import { panelsToCheckFirst } from './consts'; -/** - * gather and cache the plugins which provide visualization suggestions so they can be invoked to build suggestions - */ -async function getPanelsWithSuggestions(): Promise { - // list of plugins to load is determined by the feature flag - const pluginIds: string[] = config.featureToggles.externalVizSuggestions +interface PluginLoadResult { + plugins: PanelPlugin[]; + hasErrors: boolean; +} + +function getPanelPluginIds(): string[] { + return config.featureToggles.externalVizSuggestions ? getAllPanelPluginMeta() .filter((panel) => panel.suggestions) .map((m) => m.id) : panelsToCheckFirst; +} +/** + * gather and cache the plugins which provide visualization suggestions so they can be invoked to build suggestions + */ +export async function loadPlugins(pluginIds: string[]): Promise { // import the plugins in parallel using Promise.allSettled const plugins: PanelPlugin[] = []; - const settledPromises = await Promise.allSettled(pluginIds.map((id) => importPanelPlugin(id))); + let hasErrors = false; + const settledPromises = await Promise.allSettled( + pluginIds.map(async (pluginId) => { + return await importPanelPlugin(pluginId); + }) + ); + for (let i = 0; i < settledPromises.length; i++) { const settled = settledPromises[i]; - if (settled.status === 'fulfilled') { plugins.push(settled.value); + } else { + const pluginId = pluginIds[i]; + console.error(`Failed to load ${pluginId} for visualization suggestions:`, settled.reason); + + if (isBuiltInPlugin(pluginId)) { + hasErrors = true; + } else { + appEvents.publish({ + type: AppEvents.alertError.name, + payload: [ + t( + 'panel.visualization-suggestions.error-loading-suggestions.plugin-failed', + 'Failed to load panel plugin: {{ pluginId }}.', + { pluginId } + ), + ], + }); + } } - // TODO: do we want to somehow log if there were errors loading some of the plugins? } - if (plugins.length === 0) { - throw new Error('No panel plugins with visualization suggestions found'); - } - - return plugins; + return { plugins, hasErrors }; } /** @@ -89,41 +116,37 @@ export function sortSuggestions(suggestions: PanelPluginVisualizationSuggestion[ }); } +export interface SuggestionsResult { + suggestions: PanelPluginVisualizationSuggestion[]; + hasErrors: boolean; +} + /** * given PanelData, return a sorted list of Suggestions from all plugins which support it. * @param {PanelData} data queried and transformed data for the panel - * @returns {PanelPluginVisualizationSuggestion[]} sorted list of suggestions + * @returns {SuggestionsResult} sorted list of suggestions and error status */ -export async function getAllSuggestions(data?: PanelData): Promise { +export async function getAllSuggestions(data?: PanelData): Promise { const dataSummary = getPanelDataSummary(data?.series); const list: PanelPluginVisualizationSuggestion[] = []; - for (const plugin of await getPanelsWithSuggestions()) { - const suggestions = plugin.getSuggestions(dataSummary); - if (suggestions) { - list.push(...suggestions); - } - } + const pluginIds: string[] = getPanelPluginIds(); + const { plugins, hasErrors: pluginLoadErrors } = await loadPlugins(pluginIds); - if (dataSummary.fieldCount === 0) { - for (const plugin of Object.values(config.panels)) { - if (!plugin.skipDataQuery || plugin.hideFromList) { - continue; + let pluginSuggestionsError = false; + for (const plugin of plugins) { + try { + const suggestions = plugin.getSuggestions(dataSummary); + if (suggestions) { + list.push(...suggestions); } - - list.push({ - name: plugin.name, - pluginId: plugin.id, - description: plugin.info.description, - hash: 'plugin-empty-' + plugin.id, - cardOptions: { - imgSrc: plugin.info.logos.small, - }, - }); + } catch (e) { + console.warn(`error when loading suggestions from plugin "${plugin.meta.id}"`, e); + pluginSuggestionsError = true; } } sortSuggestions(list, dataSummary); - return list; + return { suggestions: list, hasErrors: pluginLoadErrors || pluginSuggestionsError }; } diff --git a/public/app/features/plugins/admin/api.ts b/public/app/features/plugins/admin/api.ts index 74a072ba054..aa5bc32f183 100644 --- a/public/app/features/plugins/admin/api.ts +++ b/public/app/features/plugins/admin/api.ts @@ -8,6 +8,7 @@ import { LocalPlugin, RemotePlugin, CatalogPluginDetails, + CatalogPluginInsights, Version, PluginVersion, InstancePlugin, @@ -47,6 +48,21 @@ export async function getPluginDetails(id: string): Promise { + if (!version) { + throw new Error('Version is required'); + } + try { + const insights = await getBackendSrv().get(`${GCOM_API_ROOT}/plugins/${id}/versions/${version}/insights`); + return insights; + } catch (error) { + if (isFetchError(error)) { + error.isHandled = true; + } + throw error; + } +} + export async function getRemotePlugins(): Promise { try { const { items: remotePlugins }: { items: RemotePlugin[] } = await getBackendSrv().get(`${GCOM_API_ROOT}/plugins`, { diff --git a/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx b/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx index da4eef2f0d4..0ffc93f8f77 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx @@ -62,10 +62,12 @@ const plugin: CatalogPlugin = { angularDetected: false, isFullyInstalled: true, accessControl: {}, + insights: { id: 1, name: 'test-plugin', version: '1.0.0', insights: [] }, }; jest.mock('../state/hooks', () => ({ useGetSingle: jest.fn(), + useGetPluginInsights: jest.fn(), useFetchStatus: jest.fn().mockReturnValue({ isLoading: false }), useFetchDetailsStatus: () => ({ isLoading: false }), useIsRemotePluginsAvailable: () => false, diff --git a/public/app/features/plugins/admin/components/PluginDetailsPage.tsx b/public/app/features/plugins/admin/components/PluginDetailsPage.tsx index 0e651a8e4bf..2a7342e6be8 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPage.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPage.tsx @@ -16,8 +16,7 @@ import { PluginDetailsPanel } from '../components/PluginDetailsPanel'; import { PluginDetailsSignature } from '../components/PluginDetailsSignature'; import { usePluginDetailsTabs } from '../hooks/usePluginDetailsTabs'; import { usePluginPageExtensions } from '../hooks/usePluginPageExtensions'; -import { useGetSingle, useFetchStatus, useFetchDetailsStatus } from '../state/hooks'; -import { PluginTabIds } from '../types'; +import { useGetSingle, useFetchStatus, useFetchDetailsStatus, useGetPluginInsights } from '../state/hooks'; import { PluginDetailsDeprecatedWarning } from './PluginDetailsDeprecatedWarning'; @@ -49,12 +48,10 @@ export function PluginDetailsPage({ }; const queryParams = new URLSearchParams(location.search); const plugin = useGetSingle(pluginId); // fetches the plugin settings for this Grafana instance + useGetPluginInsights(pluginId, plugin?.isInstalled ? plugin?.installedVersion : plugin?.latestVersion); + const isNarrowScreen = useMedia('(max-width: 600px)'); - const { navModel, activePageId } = usePluginDetailsTabs( - plugin, - queryParams.get('page') as PluginTabIds, - isNarrowScreen - ); + const { navModel, activePageId } = usePluginDetailsTabs(plugin, queryParams.get('page'), isNarrowScreen); const { actions, info, subtitle } = usePluginPageExtensions(plugin); const { isLoading: isFetchLoading } = useFetchStatus(); const { isLoading: isFetchDetailsLoading } = useFetchDetailsStatus(); diff --git a/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx b/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx index eade37f559c..20787099842 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx @@ -1,11 +1,23 @@ +import userEvent from '@testing-library/user-event'; import { render, screen } from 'test/test-utils'; import { PluginSignatureStatus, PluginSignatureType, PluginType } from '@grafana/data'; +import { config } from '@grafana/runtime'; -import { CatalogPlugin } from '../types'; +import { CatalogPlugin, SCORE_LEVELS } from '../types'; import { PluginDetailsPanel } from './PluginDetailsPanel'; +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + config: { + ...jest.requireActual('@grafana/runtime').config, + featureToggles: { + pluginInsights: false, + }, + }, +})); + const mockPlugin: CatalogPlugin = { description: 'Test plugin description', downloads: 1000, @@ -185,4 +197,61 @@ describe('PluginDetailsPanel', () => { expect(regularLinks).toContainElement(raiseIssueLink); expect(regularLinks).not.toContainElement(websiteLink); }); + + it('should render plugin insights when plugin has insights', async () => { + config.featureToggles.pluginInsights = true; + const pluginWithInsights = { + ...mockPlugin, + insights: { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [ + { + name: 'security', + scoreValue: 90, + scoreLevel: SCORE_LEVELS.EXCELLENT, + items: [ + { + id: 'signature', + name: 'Signature verified', + level: 'ok' as const, + }, + ], + }, + ], + }, + }; + render(); + expect(screen.getByTestId('plugin-insights-container')).toBeInTheDocument(); + expect(screen.getByText('Plugin insights')).toBeInTheDocument(); + expect(screen.queryByText('Security')).toBeInTheDocument(); + await userEvent.click(screen.getByText('Security')); + expect(screen.getByTestId('plugin-insight-item-signature')).toBeInTheDocument(); + }); + + it('should not render plugin insights when plugin has no insights', () => { + const pluginWithoutInsights = { + ...mockPlugin, + insights: undefined, + }; + render(); + expect(screen.queryByTestId('plugin-insights-container')).not.toBeInTheDocument(); + expect(screen.queryByText('Plugin insights')).not.toBeInTheDocument(); + }); + + it('should not render plugin insights when insights array is empty', () => { + const pluginWithEmptyInsights = { + ...mockPlugin, + insights: { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [], + }, + }; + render(); + expect(screen.queryByTestId('plugin-insights-container')).not.toBeInTheDocument(); + expect(screen.queryByText('Plugin insights')).not.toBeInTheDocument(); + }); }); diff --git a/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx b/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx index 00211b61c6e..aa8b6c792ef 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { t, Trans } from '@grafana/i18n'; -import { reportInteraction } from '@grafana/runtime'; +import { config, reportInteraction } from '@grafana/runtime'; import { PageInfoItem } from '@grafana/runtime/internal'; import { Stack, @@ -22,6 +22,8 @@ import { formatDate } from 'app/core/internationalization/dates'; import { CatalogPlugin } from '../types'; +import { PluginInsights } from './PluginInsights'; + type Props = { pluginExtentionsInfo: PageInfoItem[]; plugin: CatalogPlugin; width?: string }; export function PluginDetailsPanel(props: Props): React.ReactElement | null { @@ -69,6 +71,11 @@ export function PluginDetailsPanel(props: Props): React.ReactElement | null { return ( <> + {config.featureToggles.pluginInsights && plugin.insights && plugin.insights?.insights?.length > 0 && ( + + + + )} {pluginExtentionsInfo.map((infoItem, index) => { diff --git a/public/app/features/plugins/admin/components/PluginInsights.test.tsx b/public/app/features/plugins/admin/components/PluginInsights.test.tsx new file mode 100644 index 00000000000..efd064c7172 --- /dev/null +++ b/public/app/features/plugins/admin/components/PluginInsights.test.tsx @@ -0,0 +1,171 @@ +import userEvent from '@testing-library/user-event'; +import { render, screen } from 'test/test-utils'; + +import { CatalogPluginInsights, InsightLevel, SCORE_LEVELS } from '../types'; + +import { PluginInsights } from './PluginInsights'; + +const mockPluginInsights: CatalogPluginInsights = { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [ + { + name: 'security', + scoreValue: 90, + scoreLevel: SCORE_LEVELS.EXCELLENT, + items: [ + { + id: 'signature', + name: 'Signature verified', + description: 'Plugin signature is valid', + level: 'ok' as InsightLevel, + }, + { + id: 'trackingscripts', + name: 'No unsafe JavaScript detected', + level: 'good' as InsightLevel, + }, + ], + }, + { + name: 'quality', + scoreValue: 60, + scoreLevel: SCORE_LEVELS.FAIR, + items: [ + { + id: 'metadatavalid', + name: 'Metadata is valid', + level: 'ok' as InsightLevel, + }, + { + id: 'code-rules', + name: 'Missing code rules', + description: 'Plugin lacks comprehensive code rules', + level: 'warning' as InsightLevel, + }, + ], + }, + ], +}; + +const mockPluginInsightsWithPoorLevel: CatalogPluginInsights = { + id: 3, + name: 'test-plugin-poor', + version: '0.8.0', + insights: [ + { + name: 'quality', + scoreValue: 35, + scoreLevel: SCORE_LEVELS.POOR, + items: [ + { + id: 'legacy-platform', + name: 'Quality issues detected', + level: 'warning' as InsightLevel, + }, + ], + }, + ], +}; + +describe('PluginInsights', () => { + it('should render plugin insights section', () => { + render(); + const insightsSection = screen.getByTestId('plugin-insights-container'); + expect(insightsSection).toBeInTheDocument(); + expect(screen.getByText('Plugin insights')).toBeInTheDocument(); + }); + + it('should render all insight categories with test ids', () => { + render(); + expect(screen.getByTestId('plugin-insight-security')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-quality')).toBeInTheDocument(); + }); + + it('should render category names with test ids', () => { + render(); + const securityCategory = screen.getByTestId('plugin-insight-security'); + const qualityCategory = screen.getByTestId('plugin-insight-quality'); + + expect(securityCategory).toBeInTheDocument(); + expect(securityCategory).toHaveTextContent('Security'); + expect(qualityCategory).toBeInTheDocument(); + expect(qualityCategory).toHaveTextContent('Quality'); + }); + + it('should render individual insight items with test ids', async () => { + render(); + await userEvent.click(screen.getByText('Security')); + expect(screen.getByTestId('plugin-insight-item-signature')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-item-trackingscripts')).toBeInTheDocument(); + await userEvent.click(screen.getByText('Quality')); + expect(screen.getByTestId('plugin-insight-item-metadatavalid')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-item-code-rules')).toBeInTheDocument(); + }); + + it('should display correct icons for Excellent score level', () => { + render(); + + const securityCategory = screen.getByTestId('plugin-insight-security'); + const securityIcon = securityCategory.querySelector('[data-testid="excellent-icon"]'); + expect(securityIcon).toBeInTheDocument(); + }); + + it('should display correct icons for Poor score levels', () => { + // Test Poor level - should show exclamation-triangle + render(); + const poorCategory = screen.getByTestId('plugin-insight-quality'); + const poorIcon = poorCategory.querySelector('[data-testid="poor-icon"]'); + expect(poorIcon).toBeInTheDocument(); + }); + + it('should handle multiple items with different insight levels', async () => { + const multiLevelInsights: CatalogPluginInsights = { + id: 5, + name: 'multi-level-plugin', + version: '2.0.0', + insights: [ + { + name: 'quality', + scoreValue: 75, + scoreLevel: SCORE_LEVELS.GOOD, + items: [ + { + id: 'code-rules', + name: 'Info level item', + level: 'info' as InsightLevel, + }, + { + id: 'sdk-usage', + name: 'OK level item', + level: 'ok' as InsightLevel, + }, + { + id: 'jsMap', + name: 'Good level item', + level: 'good' as InsightLevel, + }, + { + id: 'gosec', + name: 'Warning level item', + level: 'warning' as InsightLevel, + }, + { + id: 'legacy-builder', + name: 'Danger level item', + level: 'danger' as InsightLevel, + }, + ], + }, + ], + }; + render(); + await userEvent.click(screen.getByText('Quality')); + expect(screen.getByText('Info level item')).toBeInTheDocument(); + expect(screen.getByText('OK level item')).toBeInTheDocument(); + expect(screen.getByText('Good level item')).toBeInTheDocument(); + expect(screen.getByText('Warning level item')).toBeInTheDocument(); + expect(screen.getByText('Danger level item')).toBeInTheDocument(); + }); +}); diff --git a/public/app/features/plugins/admin/components/PluginInsights.tsx b/public/app/features/plugins/admin/components/PluginInsights.tsx new file mode 100644 index 00000000000..805bcf926bf --- /dev/null +++ b/public/app/features/plugins/admin/components/PluginInsights.tsx @@ -0,0 +1,140 @@ +import { css } from '@emotion/css'; +import { capitalize } from 'lodash'; +import { useState } from 'react'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { Trans } from '@grafana/i18n'; +import { reportInteraction } from '@grafana/runtime'; +import { Stack, Text, TextLink, CollapsableSection, Tooltip, Icon, useStyles2, useTheme2 } from '@grafana/ui'; + +import { CatalogPluginInsights } from '../types'; + +type Props = { pluginInsights: CatalogPluginInsights | undefined }; + +const PLUGINS_INSIGHTS_OPENED_EVENT_NAME = 'plugins_insights_opened'; + +export function PluginInsights(props: Props): React.ReactElement | null { + const { pluginInsights } = props; + const styles = useStyles2(getStyles); + const theme = useTheme2(); + const [openInsights, setOpenInsights] = useState>({}); + + const handleInsightToggle = (insightName: string, isOpen: boolean) => { + if (isOpen) { + reportInteraction(PLUGINS_INSIGHTS_OPENED_EVENT_NAME, { insight: insightName }); + } + setOpenInsights((prev) => ({ ...prev, [insightName]: isOpen })); + }; + + const tooltipInfo = ( + + + + + + All relevant signals are present and verified + + + + + + + + One or more signals are missing or need attention + + + +
+ + + Do you find Plugin Insights usefull? Please share your feedback{' '} + + here + + . + + +
+ ); + + return ( + <> + + + + Plugin insights + + + + + + {pluginInsights?.insights.map((insightItem, index) => { + return ( + + handleInsightToggle(insightItem.name, isOpen)} + label={ + + {insightItem.scoreLevel === 'Excellent' ? ( + + ) : ( + + )} + + {capitalize(insightItem.name)} + + + } + contentClassName={styles.pluginInsightsItems} + > + + {insightItem.items.map((item, idx) => ( + + + {item.level === 'good' ? ( + + ) : ( + + )} + + + {item.name} + + + ))} + + + + ); + })} + + + ); +} + +export const getStyles = (theme: GrafanaTheme2) => { + return { + pluginVersionDetails: css({ wordBreak: 'break-word' }), + pluginInsightsItems: css({ marginLeft: '26px', paddingTop: '0 !important' }), + pluginInsightsTooltipSeparator: css({ + border: 'none', + borderTop: `1px solid ${theme.colors.border.medium}`, + margin: `${theme.spacing(1)} 0`, + }), + }; +}; diff --git a/public/app/features/plugins/admin/hooks/usePluginDetailsTabs.tsx b/public/app/features/plugins/admin/hooks/usePluginDetailsTabs.tsx index ab616988e3f..6cb8ec39af4 100644 --- a/public/app/features/plugins/admin/hooks/usePluginDetailsTabs.tsx +++ b/public/app/features/plugins/admin/hooks/usePluginDetailsTabs.tsx @@ -18,9 +18,9 @@ type ReturnType = { }; function getCurrentPageId( - pageId: PluginTabIds | undefined, isNarrowScreen: boolean | undefined, - defaultTab: string + defaultTab: string, + pageId?: PluginTabIds | string | null ): PluginTabIds | string { if (!isNarrowScreen && pageId === PluginTabIds.PLUGINDETAILS) { return defaultTab; @@ -30,7 +30,7 @@ function getCurrentPageId( export const usePluginDetailsTabs = ( plugin?: CatalogPlugin, - pageId?: PluginTabIds, + pageId?: PluginTabIds | string | null, isNarrowScreen?: boolean ): ReturnType => { const { loading, error, value: pluginConfig } = usePluginConfig(plugin); @@ -38,7 +38,7 @@ export const usePluginDetailsTabs = ( const defaultTab = useDefaultPage(plugin, pluginConfig); const isPublished = Boolean(plugin?.isPublished); - const currentPageId = getCurrentPageId(pageId, isNarrowScreen, defaultTab); + const currentPageId = getCurrentPageId(isNarrowScreen, defaultTab, pageId); const navModelChildren = useMemo(() => { const canConfigurePlugins = plugin && contextSrv.hasPermissionInMetadata(AccessControlAction.PluginsWrite, plugin); diff --git a/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts b/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts index 9ced4f20a84..3625b687f7b 100644 --- a/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts +++ b/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts @@ -34,6 +34,7 @@ export default { updatedAt: '2021-08-25T15:03:49.000Z', version: '4.2.2', error: undefined, + insights: { id: 1, name: 'alexanderzobnin-zabbix-app', version: '4.2.2', insights: [] }, details: { grafanaDependency: '>=8.0.0', pluginDependencies: [], @@ -381,6 +382,7 @@ export const datasourcePlugin = { angularDetected: false, isFullyInstalled: true, latestVersion: '1.20.0', + insights: { id: 2, name: 'grafana-redshift-datasource', version: '1.20.0', insights: [] }, details: { grafanaDependency: '>=8.0.0', pluginDependencies: [], diff --git a/public/app/features/plugins/admin/mocks/mockHelpers.ts b/public/app/features/plugins/admin/mocks/mockHelpers.ts index 6034e8860e9..d6e04186f77 100644 --- a/public/app/features/plugins/admin/mocks/mockHelpers.ts +++ b/public/app/features/plugins/admin/mocks/mockHelpers.ts @@ -31,6 +31,9 @@ export const getPluginsStateMock = (plugins: CatalogPlugin[] = []): ReducerState 'plugins/fetchDetails': { status: RequestStatus.Fulfilled, }, + 'plugins/fetchPluginInsights': { + status: RequestStatus.Fulfilled, + }, }, // Backward compatibility plugins: [], @@ -75,6 +78,11 @@ export const mockPluginApis = ({ return Promise.resolve({ items: versions }); } + // Mock plugin insights - return empty insights to avoid API call errors + if (path.includes('/insights')) { + return Promise.resolve({ id: 1, name: '', version: '', insights: [] }); + } + // Mock local plugin settings (installed) if necessary if (local && path === `${API_ROOT}/${local.id}/settings`) { return Promise.resolve(local); diff --git a/public/app/features/plugins/admin/state/actions.ts b/public/app/features/plugins/admin/state/actions.ts index 6be68111dd5..e9cf2d9d40d 100644 --- a/public/app/features/plugins/admin/state/actions.ts +++ b/public/app/features/plugins/admin/state/actions.ts @@ -13,6 +13,7 @@ import { getPluginErrors, getLocalPlugins, getPluginDetails, + getPluginInsights, installPlugin, uninstallPlugin, getInstancePlugins, @@ -165,6 +166,22 @@ export const fetchDetails = createAsyncThunk, stri } ); +export const fetchPluginInsights = createAsyncThunk, { id: string; version?: string }>( + `${STATE_PREFIX}/fetchPluginInsights`, + async ({ id, version }, thunkApi) => { + try { + const insights = await getPluginInsights(id, version); + + return { + id, + changes: { insights }, + }; + } catch (e) { + return thunkApi.rejectWithValue('Unknown error.'); + } + } +); + export const addPlugins = createAction(`${STATE_PREFIX}/addPlugins`); // 1. gets remote equivalents from the store (if there are any) @@ -265,7 +282,8 @@ export const panelPluginLoaded = createAction(`${STATE_PREFIX}/pane // TODO export const loadPanelPlugin = (id: string): ThunkResult> => { return async (dispatch, getStore) => { - let plugin = getStore().plugins.panels[id]; + const state = getStore(); + let plugin = state.plugins.panels[id]; if (!plugin) { plugin = await importPanelPlugin(id); diff --git a/public/app/features/plugins/admin/state/hooks.ts b/public/app/features/plugins/admin/state/hooks.ts index 2185ec99465..6eb47d7e1aa 100644 --- a/public/app/features/plugins/admin/state/hooks.ts +++ b/public/app/features/plugins/admin/state/hooks.ts @@ -6,7 +6,16 @@ import { useDispatch, useSelector } from 'app/types/store'; import { sortPlugins, Sorters, isPluginUpdatable } from '../helpers'; import { CatalogPlugin, PluginStatus } from '../types'; -import { fetchAll, fetchDetails, fetchRemotePlugins, install, uninstall, fetchAllLocal, unsetInstall } from './actions'; +import { + fetchAll, + fetchDetails, + fetchRemotePlugins, + install, + uninstall, + fetchAllLocal, + unsetInstall, + fetchPluginInsights, +} from './actions'; import { selectPlugins, selectById, @@ -44,13 +53,18 @@ export const useGetUpdatable = () => { }; }; -export const useGetSingle = (id: string): CatalogPlugin | undefined => { +export const useGetSingle = (id: string, version?: string): CatalogPlugin | undefined => { useFetchAll(); useFetchDetails(id); return useSelector((state) => selectById(state, id)); }; +export const useGetPluginInsights = (id: string, version: string | undefined): CatalogPlugin | undefined => { + useFetchPluginInsights(id, version); + return useSelector((state) => selectById(state, id)); +}; + export const useGetSingleLocalWithoutDetails = (id: string): CatalogPlugin | undefined => { useFetchAllLocal(); return useSelector((state) => selectById(state, id)); @@ -153,6 +167,17 @@ export const useFetchDetails = (id: string) => { }, [plugin]); // eslint-disable-line }; +export const useFetchPluginInsights = (id: string, version: string | undefined) => { + const dispatch = useDispatch(); + const plugin = useSelector((state) => selectById(state, id)); + const isNotFetching = !useSelector(selectIsRequestPending(fetchPluginInsights.typePrefix)); + const shouldFetch = isNotFetching && plugin && !plugin.insights && version; + + useEffect(() => { + shouldFetch && dispatch(fetchPluginInsights({ id, version })); + }, [plugin, version]); // eslint-disable-line +}; + export const useFetchDetailsLazy = () => { const dispatch = useDispatch(); diff --git a/public/app/features/plugins/admin/state/reducer.ts b/public/app/features/plugins/admin/state/reducer.ts index f2414a31405..e3d5bec5427 100644 --- a/public/app/features/plugins/admin/state/reducer.ts +++ b/public/app/features/plugins/admin/state/reducer.ts @@ -7,6 +7,7 @@ import { CatalogPlugin, ReducerState, RequestStatus } from '../types'; import { fetchDetails, + fetchPluginInsights, install, uninstall, loadPluginDashboards, @@ -63,6 +64,10 @@ const slice = createSlice({ .addCase(fetchDetails.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); }) + // Fetch Plugin Insights + .addCase(fetchPluginInsights.fulfilled, (state, action) => { + pluginsAdapter.updateOne(state.items, action.payload); + }) // Install .addCase(install.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); diff --git a/public/app/features/plugins/admin/types.ts b/public/app/features/plugins/admin/types.ts index 3cc66bba0b9..df4114101b4 100644 --- a/public/app/features/plugins/admin/types.ts +++ b/public/app/features/plugins/admin/types.ts @@ -55,6 +55,7 @@ export interface CatalogPlugin extends WithAccessControlMetadata { updatedAt: string; installedVersion?: string; details?: CatalogPluginDetails; + insights?: CatalogPluginInsights; error?: PluginErrorCode; angularDetected?: boolean; // instance plugins may not be fully installed, which means a new instance @@ -90,6 +91,54 @@ export interface CatalogPluginDetails { screenshots?: Screenshots[] | null; } +export type InsightLevel = 'ok' | 'warning' | 'danger' | 'good' | 'info'; + +export const SCORE_LEVELS = { + EXCELLENT: 'Excellent', + GOOD: 'Good', + FAIR: 'Fair', + POOR: 'Poor', + CRITICAL: 'Critical', +} as const; + +export type ScoreLevel = (typeof SCORE_LEVELS)[keyof typeof SCORE_LEVELS]; + +export const INSIGHT_CATEGORIES = { + SECURITY: 'security', + QUALITY: 'quality', + PERFORMANCE: 'performance', +} as const; + +export const INSIGHT_LEVELS = { + GOOD: 'good', + OK: 'ok', + WARNING: 'warning', + DANGER: 'danger', + INFO: 'info', +} as const; + +export interface InsightItem { + id: string; + name: string; + description?: string; + level: InsightLevel; + link?: string; +} + +export interface InsightCategory { + name: string; + items: InsightItem[]; + scoreValue: number; + scoreLevel: ScoreLevel; +} + +export interface CatalogPluginInsights { + id: number; + name: string; + version: string; + insights: InsightCategory[]; +} + export interface CatalogPluginInfo { logos: { large: string; small: string }; keywords: string[]; diff --git a/public/app/features/plugins/importPanelPlugin.ts b/public/app/features/plugins/importPanelPlugin.ts index e541b8f7893..ef8d955f562 100644 --- a/public/app/features/plugins/importPanelPlugin.ts +++ b/public/app/features/plugins/importPanelPlugin.ts @@ -62,3 +62,9 @@ export function syncGetPanelPlugin(id: string): PanelPlugin | undefined { function getPanelPlugin(meta: PanelPluginMeta): Promise { return pluginImporter.importPanel(meta); } + +export function clearPanelPluginCache(): void { + for (const key of Object.keys(promiseCache)) { + delete promiseCache[key]; + } +} diff --git a/public/app/features/provisioning/Config/ConfigForm.tsx b/public/app/features/provisioning/Config/ConfigForm.tsx index a29bc68329e..3b1aebc1911 100644 --- a/public/app/features/provisioning/Config/ConfigForm.tsx +++ b/public/app/features/provisioning/Config/ConfigForm.tsx @@ -28,7 +28,6 @@ import { FormPrompt } from 'app/core/components/FormPrompt/FormPrompt'; import { DeleteRepositoryButton } from '../Repository/DeleteRepositoryButton'; import { TokenPermissionsInfo } from '../Shared/TokenPermissionsInfo'; import { getGitProviderFields, getLocalProviderFields } from '../Wizard/fields'; -import { InlineSecureValueWarning } from '../components/InlineSecureValueWarning'; import { PROVISIONING_URL } from '../constants'; import { useCreateOrUpdateRepository } from '../hooks/useCreateOrUpdateRepository'; import { RepositoryFormData } from '../types'; @@ -80,10 +79,7 @@ export function ConfigForm({ data }: ConfigFormProps) { const [isLoading, setIsLoading] = useState(false); const navigate = useNavigate(); const [type, readOnly] = watch(['type', 'readOnly']); - const targetOptions = useMemo( - () => getTargetOptions(settings.data?.allowedTargets || ['instance', 'folder']), - [settings.data] - ); + const targetOptions = useMemo(() => getTargetOptions(settings.data?.allowedTargets || ['folder']), [settings.data]); const isGitBased = isGitProvider(type); const { @@ -181,7 +177,6 @@ export function ConfigForm({ data }: ConfigFormProps) { {gitFields && ( <> - } > - diff --git a/public/app/features/provisioning/Job/JobStatus.tsx b/public/app/features/provisioning/Job/JobStatus.tsx index 02e0b733bbb..7aec776f8aa 100644 --- a/public/app/features/provisioning/Job/JobStatus.tsx +++ b/public/app/features/provisioning/Job/JobStatus.tsx @@ -1,8 +1,11 @@ +import { useEffect } from 'react'; + import { Trans, t } from '@grafana/i18n'; import { Spinner, Stack, Text } from '@grafana/ui'; import { Job, useListJobQuery } from 'app/api/clients/provisioning/v0alpha1'; import { StepStatusInfo } from '../Wizard/types'; +import { getErrorMessage } from '../utils/httpUtils'; import { FinishedJobStatus } from './FinishedJobStatus'; import { JobContent } from './JobContent'; @@ -25,6 +28,18 @@ export function JobStatus({ jobType, watch, onStatusChange }: JobStatusProps) { const activeQueryCompleted = !activeQuery.isUninitialized && !activeQuery.isLoading; const shouldCheckFinishedJobs = activeQueryCompleted && !activeJob && !!repoLabel; + useEffect(() => { + if (activeQuery.isError) { + onStatusChange?.({ + status: 'error', + error: { + title: t('provisioning.job-status.title.error-fetching-active-job', 'Error fetching active job'), + message: getErrorMessage(activeQuery.error), + }, + }); + } + }, [activeQuery.isError, activeQuery.error, onStatusChange]); + if (activeQuery.isLoading) { return ( @@ -37,12 +52,6 @@ export function JobStatus({ jobType, watch, onStatusChange }: JobStatusProps) { } if (activeQuery.isError) { - onStatusChange?.({ - status: 'error', - error: { - title: t('provisioning.job-status.title.error-fetching-active-job', 'Error fetching active job'), - }, - }); return null; } diff --git a/public/app/features/provisioning/Repository/RepositoryStatusPage.tsx b/public/app/features/provisioning/Repository/RepositoryStatusPage.tsx index a8984eaa51f..e18e47500da 100644 --- a/public/app/features/provisioning/Repository/RepositoryStatusPage.tsx +++ b/public/app/features/provisioning/Repository/RepositoryStatusPage.tsx @@ -10,8 +10,8 @@ import { Page } from 'app/core/components/Page/Page'; import { useQueryParams } from 'app/core/hooks/useQueryParams'; import { isNotFoundError } from 'app/features/alerting/unified/api/util'; -import { InlineSecureValueWarning } from '../components/InlineSecureValueWarning'; import { PROVISIONING_URL } from '../constants'; +import { getErrorMessage } from '../utils/httpUtils'; import { RepositoryActions } from './RepositoryActions'; import { RepositoryOverview } from './RepositoryOverview'; @@ -36,6 +36,7 @@ export default function RepositoryStatusPage() { const tab = queryParams['tab'] ?? TabSelection.Overview; const notFound = query.isError && isNotFoundError(query.error); + const hasError = query.isError && !notFound; const tabInfo = useMemo>( () => [ @@ -63,7 +64,11 @@ export default function RepositoryStatusPage() { actions={data && } > - + {hasError && ( + + {getErrorMessage(query.error)} + + )} {notFound ? ( item.metadata?.name?.includes(query)); const { instanceConnected } = checkSyncSettings(items); + const hasInstanceSyncRepo = items.some((item) => item.spec?.sync?.target === 'instance'); const getResourceCountSection = () => { if (isProvisionedInstance) { @@ -77,6 +78,17 @@ export function RepositoryList({ items }: Props) { return ( <> {getResourceCountSection()} + {hasInstanceSyncRepo && ( + + + Instance sync is currently not fully supported and breaks library panels and alerts. To use library panels + and alerts, disconnect your repository and reconnect it using folder sync instead. + + + )} {!instanceConnected && ( diff --git a/public/app/features/provisioning/Wizard/BootstrapStep.test.tsx b/public/app/features/provisioning/Wizard/BootstrapStep.test.tsx index 90d566415b9..24d7e322ac3 100644 --- a/public/app/features/provisioning/Wizard/BootstrapStep.test.tsx +++ b/public/app/features/provisioning/Wizard/BootstrapStep.test.tsx @@ -32,7 +32,7 @@ function FormWrapper({ children, defaultValues }: { children: ReactNode; default url: 'https://github.com/test/repo', title: '', sync: { - target: 'instance', + target: 'folder', enabled: true, }, branch: 'main', @@ -101,12 +101,6 @@ describe('BootstrapStep', () => { (useModeOptions as jest.Mock).mockReturnValue({ enabledOptions: [ - { - target: 'instance', - label: 'Sync all resources with external storage', - description: 'Resources will be synced with external storage', - subtitle: 'Use this option if you want to sync your entire instance', - }, { target: 'folder', label: 'Sync external storage to a new Grafana folder', @@ -142,8 +136,8 @@ describe('BootstrapStep', () => { it('should render correct info for GitHub repository type', async () => { setup(); - expect(screen.getAllByText('External storage')).toHaveLength(2); - expect(screen.getAllByText('Empty')).toHaveLength(4); // Four elements should show "Empty" (2 external + 2 unmanaged, one per card) + expect(screen.getAllByText('External storage')).toHaveLength(1); // Only folder sync is shown by default + expect(screen.getAllByText('Empty')).toHaveLength(2); // Two elements should have the role "Empty" (1 external + 1 unmanaged) }); it('should render correct info for local file repository type', async () => { @@ -171,10 +165,12 @@ describe('BootstrapStep', () => { setup(); - expect(await screen.getAllByText('2 files')).toHaveLength(2); + expect(await screen.getAllByText('2 files')).toHaveLength(1); // Only folder sync is shown by default }); it('should display resource counts when resources exist', async () => { + // Note: Resource counts are only shown for instance sync, but instance sync is not available by default + // This test is kept for when instance sync is explicitly enabled via settings (useGetResourceStatsQuery as jest.Mock).mockReturnValue({ data: { instance: [ @@ -196,10 +192,29 @@ describe('BootstrapStep', () => { shouldSkipSync: false, }); - setup(); + // Mock settings to allow instance sync for this test + (useModeOptions as jest.Mock).mockReturnValue({ + enabledOptions: [ + { + target: 'instance', + label: 'Sync all resources with external storage', + description: 'Resources will be synced with external storage', + subtitle: 'Use this option if you want to sync your entire instance', + }, + ], + disabledOptions: [], + }); - // Two elements display "7 resources": one in the external storage card and one in unmanaged resources card - expect(await screen.findAllByText('7 resources')).toHaveLength(2); + setup({ + settingsData: { + allowedTargets: ['instance', 'folder'], + allowImageRendering: true, + items: [], + availableRepositoryTypes: [], + }, + }); + + expect(await screen.findByText('7 resources')).toBeInTheDocument(); }); }); @@ -208,16 +223,30 @@ describe('BootstrapStep', () => { setup(); const mockUseResourceStats = require('./hooks/useResourceStats').useResourceStats; - expect(mockUseResourceStats).toHaveBeenCalledWith('test-repo', 'instance'); + expect(mockUseResourceStats).toHaveBeenCalledWith('test-repo', 'folder'); + }); + + it('should use useResourceStats hook with settings data', async () => { + setup({ + settingsData: { + allowedTargets: ['folder'], + allowImageRendering: true, + items: [], + availableRepositoryTypes: [], + }, + }); + + const mockUseResourceStats = require('./hooks/useResourceStats').useResourceStats; + expect(mockUseResourceStats).toHaveBeenCalledWith('test-repo', 'folder'); }); }); describe('sync target options', () => { - it('should display both instance and folder options by default', async () => { + it('should display only folder option by default', async () => { setup(); - expect(await screen.findByText('Sync all resources with external storage')).toBeInTheDocument(); expect(await screen.findByText('Sync external storage to a new Grafana folder')).toBeInTheDocument(); + expect(screen.queryByText('Sync all resources with external storage')).not.toBeInTheDocument(); }); it('should only display instance option when legacy storage exists', async () => { @@ -242,6 +271,7 @@ describe('BootstrapStep', () => { setup({ settingsData: { + allowedTargets: ['instance', 'folder'], allowImageRendering: true, items: [], availableRepositoryTypes: [], @@ -264,15 +294,10 @@ describe('BootstrapStep', () => { }); describe('title field visibility', () => { - it('should show title field only for folder sync target', async () => { - const { user } = setup(); - - // Initially should not show title field (default is instance) - expect(screen.queryByRole('textbox', { name: /display name/i })).not.toBeInTheDocument(); - - const folderOption = await screen.findByText('Sync external storage to a new Grafana folder'); - await user.click(folderOption); + it('should show title field for folder sync target', async () => { + setup(); + // Default is folder, so title field should be visible expect(await screen.findByRole('textbox', { name: /display name/i })).toBeInTheDocument(); }); }); diff --git a/public/app/features/provisioning/Wizard/ProvisioningWizard.test.tsx b/public/app/features/provisioning/Wizard/ProvisioningWizard.test.tsx index 24d23acc607..db49c3bb86e 100644 --- a/public/app/features/provisioning/Wizard/ProvisioningWizard.test.tsx +++ b/public/app/features/provisioning/Wizard/ProvisioningWizard.test.tsx @@ -227,6 +227,15 @@ describe('ProvisioningWizard', () => { error: null, refetch: jest.fn(), }); + // Mock files to ensure sync step is not skipped for folder sync + mockUseGetRepositoryFilesQuery.mockReturnValue({ + data: { + items: [{ name: 'test.json', path: 'test.json' }], + }, + isLoading: false, + error: null, + refetch: jest.fn(), + }); const { user } = setup(); await fillConnectionForm(user, 'github', { @@ -500,10 +509,10 @@ describe('ProvisioningWizard', () => { }); it('should show button text changes based on current step', async () => { - // Mock resources to ensure sync step is not skipped - mockUseGetResourceStatsQuery.mockReturnValue({ + // Mock files to ensure sync step is not skipped for folder sync + mockUseGetRepositoryFilesQuery.mockReturnValue({ data: { - instance: [{ group: 'dashboard.grafana.app', count: 1 }], + items: [{ name: 'test.json', path: 'test.json' }], }, isLoading: false, error: null, diff --git a/public/app/features/provisioning/Wizard/hooks/useModeOptions.ts b/public/app/features/provisioning/Wizard/hooks/useModeOptions.ts index 4bf817b091e..3d288ab487d 100644 --- a/public/app/features/provisioning/Wizard/hooks/useModeOptions.ts +++ b/public/app/features/provisioning/Wizard/hooks/useModeOptions.ts @@ -10,7 +10,7 @@ import { ModeOption } from '../types'; */ function filterModeOptions(modeOptions: ModeOption[], repoName: string, settings?: RepositoryViewList): ModeOption[] { const folderConnected = settings?.items?.some((item) => item.target === 'folder' && item.name !== repoName); - const allowedTargets = settings?.allowedTargets || ['instance', 'folder']; + const allowedTargets = settings?.allowedTargets || ['folder']; return modeOptions.map((option) => { if (option.disabled) { diff --git a/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts b/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts index dd4b222cb19..5daaed87f95 100644 --- a/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts +++ b/public/app/features/provisioning/Wizard/hooks/useResourceStats.ts @@ -121,22 +121,10 @@ export function useResourceStats(repoName?: string, syncTarget?: RepositoryView[ }; }, [resourceStatsQuery.data]); - // Calculate base requiresMigration: true if there are resources to migrate - const baseRequiresMigration = resourceCount > 0; - - // Calculate final requiresMigration based on sync target and user selection - // For instance sync: always use baseRequiresMigration (checkbox is disabled and always true) + // Calculate requiresMigration based on sync target and user selection + // For instance sync: migrate if there are resources (checkbox is disabled and always true) // For folder sync: only migrate if user explicitly opts in via checkbox - const requiresMigration = useMemo(() => { - if (syncTarget === 'instance') { - return baseRequiresMigration; - } - if (syncTarget === 'folder') { - return migrateResources ?? false; - } - return baseRequiresMigration; - }, [syncTarget, baseRequiresMigration, migrateResources]); - + const requiresMigration = syncTarget === 'instance' ? resourceCount > 0 : (migrateResources ?? false); const shouldSkipSync = (resourceCount === 0 || syncTarget === 'folder') && fileCount === 0; // Format display strings diff --git a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.test.tsx b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.test.tsx index bca9ca1939c..69a94c5e9ae 100644 --- a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.test.tsx +++ b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.test.tsx @@ -9,7 +9,7 @@ import { DashboardScene } from 'app/features/dashboard-scene/scene/DashboardScen import { validationSrv } from 'app/features/manage-dashboards/services/ValidationSrv'; import { useCreateOrUpdateRepositoryFile } from 'app/features/provisioning/hooks/useCreateOrUpdateRepositoryFile'; -import { SaveProvisionedDashboardForm, Props } from './SaveProvisionedDashboardForm'; +import { Props, SaveProvisionedDashboardForm } from './SaveProvisionedDashboardForm'; jest.mock('@grafana/runtime', () => { const actual = jest.requireActual('@grafana/runtime'); @@ -118,6 +118,7 @@ function setup(props: Partial = {}) { closeModal: jest.fn(), getSaveAsModel: jest.fn().mockReturnValue(mockDashboard), setManager: jest.fn(), + getRawJsonFromEditor: jest.fn().mockReturnValue(undefined), } as unknown as DashboardScene, drawer: { onClose: jest.fn(), @@ -291,6 +292,7 @@ describe('SaveProvisionedDashboardForm', () => { closeModal: jest.fn(), getSaveResource: jest.fn().mockReturnValue(updatedDashboard), setManager: jest.fn(), + getRawJsonFromEditor: jest.fn().mockReturnValue(undefined), } as unknown as DashboardScene, }); @@ -385,6 +387,7 @@ describe('SaveProvisionedDashboardForm', () => { closeModal: jest.fn(), getSaveAsModel: jest.fn().mockReturnValue({}), setManager: jest.fn(), + getRawJsonFromEditor: jest.fn().mockReturnValue(undefined), } as unknown as DashboardScene, }); @@ -431,6 +434,7 @@ describe('SaveProvisionedDashboardForm', () => { closeModal: jest.fn(), getSaveAsModel: jest.fn().mockReturnValue({}), setManager: jest.fn(), + getRawJsonFromEditor: jest.fn().mockReturnValue(undefined), } as unknown as DashboardScene, }); @@ -445,4 +449,70 @@ describe('SaveProvisionedDashboardForm', () => { expect(saveButton).toBeEnabled(); }); }); + + it('should save dashboard with raw JSON from editor', async () => { + const mockAction = jest.fn(); + const mockRequest = { ...mockRequestBase, isSuccess: true }; + (useCreateOrUpdateRepositoryFile as jest.Mock).mockReturnValue([mockAction, mockRequest]); + + const rawJson = JSON.stringify({ + title: 'Raw JSON Dashboard', + panels: [], + schemaVersion: 36, + }); + + const dashboardFromRawJson = { + apiVersion: 'dashboard.grafana.app/v1alpha1', + kind: 'Dashboard', + metadata: { + generateName: 'p', + name: undefined, + }, + spec: { + title: 'Raw JSON Dashboard', + panels: [], + schemaVersion: 36, + }, + }; + + const { user } = setup({ + dashboard: { + useState: () => ({ + meta: { + folderUid: 'folder-uid', + slug: 'test-dashboard', + }, + title: 'Test Dashboard', + description: 'Test Description', + isDirty: false, + }), + setState: jest.fn(), + closeModal: jest.fn(), + getSaveAsModel: jest.fn().mockReturnValue({}), + getSaveResource: jest.fn().mockReturnValue(dashboardFromRawJson), + getSaveResourceFromSpec: jest.fn().mockReturnValue(dashboardFromRawJson), + setManager: jest.fn(), + getRawJsonFromEditor: jest.fn().mockReturnValue(rawJson), + } as unknown as DashboardScene, + }); + + const saveButton = screen.getByRole('button', { name: /save/i }); + expect(saveButton).toBeEnabled(); + + const commentInput = screen.getByRole('textbox', { name: /comment/i }); + await user.clear(commentInput); + await user.type(commentInput, 'Save with raw JSON'); + + await user.click(saveButton); + + await waitFor(() => { + expect(mockAction).toHaveBeenCalledWith({ + ref: 'dashboard/2023-01-01-abcde', + name: 'test-repo', + path: 'test-dashboard.json', + message: 'Save with raw JSON', + body: dashboardFromRawJson, + }); + }); + }); }); diff --git a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx index a2df43a1f95..3fee476b189 100644 --- a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx +++ b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx @@ -65,8 +65,9 @@ export function SaveProvisionedDashboardForm({ register, formState: { dirtyFields }, } = methods; - // button enabled if form comment is dirty or dashboard state is dirty - const isDirtyState = Boolean(dirtyFields.comment) || isDirty; + // button enabled if form comment is dirty or dashboard state is dirty or raw JSON was provided from editor + const rawDashboardJSON = dashboard.getRawJsonFromEditor(); + const isDirtyState = Boolean(dirtyFields.comment) || isDirty || Boolean(rawDashboardJSON); const [workflow, ref, path] = watch(['workflow', 'ref', 'path']); // Update the form if default values change @@ -191,13 +192,15 @@ export function SaveProvisionedDashboardForm({ const message = comment || `Save dashboard: ${dashboard.state.title}`; - const body = dashboard.getSaveResource({ - isNew, - title, - description, - copyTags, - saveAsCopy, - }); + const body = rawDashboardJSON + ? dashboard.getSaveResourceFromSpec(rawDashboardJSON) + : dashboard.getSaveResource({ + isNew, + title, + description, + copyTags, + saveAsCopy, + }); reportInteraction('grafana_provisioning_dashboard_save_submitted', { workflow, diff --git a/public/app/features/provisioning/components/InlineSecureValueWarning.tsx b/public/app/features/provisioning/components/InlineSecureValueWarning.tsx deleted file mode 100644 index 9ed4a23b7b1..00000000000 --- a/public/app/features/provisioning/components/InlineSecureValueWarning.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { t } from '@grafana/i18n'; -import { Alert } from '@grafana/ui'; -import { Repository } from 'app/api/clients/provisioning/v0alpha1'; - -interface Props { - repo?: Repository; - items?: Repository[]; -} - -// TODO: remove this after 12.2 -export function InlineSecureValueWarning({ repo, items }: Props) { - const isRepoValid = (r?: Repository) => r?.spec?.type === 'local' || !!r?.secure?.token?.name; - - if (isRepoValid(repo)) { - return null; - } - - // When a list is passed in, show an error if anything is missing - if (items?.every(isRepoValid)) { - return null; - } - - return ( - - ); -} diff --git a/public/app/features/provisioning/utils/httpUtils.ts b/public/app/features/provisioning/utils/httpUtils.ts index 6e9cbc4e933..3fb6bd7704f 100644 --- a/public/app/features/provisioning/utils/httpUtils.ts +++ b/public/app/features/provisioning/utils/httpUtils.ts @@ -1,4 +1,5 @@ import { t } from '@grafana/i18n'; +import { isFetchError } from '@grafana/runtime'; import { HttpError, isHttpError } from '../guards'; @@ -187,6 +188,8 @@ export function getErrorMessage(err: unknown) { } else if (err.message) { errorMessage = err.message; } + } else if (isFetchError(err)) { + errorMessage = err.data.message; } return errorMessage; diff --git a/public/app/plugins/panel/radialbar/EffectsEditor.tsx b/public/app/plugins/panel/radialbar/EffectsEditor.tsx index d7a0f03cbc7..a3c26beca90 100644 --- a/public/app/plugins/panel/radialbar/EffectsEditor.tsx +++ b/public/app/plugins/panel/radialbar/EffectsEditor.tsx @@ -44,11 +44,6 @@ export function EffectsEditor(props: StandardEditorProps) { value={!!props.value?.gradient} onChange={(e) => props.onChange({ ...props.value, gradient: e.currentTarget.checked })} /> - props.onChange({ ...props.value, rounded: e.currentTarget.checked })} - /> ) { value={!!props.value?.centerGlow} onChange={(e) => props.onChange({ ...props.value, centerGlow: e.currentTarget.checked })} /> - props.onChange({ ...props.value, spotlight: e.currentTarget.checked })} - /> ); } diff --git a/public/app/plugins/panel/radialbar/RadialBarPanel.tsx b/public/app/plugins/panel/radialbar/RadialBarPanel.tsx index 86235a3bf68..03232406463 100644 --- a/public/app/plugins/panel/radialbar/RadialBarPanel.tsx +++ b/public/app/plugins/panel/radialbar/RadialBarPanel.tsx @@ -37,11 +37,10 @@ export function RadialBarPanel({ width={width} height={height} barWidthFactor={options.barWidthFactor} - gradient={options.effects?.gradient ? 'auto' : 'none'} - spotlight={options.effects?.spotlight} + gradient={options.effects?.gradient} glowBar={options.effects?.barGlow} glowCenter={options.effects?.centerGlow} - roundedBars={options.effects?.rounded} + roundedBars={options.barShape === 'rounded'} vizCount={valueProps.count} shape={options.shape} segmentCount={options.segmentCount} @@ -51,6 +50,7 @@ export function RadialBarPanel({ alignmentFactors={valueProps.alignmentFactors} valueManualFontSize={options.text?.valueSize} nameManualFontSize={options.text?.titleSize} + endpointMarker={options.endpointMarker !== 'none' ? options.endpointMarker : undefined} onClick={menuProps.openMenu} /> ); diff --git a/public/app/plugins/panel/radialbar/module.tsx b/public/app/plugins/panel/radialbar/module.tsx index 12aff4966f7..3dfcb3e3d5f 100644 --- a/public/app/plugins/panel/radialbar/module.tsx +++ b/public/app/plugins/panel/radialbar/module.tsx @@ -69,6 +69,36 @@ export const plugin = new PanelPlugin(RadialBarPanel) }, }); + builder.addRadio({ + path: 'barShape', + name: t('radialbar.config.bar-shape', 'Bar Style'), + category, + defaultValue: defaultOptions.barShape, + settings: { + options: [ + { value: 'flat', label: t('radialbar.config.bar-shape-flat', 'Flat') }, + { value: 'rounded', label: t('radialbar.config.bar-shape-rounded', 'Rounded') }, + ], + }, + showIf: (options) => options.segmentCount === 1, + }); + + builder.addRadio({ + path: 'endpointMarker', + name: t('radialbar.config.endpoint-marker', 'Endpoint marker'), + description: t('radialbar.config.endpoint-marker-description', 'Glow is only supported in dark mode'), + category, + defaultValue: defaultOptions.endpointMarker, + settings: { + options: [ + { value: 'point', label: t('radialbar.config.endpoint-marker-point', 'Point') }, + { value: 'glow', label: t('radialbar.config.endpoint-marker-glow', 'Glow') }, + { value: 'none', label: t('radialbar.config.endpoint-marker-none', 'None') }, + ], + }, + showIf: (options) => options.barShape === 'rounded' && options.segmentCount === 1, + }); + builder.addBooleanSwitch({ path: 'sparkline', name: t('radialbar.config.sparkline', 'Show sparkline'), diff --git a/public/app/plugins/panel/radialbar/panelcfg.cue b/public/app/plugins/panel/radialbar/panelcfg.cue index a37982dcfe1..c959512c0b8 100644 --- a/public/app/plugins/panel/radialbar/panelcfg.cue +++ b/public/app/plugins/panel/radialbar/panelcfg.cue @@ -27,10 +27,8 @@ composableKinds: PanelCfg: { schema: { GaugePanelEffects: { barGlow?: bool | *false - spotlight?: bool | *false - rounded?: bool | *false centerGlow?: bool | *false - gradient?: bool | *true + gradient?: bool | *true } @cuetsy(kind="interface") Options: { @@ -42,6 +40,8 @@ composableKinds: PanelCfg: { sparkline?: bool | *true shape: "circle" | *"gauge" barWidthFactor: number | *0.5 + barShape: "flat" | "rounded" | *"flat" + endpointMarker?: "point" | "glow" | "none" | *"point" effects: GaugePanelEffects | *{} } @cuetsy(kind="interface") } diff --git a/public/app/plugins/panel/radialbar/panelcfg.gen.ts b/public/app/plugins/panel/radialbar/panelcfg.gen.ts index 24915c62ef1..e050a044f77 100644 --- a/public/app/plugins/panel/radialbar/panelcfg.gen.ts +++ b/public/app/plugins/panel/radialbar/panelcfg.gen.ts @@ -14,21 +14,19 @@ export interface GaugePanelEffects { barGlow?: boolean; centerGlow?: boolean; gradient?: boolean; - rounded?: boolean; - spotlight?: boolean; } export const defaultGaugePanelEffects: Partial = { barGlow: false, centerGlow: false, gradient: true, - rounded: false, - spotlight: false, }; export interface Options extends common.SingleStatBaseOptions { + barShape: ('flat' | 'rounded'); barWidthFactor: number; effects: GaugePanelEffects; + endpointMarker?: ('point' | 'glow' | 'none'); segmentCount: number; segmentSpacing: number; shape: ('circle' | 'gauge'); @@ -38,8 +36,10 @@ export interface Options extends common.SingleStatBaseOptions { } export const defaultOptions: Partial = { + barShape: 'flat', barWidthFactor: 0.5, effects: {}, + endpointMarker: 'point', segmentCount: 1, segmentSpacing: 0.3, shape: 'gauge', diff --git a/public/app/plugins/panel/radialbar/suggestions.ts b/public/app/plugins/panel/radialbar/suggestions.ts index 00896ae8458..eab5334ef40 100644 --- a/public/app/plugins/panel/radialbar/suggestions.ts +++ b/public/app/plugins/panel/radialbar/suggestions.ts @@ -18,19 +18,6 @@ const withDefaults = ( } }, }, - // styles: [{ - // name: t('gauge.suggestions.style.circular', 'Glowing'), - // options: { - // effects: { - // rounded: true, - // barGlow: true, - // centerGlow: true, - // spotlight: true, - // }, - // }, - // }, { - // name: t('gauge.suggestions.style.simple', 'Simple'), - // }] } satisfies VisualizationSuggestion); const MAX_GAUGES = 10; diff --git a/public/app/plugins/panel/table/suggestions.ts b/public/app/plugins/panel/table/suggestions.ts index 8e0d6e44953..260e73b43eb 100644 --- a/public/app/plugins/panel/table/suggestions.ts +++ b/public/app/plugins/panel/table/suggestions.ts @@ -1,4 +1,5 @@ import { PanelDataSummary, VisualizationSuggestionScore, VisualizationSuggestionsSupplier } from '@grafana/data'; +import { config } from 'app/core/config'; import icnTablePanelSvg from 'app/plugins/panel/table/img/icn-table-panel.svg'; import { Options, FieldConfig } from './panelcfg.gen'; @@ -29,7 +30,7 @@ export const tableSuggestionsSupplier: VisualizationSuggestionsSupplier(TextPanel) defaultValue: defaultOptions.content, }); }) - .setMigrationHandler(textPanelMigrationHandler); + .setMigrationHandler(textPanelMigrationHandler) + .setSuggestionsSupplier((ds) => + ds.fieldCount === 0 && !config.featureToggles.newVizSuggestions + ? [{ cardOptions: { imgSrc: icnTextPanelSvg } }] + : [] + ); diff --git a/public/app/plugins/panel/text/plugin.json b/public/app/plugins/panel/text/plugin.json index ce437e97bf5..a1acce42c6e 100644 --- a/public/app/plugins/panel/text/plugin.json +++ b/public/app/plugins/panel/text/plugin.json @@ -2,7 +2,7 @@ "type": "panel", "name": "Text", "id": "text", - + "suggestions": true, "skipDataQuery": true, "info": { diff --git a/public/locales/cs-CZ/grafana.json b/public/locales/cs-CZ/grafana.json index 575bba19ca1..84cc597980b 100644 --- a/public/locales/cs-CZ/grafana.json +++ b/public/locales/cs-CZ/grafana.json @@ -2688,6 +2688,35 @@ "text-federated": "Federované", "text-provisioned": "Zajištěno" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Zdroj dat", @@ -3749,6 +3778,7 @@ "text": "Nebyly nalezeny žádné výsledky pro váš dotaz" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6222,7 +6252,7 @@ "title-someone-else-has-updated-this-dashboard": "Tuto nástěnku aktualizoval jiný uživatel", "would-still-dashboard": "Chcete přesto tuto nástěnku uložit?" }, - "save-and-overwrite": "Uložit a přepsat" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7211,6 +7241,9 @@ "time-range-label": "Zamknout časový rozsah" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Pro tip: {{proTip}}" }, @@ -7691,39 +7724,6 @@ }, "share-span": "Sdílet" }, - "span-filters": { - "aria-label-select-max-span-operator": "Vyberte operátor max. rozsahu", - "aria-label-select-min-span-operator": "Vyberte operátor min. rozsahu", - "aria-label-select-service-name": "Vyberte název služby", - "aria-label-select-service-name-operator": "Vyberte operátor názvu služby", - "aria-label-select-span-name": "Vyberte název rozsahu", - "aria-label-select-span-name-operator": "Vyberte operátor názvu rozsahu", - "ariaLabel-select-max-span-duration": "Vyberte maximální dobu trvání", - "ariaLabel-select-min-span-duration": "Vyberte minimální dobu trvání rozsahu", - "label-collapse": "Filtry rozsahu", - "label-duration": "Doba trvání", - "label-service-name": "Název služby", - "label-span-name": "Název rozsahu", - "label-tags": "Tagy", - "placeholder-all-service-names": "Všechny názvy služby", - "placeholder-all-span-names": "Všechny názvy rozsahu", - "tooltip-collapse": "Filtrujte svá rozpětí níže. Filtry můžete používat tak dlouho, dokud nezúžíte výsledná rozpětí na několik vybraných, které vás nejvíce zajímají.", - "tooltip-duration": "Filtrovat podle doby trvání. Akceptované jednotky jsou {{units}}", - "tooltip-tags": "Filtrujte podle tagů, tagů procesů nebo polí protokolu ve vybraném rozpětí." - }, - "span-filters-tags": { - "aria-label-add-tag": "Přidat tag", - "aria-label-input-tag-value": "Vstupní hodnota tagu", - "aria-label-remove-tag": "Odebrat tag", - "aria-label-select-tag-key": "Vyberte klíč tagu", - "aria-label-select-tag-operator": "Vyberte operátor tagu", - "aria-label-select-tag-value": "Vyberte hodnotu tagu", - "placeholder-select-tag": "Vyberte tag", - "placeholder-select-value": "Vyberte hodnotu", - "placeholder-tag-value": "Hodnota tagu", - "tooltip-add-tag": "Přidat tag", - "tooltip-remove-tag": "Odebrat tag" - }, "span-flame-graph": { "flame-graph": "Graf plamene" }, @@ -7922,23 +7922,18 @@ "label-upsample": "Zvýšit vzorkovací frekvenci", "tooltip-s-m-h": "10s, 1m, 30m, 1h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Spustit dotaz", - "modal-title": "Editor SQL", "tooltip-experimental": "Integrace LLM pro výrazy jazyka SQL je experimentální. Jakékoli problémy nahlaste týmu Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Vstup" @@ -8013,11 +8008,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9463,6 +9454,7 @@ "name-unit": "Jednotka", "name-value-name": "Název hodnoty", "name-y-axis-scale": "Měřítko osy Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Auto", "placeholder-axis-width": "Auto", "placeholder-decimals": "Auto", @@ -9492,6 +9484,18 @@ "label-all": "Vše", "label-hidden": "Skryté", "label-single": "Jednorázový" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11295,9 +11299,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -12074,7 +12083,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Zobrazit podrobnosti", "loading-finished-job": "Načítání dokončené úlohy…", @@ -12180,6 +12192,9 @@ "webhook-last-event": "Poslední událost:", "webhook-url": "Zobrazit webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Zpět na úložiště", "cleaning-up-resources": "Čištění zdrojů úložiště", @@ -12284,6 +12299,9 @@ "tooltip-unhealthy-repository": "Nelze stáhnout nezdravé úložiště" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12303,10 +12321,15 @@ }, "warning-title-default": "Varování", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Doba trvání tohoto procesu závisí na počtu zapojených zdrojů.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12325,6 +12348,7 @@ "step-finish": "Vybrat další nastavení", "step-synchronize": "Synchronizovat s externím úložištěm", "sync-description": "Synchronizujte zdroje s externím úložištěm. Po tomto jednorázovém kroku budou všechny budoucí aktualizace automaticky uloženy do úložiště a zajištěny zpět do instance.", + "sync-option-migrate-resources": "", "title-bootstrap": "Vyberte, co chcete synchronizovat", "title-connect": "Připojit k externímu úložišti", "title-finish": "Vybrat další nastavení", @@ -12564,16 +12588,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/de-DE/grafana.json b/public/locales/de-DE/grafana.json index 9df0dd8a2da..ef5f649123d 100644 --- a/public/locales/de-DE/grafana.json +++ b/public/locales/de-DE/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Verbunden", "text-provisioned": "Bereitgestellt" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Datenquelle", @@ -3717,6 +3746,7 @@ "text": "Keine Ergebnisse für deine Abfrage gefunden" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Eine andere Person hat dieses Dashboard aktualisiert", "would-still-dashboard": "Möchten Sie dieses Dashboard trotzdem speichern?" }, - "save-and-overwrite": "'Speichern und überschreiben'" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Zeitbereich sperren" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Profitipp: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Teilen" }, - "span-filters": { - "aria-label-select-max-span-operator": "Höchstspannen-Operator auswählen", - "aria-label-select-min-span-operator": "Mindestspannen-Operator auswählen", - "aria-label-select-service-name": "Dienstname auswählen", - "aria-label-select-service-name-operator": "Dienstnamen-Operator auswählen", - "aria-label-select-span-name": "Spannen-Name auswählen", - "aria-label-select-span-name-operator": "Spannen-Namen-Operator auswählen", - "ariaLabel-select-max-span-duration": "Dauer der max. Spanne auswählen", - "ariaLabel-select-min-span-duration": "Dauer der min. Spanne auswählen", - "label-collapse": "Spannenfilter", - "label-duration": "Dauer", - "label-service-name": "Dienstname", - "label-span-name": "Spannen-Name", - "label-tags": "Tags", - "placeholder-all-service-names": "Alle Dienstnamen", - "placeholder-all-span-names": "Alle Spannen-Namen", - "tooltip-collapse": "Filtern Sie unten Ihre Spannen. Sie können weiterhin Filter anwenden, bis Sie Ihre resultierenden Spannen auf die wenigen eingegrenzt haben, die für Sie am meisten von Interesse sind.", - "tooltip-duration": "Nach Dauer filtern. Zulässige Einheiten sind {{units}}", - "tooltip-tags": "Filtern Sie in Ihren Spannen nach Tags, Prozess-Tags oder Log-Feldern." - }, - "span-filters-tags": { - "aria-label-add-tag": "Tag hinzufügen", - "aria-label-input-tag-value": "Tag-Wert eingeben", - "aria-label-remove-tag": "Tag entfernen", - "aria-label-select-tag-key": "Tag-Key auswählen", - "aria-label-select-tag-operator": "Tag-Operator auswählen", - "aria-label-select-tag-value": "Tag-Wert auswählen", - "placeholder-select-tag": "Tag auswählen", - "placeholder-select-value": "Wert auswählen", - "placeholder-tag-value": "Tag-Wert", - "tooltip-add-tag": "Tag hinzufügen", - "tooltip-remove-tag": "Tag entfernen" - }, "span-flame-graph": { "flame-graph": "Flammendiagramm" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Upsample", "tooltip-s-m-h": "10 s, 1 min., 30 min., 1 h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Abfrage ausführen", - "modal-title": "SQL Editor", "tooltip-experimental": "Die Integration des SQL Expressions LLM ist experimentell. Bitte melden Sie Probleme dem Grafana-Team." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Eingabe" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Einheit", "name-value-name": "Wertname", "name-y-axis-scale": "Y-Achsenskala", + "name-y-bucket-scale": "", "placeholder-axis-label": "Auto", "placeholder-axis-width": "Auto", "placeholder-decimals": "Auto", @@ -9422,6 +9414,18 @@ "label-all": "Alles", "label-hidden": "Ausgeblendet", "label-single": "Einzeln" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Details anzeigen", "loading-finished-job": "Fertiger Auftrag wird geladen …", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Letztes Ereignis:", "webhook-url": "Webhook anzeigen" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Zurück zu den Repositorys", "cleaning-up-resources": "Bereinigen von Repository-Ressourcen", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Ein fehlerhaftes Repository kann nicht abgerufen werden" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Warnung", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Die Dauer dieses Prozesses hängt von der Anzahl der betroffenen Ressourcen ab.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Zusätzliche Einstellungen auswählen", "step-synchronize": "Mit externem Speicher synchronisieren", "sync-description": "Synchronisieren Sie Ressourcen mit externem Speicher. Nach diesem einmaligen Schritt werden alle zukünftigen Updates automatisch im Repository gespeichert und wieder in der Instanz bereitgestellt.", + "sync-option-migrate-resources": "", "title-bootstrap": "Wählen Sie aus, was synchronisiert wird", "title-connect": "Mit externem Speicher verbinden", "title-finish": "Zusätzliche Einstellungen auswählen", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/en-US/grafana.json b/public/locales/en-US/grafana.json index febd4c0442e..807d6fbfa4b 100644 --- a/public/locales/en-US/grafana.json +++ b/public/locales/en-US/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federated", "text-provisioned": "Provisioned" }, + "saved-searches": { + "actions-aria-label": "Actions", + "apply-aria-label": "Apply search \"{{name}}\"", + "apply-tooltip": "Apply this search", + "button-label": "Saved searches", + "cancel": "Cancel", + "default-indicator": "Default search", + "delete": "Delete", + "delete-button": "Delete", + "dropdown-aria-label": "Saved searches", + "empty-state": "No saved searches yet", + "error-load-description": "Your saved searches could not be loaded. Please try refreshing the page.", + "error-load-title": "Failed to load saved searches", + "error-name-duplicate": "A saved search with this name already exists", + "error-name-required": "Name is required", + "error-rename-description": "Your changes could not be saved. Please try again.", + "error-rename-title": "Failed to rename", + "error-save-description": "Your changes could not be saved. Please try again.", + "error-save-title": "Failed to save", + "list-aria-label": "Saved searches list", + "name-placeholder": "Enter a name...", + "remove-default": "Remove default", + "rename": "Rename", + "rename-button": "Rename", + "save-button": "Save", + "save-current-search": "Save current search", + "save-disabled-tooltip": "Enter a search query first", + "set-default": "Set as default" + }, "search": { "property": { "data-source": "Data source", @@ -6181,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Someone else has updated this dashboard", "would-still-dashboard": "Would you still like to save this dashboard?" }, - "save-and-overwrite": "'Save and overwrite'" + "save-and-overwrite": "Save and overwrite" }, "library-viz-panel-info": { "last-edited": "{{timeAgo}} by ", @@ -7843,23 +7872,18 @@ "label-upsample": "Upsample", "tooltip-s-m-h": "10s, 1m, 30m, 1h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "Close schema inspector" - }, "sql-expr": { "button-run-query": "Run query", - "modal-title": "SQL Editor", "tooltip-experimental": "SQL Expressions LLM integration is experimental. Please report any issues to the Grafana team." }, "sql-schema": { - "close-schema-inspector": "Close schema inspector", "error-title": "Error", - "inspect-button": "Inspect schema", "loading": "Loading schema information...", "no-data-title": "No schema information available", "no-fields-desc": "This query returned no schema information.", "no-fields-title": "No schema information", - "query-error-title": "Query error" + "query-error-title": "Query error", + "schema-inspector": "Schema inspector" }, "threshold": { "label-input": "Input" @@ -7934,11 +7958,7 @@ "suggestions": { "arc": "Gauge", "circular": "Circular gauge", - "no-thresholds": "Gauge - no thresholds", - "style": { - "circular": "Glowing", - "simple": "Simple" - } + "no-thresholds": "Gauge - no thresholds" }, "threshold": "Threshold {{value}}" }, @@ -11187,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "Apply {{suggestionName}} visualization", + "error-loading-some-suggestions": { + "message": "Some suggestions could not be loaded" + }, "error-loading-suggestions": { "message": "An error occurred when loading visualization suggestions.", - "title": "Error" + "plugin-failed": "Failed to load panel plugin: {{ pluginId }}.", + "title": "Error", + "try-again-button": "Try again" }, "unknown-viz-type": "Unknown visualization type", "use-this-suggestion": "Use this suggestion" @@ -11406,6 +11431,12 @@ "latestReleaseDate": "Latest release date:", "latestVersion": "Latest Version", "license": "License", + "moreDetails": "Do you find Plugin Insights usefull? Please share your feedback <2>here.", + "pluginInsights": { + "header": "Plugin insights" + }, + "pluginInsightsSuccessTooltip": "All relevant signals are present and verified", + "pluginInsightsWarningTooltip": "One or more signals are missing or need attention", "raiseAnIssue": "Raise an issue", "reportAbuse": "Report a concern", "reportAbuseTooltip": "Report issues related to malicious or harmful plugins directly to Grafana Labs.", @@ -11950,7 +11981,10 @@ "resource-not-found": "Resource not found. Please check the URL or repository.", "unsupported-repository-type": "Unsupported repository type: {{repositoryType}}" }, - "inline-secure-values-warning": "You need to save your access tokens again due to a system update", + "instance-sync-deprecation": { + "message": "Instance sync is currently not fully supported and breaks library panels and alerts. To use library panels and alerts, disconnect your repository and reconnect it using folder sync instead.", + "title": "Instance sync is not fully supported" + }, "job-status": { "label-view-details": "View details", "loading-finished-job": "Loading finished job...", @@ -12056,6 +12090,9 @@ "webhook-last-event": "Last Event:", "webhook-url": "View Webhook" }, + "repository-status": { + "error": "Failed to load repository" + }, "repository-status-page": { "back-to-repositories": "Back to repositories", "cleaning-up-resources": "Cleaning up repository resources", @@ -12447,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "Bar Style", + "bar-shape-flat": "Flat", + "bar-shape-rounded": "Rounded", "bar-width": "Bar width", "effects": { "bar-glow": "Bar glow", "center-glow": "Center glow", "gradient": "Gradient", - "label": "Effects", - "rounded-bars": "Rounded bars", - "spotlight": "Spotlight", - "spotlight-tooltip": "Only visible in dark themes" + "label": "Effects" }, + "endpoint-marker": "Endpoint marker", + "endpoint-marker-description": "Glow is only supported in dark mode", + "endpoint-marker-glow": "Glow", + "endpoint-marker-none": "None", + "endpoint-marker-point": "Point", "segment-count": "Segments", "segment-spacing": "Segment spacing", "shape": "Style", diff --git a/public/locales/es-ES/grafana.json b/public/locales/es-ES/grafana.json index 1c8c641cfad..443dbefbc39 100644 --- a/public/locales/es-ES/grafana.json +++ b/public/locales/es-ES/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federado", "text-provisioned": "Provisionado" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Fuente de datos", @@ -3717,6 +3746,7 @@ "text": "No se han encontrado resultados para tu consulta" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Otra persona ha actualizado este dashboard", "would-still-dashboard": "¿Seguro que quieres guardar este dashboard?" }, - "save-and-overwrite": "«Guardar y sobrescribir»" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Bloquear el intervalo de tiempo" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Consejo profesional: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Compartir" }, - "span-filters": { - "aria-label-select-max-span-operator": "Seleccionar operador de intervalo máximo", - "aria-label-select-min-span-operator": "Seleccionar operador de intervalo mínimo", - "aria-label-select-service-name": "Seleccionar nombre de servicio", - "aria-label-select-service-name-operator": "Seleccionar operador de nombre de servicio", - "aria-label-select-span-name": "Seleccionar nombre de intervalo", - "aria-label-select-span-name-operator": "Seleccionar operador de nombre de intervalo", - "ariaLabel-select-max-span-duration": "Seleccionar duración máxima del intervalo", - "ariaLabel-select-min-span-duration": "Seleccionar duración mínima del intervalo", - "label-collapse": "Filtros de intervalo", - "label-duration": "Duración", - "label-service-name": "Nombre de servicio", - "label-span-name": "Nombre del intervalo", - "label-tags": "Etiquetas", - "placeholder-all-service-names": "Todos los nombres de servicios", - "placeholder-all-span-names": "Todos los nombres de intervalo", - "tooltip-collapse": "Filtre sus intervalos a continuación. Puede seguir aplicando filtros hasta que haya reducido los intervalos resultantes a los que más le interesen.", - "tooltip-duration": "Filtra por duración. Las unidades aceptadas son {{units}}", - "tooltip-tags": "Filtra por etiquetas, etiquetas de proceso o campos de logs en tus intervalos." - }, - "span-filters-tags": { - "aria-label-add-tag": "Añadir etiqueta", - "aria-label-input-tag-value": "Introducir valor de la etiqueta", - "aria-label-remove-tag": "Quitar etiqueta", - "aria-label-select-tag-key": "Seleccionar clave de etiqueta", - "aria-label-select-tag-operator": "Seleccionar operador de etiqueta", - "aria-label-select-tag-value": "Seleccionar valor de etiqueta", - "placeholder-select-tag": "Seleccionar etiqueta", - "placeholder-select-value": "Seleccionar valor", - "placeholder-tag-value": "Valor de etiqueta", - "tooltip-add-tag": "Añadir etiqueta", - "tooltip-remove-tag": "Quitar etiqueta" - }, "span-flame-graph": { "flame-graph": "Gráfico de llama" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Aumentar tamaño", "tooltip-s-m-h": "10 s, 1 m, 30 m, 1 h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Ejecutar consulta", - "modal-title": "Editor de SQL", "tooltip-experimental": "La integración de LLM de expresiones SQL es experimental. Avisa de cualquier problema al equipo de Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Entrada" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Unidad", "name-value-name": "Nombre del valor", "name-y-axis-scale": "Escala del eje Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Auto", "placeholder-axis-width": "Auto", "placeholder-decimals": "Auto", @@ -9422,6 +9414,18 @@ "label-all": "Todo", "label-hidden": "Oculto", "label-single": "Único" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Ver detalles", "loading-finished-job": "Cargando trabajo finalizado...", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Último evento:", "webhook-url": "Ver webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Volver a los repositorios", "cleaning-up-resources": "Limpiando los recursos del repositorio", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "No se puede extraer un repositorio que no está en buen estado" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Advertencia", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "La duración de este proceso depende del número de recursos involucrados.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Elegir ajustes adicionales", "step-synchronize": "Sincronizar con un almacenamiento externo", "sync-description": "Sincroniza los recursos con un almacenamiento externo. Después de este paso único, todas las actualizaciones futuras se guardarán automáticamente en el repositorio y se aprovisionarán de nuevo en la instancia.", + "sync-option-migrate-resources": "", "title-bootstrap": "Elegir qué sincronizar", "title-connect": "Conectar a un almacenamiento externo", "title-finish": "Elegir ajustes adicionales", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/fr-FR/grafana.json b/public/locales/fr-FR/grafana.json index d2faa93f8e5..1d98e007593 100644 --- a/public/locales/fr-FR/grafana.json +++ b/public/locales/fr-FR/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Fédéré", "text-provisioned": "Mis en service" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Source de données", @@ -3717,6 +3746,7 @@ "text": "Aucun résultat n'a été trouvé pour votre requête" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Quelqu’un d’autre a mis à jour ce tableau de bord", "would-still-dashboard": "Voulez-vous toujours enregistrer ce tableau de bord ?" }, - "save-and-overwrite": "« Enregistrer et écraser »" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Verrouiller la période temporelle" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Conseil de pro : {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Partager" }, - "span-filters": { - "aria-label-select-max-span-operator": "Sélectionner l’opérateur de la durée maximale", - "aria-label-select-min-span-operator": "Sélectionner l’opérateur de la durée minimale", - "aria-label-select-service-name": "Sélectionner le nom de service", - "aria-label-select-service-name-operator": "Sélectionner l’opérateur de nom de service", - "aria-label-select-span-name": "Sélectionner le nom de la durée", - "aria-label-select-span-name-operator": "Sélectionner l’opérateur de nom de la durée", - "ariaLabel-select-max-span-duration": "Sélectionner la durée maximale de segment", - "ariaLabel-select-min-span-duration": "Sélectionner la durée minimale de segment", - "label-collapse": "Filtres de durée", - "label-duration": "Durée", - "label-service-name": "Nom du service", - "label-span-name": "Nom de la durée", - "label-tags": "Étiquettes", - "placeholder-all-service-names": "Tous les noms de service", - "placeholder-all-span-names": "Tous les noms de durée", - "tooltip-collapse": "Filtrez vos plages ci-dessous. Vous pouvez continuer à appliquer des filtres jusqu’à ce que vous ayez réduit votre plage de résultats à ceux qui vous intéressent le plus.", - "tooltip-duration": "Filtrer par durée. Les unités acceptées sont {{units}}", - "tooltip-tags": "Filtrez par balises, balises de processus ou champs de journal dans vos durées." - }, - "span-filters-tags": { - "aria-label-add-tag": "Ajouter une balise", - "aria-label-input-tag-value": "Saisir la valeur de la balise", - "aria-label-remove-tag": "Supprimer la balise", - "aria-label-select-tag-key": "Sélectionner la clé de la balise", - "aria-label-select-tag-operator": "Sélectionner l’opérateur de la balise", - "aria-label-select-tag-value": "Sélectionner la valeur de la balise", - "placeholder-select-tag": "Choisir une balise", - "placeholder-select-value": "Sélectionner une valeur", - "placeholder-tag-value": "Valeur de la balise", - "tooltip-add-tag": "Ajouter une balise", - "tooltip-remove-tag": "Supprimer la balise" - }, "span-flame-graph": { "flame-graph": "Graphique de flamme" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Sur-échantillonner", "tooltip-s-m-h": "10 s, 1 m, 30 m, 1 h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Exécuter la requête", - "modal-title": "Éditeur SQL", "tooltip-experimental": "L’intégration des expressions SQL avec les LLM est expérimentale. Merci de signaler tout problème à l’équipe Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Entrée" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Unité", "name-value-name": "Nom de la valeur", "name-y-axis-scale": "Échelle de l’axe Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Auto", "placeholder-axis-width": "Auto", "placeholder-decimals": "Auto", @@ -9422,6 +9414,18 @@ "label-all": "Tous", "label-hidden": "Masqué", "label-single": "Unique" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Afficher les détails", "loading-finished-job": "Chargement de mission terminée…", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Dernier événement :", "webhook-url": "Voir le webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Retour aux référentiels", "cleaning-up-resources": "Nettoyage des ressources du référentiel", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Impossible de fusionner un référentiel en mauvais état" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Avertissement", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "La durée de ce processus dépend du nombre de ressources impliquées.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Choisir des paramètres supplémentaires", "step-synchronize": "Synchroniser avec un stockage externe", "sync-description": "Synchronisez les ressources avec un stockage externe. Après cette étape unique, toutes les futures mises à jour seront automatiquement enregistrées dans le référentiel et mises en service dans l’instance.", + "sync-option-migrate-resources": "", "title-bootstrap": "Choisir ce qui doit être synchronisé", "title-connect": "Se connecter à un stockage externe", "title-finish": "Choisir des paramètres supplémentaires", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/hu-HU/grafana.json b/public/locales/hu-HU/grafana.json index 0c8c164742b..bfe9d3e9542 100644 --- a/public/locales/hu-HU/grafana.json +++ b/public/locales/hu-HU/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Összevont", "text-provisioned": "Kiépítve" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Adatforrás", @@ -3717,6 +3746,7 @@ "text": "Nincs találat a lekérdezésre" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Valaki más frissítette ezt az irányítópultot", "would-still-dashboard": "Biztosan menti ezt az irányítópultot?" }, - "save-and-overwrite": "„Mentés és felülírás”" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Időtartomány zárolása" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "ProTip: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Megosztás" }, - "span-filters": { - "aria-label-select-max-span-operator": "Max. terjedelem operátor kijelölése", - "aria-label-select-min-span-operator": "Válasszon operátort a min. terjedelemhez", - "aria-label-select-service-name": "Válasszon szolgáltatásnevet", - "aria-label-select-service-name-operator": "Válasszon operátort a szolgáltatásnévhez", - "aria-label-select-span-name": "Válasszon terjedelemnevet", - "aria-label-select-span-name-operator": "Terjedelemnév operátor kijelölése", - "ariaLabel-select-max-span-duration": "Maximális időtartam kiválasztása", - "ariaLabel-select-min-span-duration": "Minimális időtartam kiválasztása", - "label-collapse": "Terjedelemszűrők", - "label-duration": "Időtartam", - "label-service-name": "Szolgáltatásnév", - "label-span-name": "Terjedelemnév", - "label-tags": "Címkék", - "placeholder-all-service-names": "Összes szolgáltatásnév", - "placeholder-all-span-names": "Összes terjedelemnév", - "tooltip-collapse": "Alább szűrheti a terjedelmeket. Folytathatja a szűrők alkalmazását, amíg a kapott terjedelmeket a leginkább keresett néhány terjedelemre nem szűkíti.", - "tooltip-duration": "Szűrés időtartam szerint. Elfogadott mértékegységek: {{units}}", - "tooltip-tags": "Szűrés címkék, folyamatcímkék vagy naplómezők alapján a terjedelmeiben." - }, - "span-filters-tags": { - "aria-label-add-tag": "Címke hozzáadása", - "aria-label-input-tag-value": "Bemeneti címke értéke", - "aria-label-remove-tag": "Címke eltávolítása", - "aria-label-select-tag-key": "Címkekulcs kijelölése", - "aria-label-select-tag-operator": "Címkeoperátor kijelölése", - "aria-label-select-tag-value": "Címkeérték kijelölése", - "placeholder-select-tag": "Címke kijelölése", - "placeholder-select-value": "Érték kijelölése", - "placeholder-tag-value": "Címke értéke", - "tooltip-add-tag": "Címke hozzáadása", - "tooltip-remove-tag": "Címke eltávolítása" - }, "span-flame-graph": { "flame-graph": "Lángdiagram" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Mintasűrűség növelése", "tooltip-s-m-h": "10 mp., 1 p., 30 p., 1 ó." }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Lekérdezés futtatása", - "modal-title": "SQL-szerkesztő", "tooltip-experimental": "Az SQL-kifejezések LLM-integrációja kísérleti jellegű. Kérjük, jelentse az esetleges problémákat a Grafana csapatának." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Bemenet" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Egység", "name-value-name": "Érték neve", "name-y-axis-scale": "Y tengely skálája", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automatikus", "placeholder-axis-width": "Automatikus", "placeholder-decimals": "Automatikus", @@ -9422,6 +9414,18 @@ "label-all": "Összes", "label-hidden": "Rejtett", "label-single": "Különálló" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Részletek megtekintése", "loading-finished-job": "Befejezett feladat betöltése…", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Legutóbbi esemény:", "webhook-url": "Webkapocs megtekintése" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Vissza az adattárakhoz", "cleaning-up-resources": "Adattári erőforrások tisztítása", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Nem lehet beolvasni egy nem megfelelő állapotú adattárat" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Figyelmeztetés", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "A folyamat időtartama az érintett erőforrások számától függ.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Válassza ki a további beállításokat", "step-synchronize": "Szinkronizálás külső tárolóval", "sync-description": "Erőforrások szinkronizálása külső tárolóval. Ezután az egyszeri lépés után az összes jövőbeli frissítés automatikusan mentve lesz az adattárba, és vissza lesz építve a példányba.", + "sync-option-migrate-resources": "", "title-bootstrap": "Válassza ki, mit szeretne szinkronizálni", "title-connect": "Csatlakozás külső tárolóhoz", "title-finish": "Válassza ki a további beállításokat", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/id-ID/grafana.json b/public/locales/id-ID/grafana.json index 66ad5574fb6..86b18767abb 100644 --- a/public/locales/id-ID/grafana.json +++ b/public/locales/id-ID/grafana.json @@ -2655,6 +2655,35 @@ "text-federated": "Federasi", "text-provisioned": "Disediakan" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Sumber data", @@ -3701,6 +3730,7 @@ "text": "Hasil untuk kueri Anda tidak ditemukan" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6159,7 +6189,7 @@ "title-someone-else-has-updated-this-dashboard": "Orang lain telah memperbarui dasbor ini", "would-still-dashboard": "Ingin tetap menyimpan dasbor ini?" }, - "save-and-overwrite": "'Simpan dan timpa'" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7142,6 +7172,9 @@ "time-range-label": "Kunci rentang waktu" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Kiat Pro: {{proTip}}" }, @@ -7616,39 +7649,6 @@ }, "share-span": "Bagikan" }, - "span-filters": { - "aria-label-select-max-span-operator": "Pilih operator rentang maksimum", - "aria-label-select-min-span-operator": "Pilih operator rentang min", - "aria-label-select-service-name": "Pilih nama layanan", - "aria-label-select-service-name-operator": "Pilih operator nama layanan", - "aria-label-select-span-name": "Pilih nama rentang", - "aria-label-select-span-name-operator": "Pilih operator nama rentang", - "ariaLabel-select-max-span-duration": "Pilih durasi rentang maksimum", - "ariaLabel-select-min-span-duration": "Pilih durasi rentang minimum", - "label-collapse": "Filter Rentang", - "label-duration": "Durasi", - "label-service-name": "Nama layanan", - "label-span-name": "Nama rentang", - "label-tags": "Tag", - "placeholder-all-service-names": "Semua nama layanan", - "placeholder-all-span-names": "Semua nama rentang", - "tooltip-collapse": "Filter rentang Anda di bawah ini. Anda dapat terus menerapkan filter hingga Anda mempersempit rentang hasil Anda menjadi beberapa pilihan yang paling Anda minati.", - "tooltip-duration": "Filter menurut durasi. Unit yang diterima adalah {{units}}", - "tooltip-tags": "Filter berdasarkan tag, tag proses, atau bidang log di rentang Anda." - }, - "span-filters-tags": { - "aria-label-add-tag": "Tambah tag", - "aria-label-input-tag-value": "Masukkan nilai tag", - "aria-label-remove-tag": "Hapus tag", - "aria-label-select-tag-key": "Pilih kunci tag", - "aria-label-select-tag-operator": "Pilih operator tag", - "aria-label-select-tag-value": "Pilih nilai tag", - "placeholder-select-tag": "Pilih tag", - "placeholder-select-value": "Pilih nilai", - "placeholder-tag-value": "Nilai tag", - "tooltip-add-tag": "Tambah tag", - "tooltip-remove-tag": "Hapus tag" - }, "span-flame-graph": { "flame-graph": "Grafik api" }, @@ -7847,23 +7847,18 @@ "label-upsample": "Tingkatkan sample", "tooltip-s-m-h": "10 dtk, 1 mnt, 30 mnt, 1 jm" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Jalankan kueri", - "modal-title": "Editor SQL", "tooltip-experimental": "Integrasi LLM Ekspresi SQL bersifat eksperimental. Harap laporkan masalah apa pun kepada tim Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Input" @@ -7938,11 +7933,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9358,6 +9349,7 @@ "name-unit": "Unit", "name-value-name": "Nama nilai", "name-y-axis-scale": "Skala sumbu Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Otomatis", "placeholder-axis-width": "Otomatis", "placeholder-decimals": "Otomatis", @@ -9387,6 +9379,18 @@ "label-all": "Semua", "label-hidden": "Tersembunyi", "label-single": "Tunggal" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11157,9 +11161,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11921,7 +11930,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Lihat detail", "loading-finished-job": "Memuat pekerjaan yang sudah selesai...", @@ -12027,6 +12039,9 @@ "webhook-last-event": "Peristiwa Terakhir:", "webhook-url": "Lihat Webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Kembali ke repositori", "cleaning-up-resources": "Membersihkan sumber daya repositori", @@ -12131,6 +12146,9 @@ "tooltip-unhealthy-repository": "Tidak dapat menerapkan pull pada repositori yang tidak sehat" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12150,10 +12168,15 @@ }, "warning-title-default": "Peringatan", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Durasi proses ini bergantung pada jumlah sumber daya yang terlibat.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12172,6 +12195,7 @@ "step-finish": "Pilih pengaturan tambahan", "step-synchronize": "Sinkronkan dengan penyimpanan eksternal", "sync-description": "Sinkronkan sumber daya dengan penyimpanan eksternal. Setelah langkah satu kali ini, semua pembaruan mendatang akan disimpan secara otomatis ke repositori dan disediakan kembali ke instans.", + "sync-option-migrate-resources": "", "title-bootstrap": "Pilih item yang akan disinkronkan", "title-connect": "Hubungkan ke penyimpanan eksternal", "title-finish": "Pilih pengaturan tambahan", @@ -12408,16 +12432,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/it-IT/grafana.json b/public/locales/it-IT/grafana.json index 76898afd674..976d81b2f37 100644 --- a/public/locales/it-IT/grafana.json +++ b/public/locales/it-IT/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federato", "text-provisioned": "Fornito" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Sorgente dati", @@ -3717,6 +3746,7 @@ "text": "Nessun risultato trovato per la ricerca" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Qualcun altro ha aggiornato questa dashboard", "would-still-dashboard": "Desideri comunque salvare questa dashboard?" }, - "save-and-overwrite": "\"Salva e sovrascrivi\"" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Blocca intervallo di tempo" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Suggerimento pro: {{proTip}} " }, @@ -7641,39 +7674,6 @@ }, "share-span": "Condividi" }, - "span-filters": { - "aria-label-select-max-span-operator": "Seleziona l'operatore di intervallo massimo", - "aria-label-select-min-span-operator": "Seleziona operatore di intervallo minimo", - "aria-label-select-service-name": "Seleziona nome servizio", - "aria-label-select-service-name-operator": "Seleziona operatore nome servizio", - "aria-label-select-span-name": "Seleziona nome intervallo", - "aria-label-select-span-name-operator": "Seleziona l'operatore del nome dell'intervallo", - "ariaLabel-select-max-span-duration": "Seleziona la durata dell'intervallo massimo", - "ariaLabel-select-min-span-duration": "Seleziona la durata dell'intervallo minimo", - "label-collapse": "Filtri intervallo", - "label-duration": "Durata", - "label-service-name": "Nome del servizio", - "label-span-name": "Nome intervallo", - "label-tags": "Tag", - "placeholder-all-service-names": "Tutti i nomi dei servizi", - "placeholder-all-span-names": "Tutti i nomi degli intervalli", - "tooltip-collapse": "Filtra i tuoi intervalli qui sotto. Puoi continuare ad applicare i filtri fino a quando non avrai ristretto gli intervalli risultanti ai pochi selezionati a cui sei più interessato.", - "tooltip-duration": "Filtra per durata. Le unità accettate sono {{units}}", - "tooltip-tags": "Filtra per tag, tag di processo o campi di registro nei tuoi intervalli." - }, - "span-filters-tags": { - "aria-label-add-tag": "Aggiungi tag", - "aria-label-input-tag-value": "Valore del tag di inserimento", - "aria-label-remove-tag": "Rimuovi tag", - "aria-label-select-tag-key": "Seleziona chiave tag", - "aria-label-select-tag-operator": "Seleziona operatore tag", - "aria-label-select-tag-value": "Seleziona valore tag", - "placeholder-select-tag": "Seleziona tag", - "placeholder-select-value": "Seleziona valore", - "placeholder-tag-value": "Valore del tag", - "tooltip-add-tag": "Aggiungi tag", - "tooltip-remove-tag": "Rimuovi tag" - }, "span-flame-graph": { "flame-graph": "Grafico a fiamma" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Aumenta campionamento", "tooltip-s-m-h": "10 s, 1 m, 30 m, 1 h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Esegui query", - "modal-title": "Editor SQL", "tooltip-experimental": "L'integrazione LLM delle Espressioni SQL è sperimentale. Segnala eventuali problemi al team Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Inserisci" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Unità", "name-value-name": "Nome del valore", "name-y-axis-scale": "Scala asse Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automatico", "placeholder-axis-width": "Automatico", "placeholder-decimals": "Automatico", @@ -9422,6 +9414,18 @@ "label-all": "Tutti", "label-hidden": "Nascosto", "label-single": "Singolo" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Visualizza dettagli", "loading-finished-job": "Caricamento attività terminata in corso...", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Ultimo evento:", "webhook-url": "Visualizza webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Torna ai repository", "cleaning-up-resources": "Pulizia delle risorse del repository", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Impossibile eseguire il pull di un repository non integro" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Attenzione", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "La durata di questo processo dipende dal numero di risorse coinvolte.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Scegli impostazioni aggiuntive", "step-synchronize": "Sincronizza con la memoria esterna", "sync-description": "Sincronizza le risorse con la memoria esterna. Dopo questo passaggio una tantum, tutti gli aggiornamenti futuri verranno salvati automaticamente nel repository e ripristinati nell'istanza.", + "sync-option-migrate-resources": "", "title-bootstrap": "Scegli cosa sincronizzare", "title-connect": "Connetti a una memoria esterna", "title-finish": "Scegli impostazioni aggiuntive", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/ja-JP/grafana.json b/public/locales/ja-JP/grafana.json index cebb4cd6bad..9bfbc78a21e 100644 --- a/public/locales/ja-JP/grafana.json +++ b/public/locales/ja-JP/grafana.json @@ -2655,6 +2655,35 @@ "text-federated": "フェデレーション", "text-provisioned": "プロビジョニング済み" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "データソース", @@ -3701,6 +3730,7 @@ "text": "クエリに一致する結果が見つかりませんでした。" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6159,7 +6189,7 @@ "title-someone-else-has-updated-this-dashboard": "他のユーザーがこのダッシュボードを更新しました", "would-still-dashboard": "このダッシュボードの保存を続行しますか?" }, - "save-and-overwrite": "「保存して上書き」" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7142,6 +7172,9 @@ "time-range-label": "時間範囲をロック" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "プロのヒント:{{proTip}} " }, @@ -7616,39 +7649,6 @@ }, "share-span": "共有" }, - "span-filters": { - "aria-label-select-max-span-operator": "最大スパン演算子を選択", - "aria-label-select-min-span-operator": "最小スパン演算子を選択", - "aria-label-select-service-name": "サービス名を選択", - "aria-label-select-service-name-operator": "サービス名演算子を選択", - "aria-label-select-span-name": "スパン名を選択", - "aria-label-select-span-name-operator": "スパン名演算子を選択", - "ariaLabel-select-max-span-duration": "最大スパン期間を選択", - "ariaLabel-select-min-span-duration": "最小スパン期間を選択", - "label-collapse": "スパンフィルター", - "label-duration": "継続時間", - "label-service-name": "サービス名", - "label-span-name": "スパン名", - "label-tags": "タグ", - "placeholder-all-service-names": "すべてのサービス名", - "placeholder-all-span-names": "すべてのスパン名", - "tooltip-collapse": "以下のスパンを絞り込みます。最も関心のある少数のスパンに絞り込むまで、フィルターを適用し続けることができます。", - "tooltip-duration": "期間で絞り込みます。使用可能な単位:{{units}}", - "tooltip-tags": "スパン内のタグ、プロセスタグ、またはログフィールドで絞り込みます。" - }, - "span-filters-tags": { - "aria-label-add-tag": "タグを追加", - "aria-label-input-tag-value": "タグ値を入力", - "aria-label-remove-tag": "タグを削除", - "aria-label-select-tag-key": "タグキーを選択", - "aria-label-select-tag-operator": "タグ演算子を選択", - "aria-label-select-tag-value": "タグ値を選択", - "placeholder-select-tag": "タグを選択", - "placeholder-select-value": "値を選択", - "placeholder-tag-value": "タグ値", - "tooltip-add-tag": "タグを追加", - "tooltip-remove-tag": "タグを削除" - }, "span-flame-graph": { "flame-graph": "フレームグラフ" }, @@ -7847,23 +7847,18 @@ "label-upsample": "アップサンプリング", "tooltip-s-m-h": "10秒、1分、30分、1時間" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "クエリを実行", - "modal-title": "SQLエディター", "tooltip-experimental": "SQL Expressions LLMの統合は実験的です。問題が発生した場合は、Grafanaチームに報告してください。" }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "入力" @@ -7938,11 +7933,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9358,6 +9349,7 @@ "name-unit": "単位", "name-value-name": "値の名前", "name-y-axis-scale": "Y軸スケール", + "name-y-bucket-scale": "", "placeholder-axis-label": "自動", "placeholder-axis-width": "自動", "placeholder-decimals": "自動", @@ -9387,6 +9379,18 @@ "label-all": "すべて", "label-hidden": "非表示", "label-single": "単体" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11157,9 +11161,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11921,7 +11930,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "詳細を表示", "loading-finished-job": "完了したジョブを読み込み中...", @@ -12027,6 +12039,9 @@ "webhook-last-event": "最新イベント:", "webhook-url": "Webhookを表示" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "リポジトリに戻る", "cleaning-up-resources": "リポジトリリソースのクリーンアップ中", @@ -12131,6 +12146,9 @@ "tooltip-unhealthy-repository": "問題のあるリポジトリをプルできません" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12150,10 +12168,15 @@ }, "warning-title-default": "警告", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "このプロセスの所要時間は、関連するリソースの数によって異なります。", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12172,6 +12195,7 @@ "step-finish": "追加設定を選択", "step-synchronize": "外部ストレージと同期", "sync-description": "リソースを外部ストレージと同期します。この一度限りの手順が完了すると、その後のすべての更新は自動的にリポジトリに保存され、インスタンスにプロビジョニングされます。", + "sync-option-migrate-resources": "", "title-bootstrap": "同期する内容を選択", "title-connect": "外部ストレージに接続", "title-finish": "追加設定を選択", @@ -12408,16 +12432,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/ko-KR/grafana.json b/public/locales/ko-KR/grafana.json index 07e410e67e1..bd4103a1de1 100644 --- a/public/locales/ko-KR/grafana.json +++ b/public/locales/ko-KR/grafana.json @@ -2655,6 +2655,35 @@ "text-federated": "연합됨", "text-provisioned": "프로비저닝됨" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "데이터 소스", @@ -3701,6 +3730,7 @@ "text": "쿼리에 대해 찾은 결과 없음" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6159,7 +6189,7 @@ "title-someone-else-has-updated-this-dashboard": "다른 사람이 이 대시보드를 업데이트했습니다", "would-still-dashboard": "그래도 이 대시보드를 저장하시겠어요?" }, - "save-and-overwrite": "'저장 및 덮어쓰기'" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7142,6 +7172,9 @@ "time-range-label": "시간 범위 잠그기" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "유용한 팁: {{proTip}} " }, @@ -7616,39 +7649,6 @@ }, "share-span": "공유" }, - "span-filters": { - "aria-label-select-max-span-operator": "최대 스팬 연산자 선택", - "aria-label-select-min-span-operator": "최소 스팬 연산자 선택", - "aria-label-select-service-name": "서비스 이름 선택", - "aria-label-select-service-name-operator": "서비스 이름 연산자 선택", - "aria-label-select-span-name": "스팬 이름 선택", - "aria-label-select-span-name-operator": "스팬 이름 연산자 선택", - "ariaLabel-select-max-span-duration": "최대 스팬 기간 선택", - "ariaLabel-select-min-span-duration": "최소 스팬 기간 선택", - "label-collapse": "스팬 필터", - "label-duration": "지속 시간", - "label-service-name": "서비스 이름", - "label-span-name": "스팬 이름", - "label-tags": "태그", - "placeholder-all-service-names": "모든 서비스 이름", - "placeholder-all-span-names": "모든 스팬 이름", - "tooltip-collapse": "아래에서 스팬을 필터링합니다. 결과 스팬을 가장 관심 있는 몇 가지로 좁힐 때까지 필터를 계속 적용할 수 있습니다.", - "tooltip-duration": "지속 시간을 기준으로 필터링합니다. 허용되는 단위는 {{units}}입니다", - "tooltip-tags": "스팬의 태그, 프로세스 태그 또는 로그 필드를 기준으로 필터링합니다." - }, - "span-filters-tags": { - "aria-label-add-tag": "태그 추가", - "aria-label-input-tag-value": "태그 값 입력", - "aria-label-remove-tag": "태그 제거", - "aria-label-select-tag-key": "태그 키 선택", - "aria-label-select-tag-operator": "태그 연산자 선택", - "aria-label-select-tag-value": "태그 값 선택", - "placeholder-select-tag": "태그 선택", - "placeholder-select-value": "값 선택", - "placeholder-tag-value": "태그 값", - "tooltip-add-tag": "태그 추가", - "tooltip-remove-tag": "태그 제거" - }, "span-flame-graph": { "flame-graph": "불꽃 그래프" }, @@ -7847,23 +7847,18 @@ "label-upsample": "업샘플", "tooltip-s-m-h": "10초, 1분, 30분, 1시간" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "쿼리 실행", - "modal-title": "SQL 편집기", "tooltip-experimental": "SQL 표현식 LLM 통합 기능은 실험 단계입니다. 문제가 발생하면 Grafana 팀에 보고해 주세요." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "입력" @@ -7938,11 +7933,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9358,6 +9349,7 @@ "name-unit": "단위", "name-value-name": "값 이름", "name-y-axis-scale": "Y축 스케일", + "name-y-bucket-scale": "", "placeholder-axis-label": "자동", "placeholder-axis-width": "자동", "placeholder-decimals": "자동", @@ -9387,6 +9379,18 @@ "label-all": "전체", "label-hidden": "숨김", "label-single": "단일" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11157,9 +11161,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11921,7 +11930,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "세부 정보 보기", "loading-finished-job": "완료된 작업 로딩 중...", @@ -12027,6 +12039,9 @@ "webhook-last-event": "마지막 이벤트:", "webhook-url": "웹훅 보기" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "리포지토리로 돌아가기", "cleaning-up-resources": "리포지토리 리소스 정리 및 삭제 중", @@ -12131,6 +12146,9 @@ "tooltip-unhealthy-repository": "상태가 좋지 않은 리포지토리를 가져올 수 없습니다" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12150,10 +12168,15 @@ }, "warning-title-default": "경고", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "이 프로세스의 지속 시간은 관련된 리소스 수에 따라 달라집니다.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12172,6 +12195,7 @@ "step-finish": "추가 설정 선택", "step-synchronize": "외부 스토리지와 동기화", "sync-description": "외부 스토리지와 리소스를 동기화합니다. 이 일회성 단계 후에는 향후 모든 업데이트가 자동으로 리포지토리에 저장되고 인스턴스에 다시 프로비저닝됩니다.", + "sync-option-migrate-resources": "", "title-bootstrap": "동기화할 항목 선택", "title-connect": "외부 스토리지에 연결", "title-finish": "추가 설정 선택", @@ -12408,16 +12432,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/nl-NL/grafana.json b/public/locales/nl-NL/grafana.json index 237fbb74953..d5386284647 100644 --- a/public/locales/nl-NL/grafana.json +++ b/public/locales/nl-NL/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federatief", "text-provisioned": "Provisioned" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Gegevensbron", @@ -3717,6 +3746,7 @@ "text": "Geen resultaten gevonden voor je zoekopdracht" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Iemand anders heeft dit dashboard bijgewerkt", "would-still-dashboard": "Wil je dit dashboard nog steeds opslaan?" }, - "save-and-overwrite": "'Opslaan en overschrijven'" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Tijdsbereik vergrendelen" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "ProTip: {{proTip}} " }, @@ -7641,39 +7674,6 @@ }, "share-span": "Delen" }, - "span-filters": { - "aria-label-select-max-span-operator": "Operator voor maximale span selecteren", - "aria-label-select-min-span-operator": "Selecteer een operator voor een minimumspan", - "aria-label-select-service-name": "Servicenaam selecteren", - "aria-label-select-service-name-operator": "Servicenaam operator selecteren", - "aria-label-select-span-name": "Selecteer een spannaam", - "aria-label-select-span-name-operator": " Operator voor een spannaam selecteren", - "ariaLabel-select-max-span-duration": "Selecteer een maximale spanduur", - "ariaLabel-select-min-span-duration": "Selecteer een minimale spanduur", - "label-collapse": "Spanfilters", - "label-duration": "Duur", - "label-service-name": "Servicenaam", - "label-span-name": "Spannaam", - "label-tags": "Labels", - "placeholder-all-service-names": "Alle servicenamen", - "placeholder-all-span-names": "Alle spannamen", - "tooltip-collapse": "Filter je bereik hieronder. Je kunt filters blijven toepassen totdat je het resulterende bereik hebt beperkt tot de resultaten die het meest interessant voor je zijn.", - "tooltip-duration": "Filteren op duur. Geaccepteerde eenheden zijn {{units}}", - "tooltip-tags": "Filteren op labels, labels verwerken of logvelden in je spans." - }, - "span-filters-tags": { - "aria-label-add-tag": "Label toevoegen", - "aria-label-input-tag-value": "Labelwaarde invoeren", - "aria-label-remove-tag": "Label verwijderen", - "aria-label-select-tag-key": "Labelsleutel selecteren", - "aria-label-select-tag-operator": "Labeloperator selecteren", - "aria-label-select-tag-value": "Labelwaarde selecteren", - "placeholder-select-tag": "Label selecteren", - "placeholder-select-value": "Waarde selecteren", - "placeholder-tag-value": "Labelwaarde", - "tooltip-add-tag": "Label toevoegen", - "tooltip-remove-tag": "Label verwijderen" - }, "span-flame-graph": { "flame-graph": "Vlamgrafiek" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Upsample", "tooltip-s-m-h": "10s, 1m, 30m, 1u" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Query uitvoeren", - "modal-title": "SQL-editor", "tooltip-experimental": "SQL Expressions LLM-integratie is experimenteel. Meld eventuele problemen aan het Grafana-team." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Invoer" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Eenheid", "name-value-name": "Naam van waarde:", "name-y-axis-scale": "Y-as schaal", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automatisch", "placeholder-axis-width": "Automatisch", "placeholder-decimals": "Automatisch", @@ -9422,6 +9414,18 @@ "label-all": "Alle", "label-hidden": "Verborgen", "label-single": "Enkel" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Details bekijken", "loading-finished-job": "Voltooide taak laden...", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Laatste gebeurtenis:", "webhook-url": "Webhook bekijken" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Terug naar repositories", "cleaning-up-resources": "Bronnen van repository opschonen", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Kan geen ongezonde repository ophalen" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Waarschuwing", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "De duur van dit proces is afhankelijk van het aantal betrokken bronnen.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Kies aanvullende instellingen", "step-synchronize": "Synchroniseren met externe opslag", "sync-description": "Bronnen synchroniseren met externe opslag. Na deze eenmalige stap worden alle toekomstige updates automatisch opgeslagen in de repository en opnieuw ingericht in de instantie.", + "sync-option-migrate-resources": "", "title-bootstrap": "Kies wat je wilt synchroniseren", "title-connect": "Verbinden met externe opslag", "title-finish": "Kies aanvullende instellingen", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/pl-PL/grafana.json b/public/locales/pl-PL/grafana.json index 6ff40c3ab1f..ad8f9b19b6a 100644 --- a/public/locales/pl-PL/grafana.json +++ b/public/locales/pl-PL/grafana.json @@ -2688,6 +2688,35 @@ "text-federated": "Federacja", "text-provisioned": "Po aprowizacji" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Źródło danych", @@ -3749,6 +3778,7 @@ "text": "Nie znaleziono wyników dla tego zapytania" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6222,7 +6252,7 @@ "title-someone-else-has-updated-this-dashboard": "Ktoś inny zaktualizował ten pulpit", "would-still-dashboard": "Czy nadal chcesz zapisać ten pulpit?" }, - "save-and-overwrite": "„Zapisz i zastąp”" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7211,6 +7241,9 @@ "time-range-label": "Zablokuj zakres czasu" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Wskazówka: {{proTip}}" }, @@ -7691,39 +7724,6 @@ }, "share-span": "Udostępnij" }, - "span-filters": { - "aria-label-select-max-span-operator": "Wybierz operator maksymalnego zakresu", - "aria-label-select-min-span-operator": "Wybierz operator minimalnego zakresu", - "aria-label-select-service-name": "Wybierz nazwę usługi", - "aria-label-select-service-name-operator": "Wybierz operator nazwy usługi", - "aria-label-select-span-name": "Wybierz nazwę zakresu", - "aria-label-select-span-name-operator": "Wybierz operator nazwy zakresu", - "ariaLabel-select-max-span-duration": "Wybierz maksymalny czas trwania zakresu", - "ariaLabel-select-min-span-duration": "Wybierz minimalny czas trwania zakresu", - "label-collapse": "Filtry zakresu", - "label-duration": "Czas trwania", - "label-service-name": "Nazwa usługi", - "label-span-name": "Nazwa zakresu", - "label-tags": "Znaczniki", - "placeholder-all-service-names": "Wszystkie nazwy usług", - "placeholder-all-span-names": "Wszystkie nazwy zakresów", - "tooltip-collapse": "Odfiltruj zakresy poniżej. Możesz dodawać filtry, aż zawęzisz zakres wyników do kilku najbardziej interesujących.", - "tooltip-duration": "Filtrowanie według czasu trwania. Akceptowane jednostki: {{units}}", - "tooltip-tags": "Filtruj według tagów, tagów procesu lub pól logów w swoich zakresach." - }, - "span-filters-tags": { - "aria-label-add-tag": "Dodaj tag", - "aria-label-input-tag-value": "Wpisz wartość tagu", - "aria-label-remove-tag": "Usuń tag", - "aria-label-select-tag-key": "Wybierz klucz tagu", - "aria-label-select-tag-operator": "Wybierz operator tagu", - "aria-label-select-tag-value": "Wybierz wartość tagu", - "placeholder-select-tag": "Wybierz tag", - "placeholder-select-value": "Wybierz wartość", - "placeholder-tag-value": "Wartość tagu", - "tooltip-add-tag": "Dodaj tag", - "tooltip-remove-tag": "Usuń tag" - }, "span-flame-graph": { "flame-graph": "Wykres płomienia" }, @@ -7922,23 +7922,18 @@ "label-upsample": "Zwiększ próbkowanie", "tooltip-s-m-h": "10s, 1m, 30m, 1h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Uruchom zapytanie", - "modal-title": "Edytor SQL", "tooltip-experimental": "Integracja LLM z wyrażeniami SQL jest eksperymentalna. Wszelkie problemy zgłaszaj zespołowi Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Wejście" @@ -8013,11 +8008,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9463,6 +9454,7 @@ "name-unit": "Jednostka", "name-value-name": "Nazwa wartości", "name-y-axis-scale": "Skala osi Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automatycznie", "placeholder-axis-width": "Automatycznie", "placeholder-decimals": "Automatycznie", @@ -9492,6 +9484,18 @@ "label-all": "Wszystkie", "label-hidden": "Ukryte", "label-single": "Pojedyncza" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11295,9 +11299,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -12074,7 +12083,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Zobacz szczegóły", "loading-finished-job": "Wczytywanie zakończonego zadania…", @@ -12180,6 +12192,9 @@ "webhook-last-event": "Ostatnie zdarzenie:", "webhook-url": "Wyświetl element webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Wróć do repozytoriów", "cleaning-up-resources": "Sprzątanie zasobów repozytorium", @@ -12284,6 +12299,9 @@ "tooltip-unhealthy-repository": "Nie można pobrać danych z niesprawnego repozytorium" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12303,10 +12321,15 @@ }, "warning-title-default": "Ostrzeżenie", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Czas trwania tego procesu zależy od liczby zasobów.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12325,6 +12348,7 @@ "step-finish": "Wybierz dodatkowe ustawienia", "step-synchronize": "Synchronizuj z zewnętrzną pamięcią masową", "sync-description": "Zsynchronizuj zasoby z zewnętrzną pamięcią masową. Po tym jednorazowym kroku wszystkie przyszłe aktualizacje zostaną automatycznie zapisane w repozytorium i ponownie aprowizowane w instancji.", + "sync-option-migrate-resources": "", "title-bootstrap": "Wybierz, co chcesz zsynchronizować", "title-connect": "Połączenie z zewnętrzną pamięcią masową", "title-finish": "Wybierz dodatkowe ustawienia", @@ -12564,16 +12588,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/pt-BR/grafana.json b/public/locales/pt-BR/grafana.json index cbaee920be0..8ad480fc30d 100644 --- a/public/locales/pt-BR/grafana.json +++ b/public/locales/pt-BR/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federado", "text-provisioned": "Provisionado" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Fonte de dados", @@ -3717,6 +3746,7 @@ "text": "Nenhum resultado encontrado para sua consulta" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Outra pessoa atualizou este painel", "would-still-dashboard": "Deseja salvar este painel mesmo assim?" }, - "save-and-overwrite": "\"Salvar e substituir\"" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Bloquear intervalo de tempo" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Dica de especialistas: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Compartilhar" }, - "span-filters": { - "aria-label-select-max-span-operator": "Selecionar operador de intervalo máximo", - "aria-label-select-min-span-operator": "Selecionar operador de intervalo mínimo", - "aria-label-select-service-name": "Selecionar nome do serviço", - "aria-label-select-service-name-operator": "Selecionar operador de nome do serviço", - "aria-label-select-span-name": "Selecionar nome do intervalo", - "aria-label-select-span-name-operator": "Selecione o operador de nome de intervalo", - "ariaLabel-select-max-span-duration": "Selecionar duração máxima do intervalo", - "ariaLabel-select-min-span-duration": "Selecionar duração mínima do intervalo", - "label-collapse": "Filtros de intervalo", - "label-duration": "Duração", - "label-service-name": "Nome do serviço", - "label-span-name": "Nome do intervalo", - "label-tags": "Tags", - "placeholder-all-service-names": "Todos os nomes de serviço", - "placeholder-all-span-names": "Todos os nomes de intervalo", - "tooltip-collapse": "Filtre seus intervalos abaixo. Você pode continuar aplicando filtros até restringir seus intervalos resultantes a um grupo pequeno que contenha aqueles que forem mais pertinentes para você.", - "tooltip-duration": "Filtrar por duração. As unidades aceitas são {{units}}", - "tooltip-tags": "Filtrar por tags, tags de processo ou campos de logs nos seus intervalos." - }, - "span-filters-tags": { - "aria-label-add-tag": "Adicionar tag", - "aria-label-input-tag-value": "Valor da tag de entrada", - "aria-label-remove-tag": "Remover tag", - "aria-label-select-tag-key": "Selecionar chave de tag", - "aria-label-select-tag-operator": "Selecionar operador de tag", - "aria-label-select-tag-value": "Selecionar valor da tag", - "placeholder-select-tag": "Selecionar tag", - "placeholder-select-value": "Selecionar valor", - "placeholder-tag-value": "Valor da tag", - "tooltip-add-tag": "Adicionar tag", - "tooltip-remove-tag": "Remover tag" - }, "span-flame-graph": { "flame-graph": "Gráfico de chama" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Aumentar taxa de amostragem", "tooltip-s-m-h": "10s, 1m, 30m, 1h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Executar consulta", - "modal-title": "Editor de SQL", "tooltip-experimental": "A integração do LLM de expressões SQL está em fase de testes. Informe à equipe do Grafana se surgir algum problema." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Entrada" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Unidade", "name-value-name": "Nome do valor", "name-y-axis-scale": "Escala do eixo Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automático", "placeholder-axis-width": "Automático", "placeholder-decimals": "Automático", @@ -9422,6 +9414,18 @@ "label-all": "Tudo", "label-hidden": "Oculto", "label-single": "Única" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Veja os detalhes", "loading-finished-job": "Carregando tarefa concluída…", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Último evento:", "webhook-url": "Visualizar Webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Voltar para os repositórios", "cleaning-up-resources": "Limpando recursos do repositório", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Não é possível fazer extração de um repositório instável" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Aviso", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "A duração deste processo depende da quantidade de recursos envolvidos.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Escolha configurações adicionais", "step-synchronize": "Sincronizar com armazenamento externo", "sync-description": "Sincronize recursos com armazenamento externo. Após esta única etapa, todas as atualizações futuras serão salvas automaticamente no repositório e provisionadas de volta para a instância.", + "sync-option-migrate-resources": "", "title-bootstrap": "Escolha o que será sincronizado", "title-connect": "Conectar ao armazenamento externo", "title-finish": "Escolha configurações adicionais", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/pt-PT/grafana.json b/public/locales/pt-PT/grafana.json index 4e99ebc24f7..3fed004bfdf 100644 --- a/public/locales/pt-PT/grafana.json +++ b/public/locales/pt-PT/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federado", "text-provisioned": "Aprovisionado" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Origem dos dados", @@ -3717,6 +3746,7 @@ "text": "Não foram encontrados resultados para a sua consulta" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Outra pessoa atualizou este painel de controlo", "would-still-dashboard": "Ainda pretende guardar este painel de controlo?" }, - "save-and-overwrite": "\"Guardar e substituir\"" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Bloquear intervalo de tempo" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Dica Pro: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Partilhar" }, - "span-filters": { - "aria-label-select-max-span-operator": "Selecionar o operador de intervalo máximo", - "aria-label-select-min-span-operator": "Selecionar o operador de intervalo mínimo", - "aria-label-select-service-name": "Selecione o nome do serviço", - "aria-label-select-service-name-operator": "Selecionar o operador do nome do serviço", - "aria-label-select-span-name": "Selecionar o nome do intervalo", - "aria-label-select-span-name-operator": "Selecionar o operador do nome do intervalo", - "ariaLabel-select-max-span-duration": "Selecionar a duração máxima do intervalo", - "ariaLabel-select-min-span-duration": "Selecionar a duração mínima do intervalo", - "label-collapse": "Filtros de intervalo", - "label-duration": "Duração", - "label-service-name": "Nome do serviço", - "label-span-name": "Nome do intervalo", - "label-tags": "Etiquetas", - "placeholder-all-service-names": "Todos os nomes de serviços", - "placeholder-all-span-names": "Todos os nomes de intervalos", - "tooltip-collapse": "Filtre os seus intervalos abaixo. Pode continuar a aplicar filtros até ter limitado os seus períodos resultantes para apenas alguns que lhe interessem mais.", - "tooltip-duration": "Filtrar por duração. As unidades aceites são {{units}}", - "tooltip-tags": "Filtrar por etiquetas, etiquetas de processo ou campos de registo nos seus intervalos." - }, - "span-filters-tags": { - "aria-label-add-tag": "Adicionar etiqueta", - "aria-label-input-tag-value": "Valor da etiqueta de entrada", - "aria-label-remove-tag": "Remover controlo", - "aria-label-select-tag-key": "Selecionar a chave da etiqueta", - "aria-label-select-tag-operator": "Selecionar o operador da etiqueta", - "aria-label-select-tag-value": "Selecionar o valor da etiqueta", - "placeholder-select-tag": "Selecionar a etiqueta", - "placeholder-select-value": "Selecionar valor", - "placeholder-tag-value": "Valor da etiqueta", - "tooltip-add-tag": "Adicionar etiqueta", - "tooltip-remove-tag": "Remover controlo" - }, "span-flame-graph": { "flame-graph": "Gráfico de chama" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Aumentar a quantidade de amostras", "tooltip-s-m-h": "10s, 1m, 30m, 1h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Executar consulta", - "modal-title": "Editor SQL", "tooltip-experimental": "A integração de LLM de expressões SQL é experimental. Comunique quaisquer problemas à equipa da Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Entrada" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Unidade", "name-value-name": "Nome do valor", "name-y-axis-scale": "Escala do eixo Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Automático", "placeholder-axis-width": "Automático", "placeholder-decimals": "Automático", @@ -9422,6 +9414,18 @@ "label-all": "Tudo", "label-hidden": "Oculto", "label-single": "Único" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Ver detalhes", "loading-finished-job": "A carregar o trabalho concluído...", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Último evento:", "webhook-url": "Visualizar Webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Voltar aos repositórios", "cleaning-up-resources": "A limpar recursos do repositório", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Não foi possível obter um repositório que não está em bom estado" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Aviso", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "A duração deste processo depende do número de recursos envolvidos.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Escolha as definições adicionais", "step-synchronize": "Sincronizar com armazenamento externo", "sync-description": "Sincronize recursos com um armazenamento externo. Após este passo único, todas as atualizações futuras serão guardadas automaticamente no repositório e aprovisionadas novamente para a instância.", + "sync-option-migrate-resources": "", "title-bootstrap": "Escolha o que sincronizar", "title-connect": "Ligar a um armazenamento externo", "title-finish": "Escolha as definições adicionais", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/ru-RU/grafana.json b/public/locales/ru-RU/grafana.json index 3d29410a1bf..10cd0cdd7bb 100644 --- a/public/locales/ru-RU/grafana.json +++ b/public/locales/ru-RU/grafana.json @@ -2688,6 +2688,35 @@ "text-federated": "Федеративная", "text-provisioned": "Подготовлено" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Источник данных", @@ -3749,6 +3778,7 @@ "text": "По вашему запросу ничего не найдено" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6222,7 +6252,7 @@ "title-someone-else-has-updated-this-dashboard": "Дашборд обновлен другим пользователем", "would-still-dashboard": "Все равно сохранить дашборд?" }, - "save-and-overwrite": "'Сохранить и перезаписать'" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7211,6 +7241,9 @@ "time-range-label": "Заблокировать временной диапазон" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Совет: {{proTip}}" }, @@ -7691,39 +7724,6 @@ }, "share-span": "Поделиться" }, - "span-filters": { - "aria-label-select-max-span-operator": "Выбрать оператора макс. диапазона", - "aria-label-select-min-span-operator": "Выбрать оператор мин. диапазона", - "aria-label-select-service-name": "Выбрать название службы", - "aria-label-select-service-name-operator": "Выбрать оператор названия службы", - "aria-label-select-span-name": "Выбрать название диапазона", - "aria-label-select-span-name-operator": "Выбрать оператора названия диапазона", - "ariaLabel-select-max-span-duration": "Выбрать макс. продолжительность интервала", - "ariaLabel-select-min-span-duration": "Выбрать мин. продолжительность интервала", - "label-collapse": "Фильтры диапазонов", - "label-duration": "Длительность", - "label-service-name": "Название службы", - "label-span-name": "Название диапазона", - "label-tags": "Теги", - "placeholder-all-service-names": "Все названия служб", - "placeholder-all-span-names": "Все названия диапазонов", - "tooltip-collapse": "Выполните фильтрацию своих диапазонов ниже. Вы можете продолжать применять фильтры, пока не сузите полученные диапазоны до нескольких наиболее важных для вас вариантов.", - "tooltip-duration": "Фильтр по длительности. Допустимые единицы измерения: {{units}}", - "tooltip-tags": "Фильтр по тегам, тегам процессов или полям журнала в ваших диапазонах." - }, - "span-filters-tags": { - "aria-label-add-tag": "Добавить тег", - "aria-label-input-tag-value": "Ввести значение тега", - "aria-label-remove-tag": "Удалить тег", - "aria-label-select-tag-key": "Выбрать ключ тега", - "aria-label-select-tag-operator": "Выбрать оператор тега", - "aria-label-select-tag-value": "Выбрать значение тега", - "placeholder-select-tag": "Выбрать тег", - "placeholder-select-value": "Выбрать значение", - "placeholder-tag-value": "Значение тега", - "tooltip-add-tag": "Добавить тег", - "tooltip-remove-tag": "Удалить тег" - }, "span-flame-graph": { "flame-graph": "Flame-график" }, @@ -7922,23 +7922,18 @@ "label-upsample": "Увеличить частоту выборки", "tooltip-s-m-h": "10 с, 1 мин, 30 мин, 1 ч" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Выполнить запрос", - "modal-title": "Редактор SQL", "tooltip-experimental": "Интеграция LLM с SQL-выражениями является экспериментальной. При обнаружении проблем свяжитесь с командой Grafana." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Ввод" @@ -8013,11 +8008,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9463,6 +9454,7 @@ "name-unit": "Единица", "name-value-name": "Имя значения", "name-y-axis-scale": "Шкала оси Y", + "name-y-bucket-scale": "", "placeholder-axis-label": "Авто", "placeholder-axis-width": "Авто", "placeholder-decimals": "Авто", @@ -9492,6 +9484,18 @@ "label-all": "Все", "label-hidden": "Скрыты", "label-single": "Один" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11295,9 +11299,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -12074,7 +12083,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Подробнее", "loading-finished-job": "Загрузка завершенного задания...", @@ -12180,6 +12192,9 @@ "webhook-last-event": "Последнее событие:", "webhook-url": "Просмотр веб-перехватчика" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Назад к репозиториям", "cleaning-up-resources": "Очистка ресурсов репозитория", @@ -12284,6 +12299,9 @@ "tooltip-unhealthy-repository": "Невозможно внести изменения в неисправный репозиторий" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12303,10 +12321,15 @@ }, "warning-title-default": "Предупреждение", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Длительность процесса зависит от количества задействованных ресурсов.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12325,6 +12348,7 @@ "step-finish": "Выберите дополнительные параметры", "step-synchronize": "Синхронизировать с внешним хранилищем", "sync-description": "Синхронизируйте ресурсы с внешним хранилищем. После этого разового шага все будущие обновления будут автоматически сохраняться в репозитории и загружаться обратно в экземпляр.", + "sync-option-migrate-resources": "", "title-bootstrap": "Выберите, что синхронизировать", "title-connect": "Подключение к внешнему хранилищу", "title-finish": "Выбор дополнительных параметров", @@ -12564,16 +12588,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/sv-SE/grafana.json b/public/locales/sv-SE/grafana.json index 38943db06ed..faca6a40afc 100644 --- a/public/locales/sv-SE/grafana.json +++ b/public/locales/sv-SE/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Federerade", "text-provisioned": "Provisionerad" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Datakälla", @@ -3717,6 +3746,7 @@ "text": "Inga resultat hittades för din fråga" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Någon annan har uppdaterat denna instrumentpanel", "would-still-dashboard": "Vill du fortfarande spara denna instrumentpanel?" }, - "save-and-overwrite": "”Spara och skriv över”" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Lås tidsintervall" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "ProTip: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Dela" }, - "span-filters": { - "aria-label-select-max-span-operator": "Välj operator för maximalt intervall", - "aria-label-select-min-span-operator": "Välj operator för minsta intervall", - "aria-label-select-service-name": "Välj namn för tjänst", - "aria-label-select-service-name-operator": "Välj operator för tjänstnamn", - "aria-label-select-span-name": "Välj namn på intervall", - "aria-label-select-span-name-operator": "Välj operator för intervallnamn", - "ariaLabel-select-max-span-duration": "Välj maximal varaktighet för tidsspann", - "ariaLabel-select-min-span-duration": "Välj minimal varaktighet för tidsspann", - "label-collapse": "Intervallfilter", - "label-duration": "Varaktighet", - "label-service-name": "Namn på tjänst", - "label-span-name": "Intervallnamn", - "label-tags": "Taggar", - "placeholder-all-service-names": "Alla servicenamn", - "placeholder-all-span-names": "Alla namn på intervall", - "tooltip-collapse": "Filtrera dina spann nedan. Du kan fortsätta att tillämpa filter tills du har begränsat dina resulterande spann till det fåtal som du är mest intresserad av.", - "tooltip-duration": "Filtrera per varaktighet. Accepterade enheter är {{units}}", - "tooltip-tags": "Filtrera efter taggar, processtaggar eller loggfält i dina spår." - }, - "span-filters-tags": { - "aria-label-add-tag": "Lägg till etikett", - "aria-label-input-tag-value": "Ange taggvärde", - "aria-label-remove-tag": "Ta bort tagg", - "aria-label-select-tag-key": "Välj etikettnyckel", - "aria-label-select-tag-operator": "Välj etikettoperator", - "aria-label-select-tag-value": "Välj etikettvärde", - "placeholder-select-tag": "Välj etikett", - "placeholder-select-value": "Välj värde", - "placeholder-tag-value": "Etikettvärde", - "tooltip-add-tag": "Lägg till etikett", - "tooltip-remove-tag": "Ta bort tagg" - }, "span-flame-graph": { "flame-graph": "Flamgraf" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Sampla upp", "tooltip-s-m-h": "10 s, 1 m, 30 m, 1 h" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "Kör fråga", - "modal-title": "SQL-redigerare", "tooltip-experimental": "Integreringen för SQL Expressions LLM är i ett experimentellt skede. Rapportera alla problem du stöter på till Grafana-teamet." }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Ingång" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Enhet", "name-value-name": "Värdenamn", "name-y-axis-scale": "Y-axelns skala", + "name-y-bucket-scale": "", "placeholder-axis-label": "Auto", "placeholder-axis-width": "Auto", "placeholder-decimals": "Auto", @@ -9422,6 +9414,18 @@ "label-all": "Alla", "label-hidden": "Dolt", "label-single": "Singel" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Visa detaljer", "loading-finished-job": "Läser in färdigt jobb …", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Senaste händelsen:", "webhook-url": "Visa webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Tillbaka till lagringsplatserna", "cleaning-up-resources": "Rensa lagringsplatsresurser", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "Det gick inte att hämta en ohälsosam lagringsplats" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Varning", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Hur lång den här processen är beror på hur många resurser som är inblandade.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Välj ytterligare inställningar", "step-synchronize": "Synkronisera med extern lagring", "sync-description": "Synkronisera resurser med extern lagring. Efter det här engångssteget sparas alla framtida uppdateringar automatiskt på lagringsplatsen och provisioneras tillbaka till instansen.", + "sync-option-migrate-resources": "", "title-bootstrap": "Välj vad du vill synkronisera", "title-connect": "Anslut till extern lagring", "title-finish": "Välj ytterligare inställningar", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/tr-TR/grafana.json b/public/locales/tr-TR/grafana.json index 07a0b6673ac..ad957bd271f 100644 --- a/public/locales/tr-TR/grafana.json +++ b/public/locales/tr-TR/grafana.json @@ -2666,6 +2666,35 @@ "text-federated": "Şirket dışı", "text-provisioned": "Sağlanan" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "Veri kaynağı", @@ -3717,6 +3746,7 @@ "text": "Sorgunuz için sonuç bulunamadı" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6180,7 +6210,7 @@ "title-someone-else-has-updated-this-dashboard": "Başka biri bu panoyu güncelledi", "would-still-dashboard": "Yine de bu panoyu kaydetmek istiyor musunuz?" }, - "save-and-overwrite": "\"Kaydet ve üzerine yaz\"" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7165,6 +7195,9 @@ "time-range-label": "Zaman aralığını kilitle" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "Uzman ipucu: {{proTip}}" }, @@ -7641,39 +7674,6 @@ }, "share-span": "Paylaş" }, - "span-filters": { - "aria-label-select-max-span-operator": "Maksimum zaman aralığı işlecini seçin", - "aria-label-select-min-span-operator": "Minimum zaman aralığı işlecini seçin", - "aria-label-select-service-name": "Hizmet adını seç", - "aria-label-select-service-name-operator": "Hizmet adını işlecini seç", - "aria-label-select-span-name": "Zaman aralığı adı seç", - "aria-label-select-span-name-operator": "Zaman aralığı adı işleci seçin", - "ariaLabel-select-max-span-duration": "Maksimum zaman aralığı süresini seçin", - "ariaLabel-select-min-span-duration": "Minimum zaman aralığı süresini seçin", - "label-collapse": "Zaman aralığı filtreleri", - "label-duration": "Süre", - "label-service-name": "Hizmet adı", - "label-span-name": "Zaman aralığı adı", - "label-tags": "Etiketler", - "placeholder-all-service-names": "Tüm hizmet adları", - "placeholder-all-span-names": "Tüm zaman aralığı adları", - "tooltip-collapse": "Aşağıdaki zaman aralıklarınızı filtreleyin. İlginizi en çok çeken birkaç sonucu daraltana kadar filtre uygulamaya devam edebilirsiniz.", - "tooltip-duration": "Süreye göre filtreleyin. Kabul edilen birimler: {{units}}", - "tooltip-tags": "Zamanlardaki etiketlere, işlem etiketlerine veya günlük kaydı alanlarına göre filtreleyin." - }, - "span-filters-tags": { - "aria-label-add-tag": "Etiket ekle", - "aria-label-input-tag-value": "Etiket değeri girin", - "aria-label-remove-tag": "Etiketi kaldır", - "aria-label-select-tag-key": "Etiket anahtarını seçin", - "aria-label-select-tag-operator": "Etiket işlecini seçin", - "aria-label-select-tag-value": "Etiket değerini seçin", - "placeholder-select-tag": "Etiket seçin", - "placeholder-select-value": "Değer seçin", - "placeholder-tag-value": "Etiket değeri", - "tooltip-add-tag": "Etiket ekle", - "tooltip-remove-tag": "Etiketi kaldır" - }, "span-flame-graph": { "flame-graph": "Alev grafiği" }, @@ -7872,23 +7872,18 @@ "label-upsample": "Örneklemeyi artır", "tooltip-s-m-h": "10 sn, 1 dk, 30 dk, 1 sa" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "", - "modal-title": "", "tooltip-experimental": "" }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "Girdi" @@ -7963,11 +7958,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9393,6 +9384,7 @@ "name-unit": "Birim", "name-value-name": "Değer adı", "name-y-axis-scale": "Y ekseni ölçeği", + "name-y-bucket-scale": "", "placeholder-axis-label": "Otomatik", "placeholder-axis-width": "Otomatik", "placeholder-decimals": "Otomatik", @@ -9422,6 +9414,18 @@ "label-all": "Tümü", "label-hidden": "Gizli", "label-single": "Tek" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11203,9 +11207,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11972,7 +11981,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "Ayrıntıları görüntüleyin", "loading-finished-job": "Tamamlanan iş yükleniyor...", @@ -12078,6 +12090,9 @@ "webhook-last-event": "Son Olay:", "webhook-url": "Web Kancasını Görüntüle" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "Depolara geri dön", "cleaning-up-resources": "Depo kaynakları temizleniyor", @@ -12182,6 +12197,9 @@ "tooltip-unhealthy-repository": "İyi durumda olmayan bir depo çekilemedi" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12201,10 +12219,15 @@ }, "warning-title-default": "Uyarı", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "Bu işlemin süresi dâhil olan kaynakların sayısına bağlıdır.", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12223,6 +12246,7 @@ "step-finish": "Ek ayarlar seçin", "step-synchronize": "Harici depolama ile senkronize et", "sync-description": "Kaynakları harici depolama ile senkronize edin. Bu tek seferlik adımdan sonra tüm gelecekteki güncellemeler otomatik olarak depoya kaydedilecek ve örneğe geri sağlanacaktır.", + "sync-option-migrate-resources": "", "title-bootstrap": "Nelerin senkronize edileceğini seçin", "title-connect": "Harici depolamaya bağlan", "title-finish": "Ek ayarlar seçin", @@ -12460,16 +12484,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/zh-Hans/grafana.json b/public/locales/zh-Hans/grafana.json index a1eb5ea1fae..f02bcda5189 100644 --- a/public/locales/zh-Hans/grafana.json +++ b/public/locales/zh-Hans/grafana.json @@ -2655,6 +2655,35 @@ "text-federated": "联合", "text-provisioned": "已预置" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "数据源", @@ -3701,6 +3730,7 @@ "text": "未找到与您的查询相关的结果" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6159,7 +6189,7 @@ "title-someone-else-has-updated-this-dashboard": "其他人已更新此数据面板", "would-still-dashboard": "您仍然要保存此数据面板吗?" }, - "save-and-overwrite": "‘保存并覆盖’" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7142,6 +7172,9 @@ "time-range-label": "锁定时间范围" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "专业提示:{{proTip}}" }, @@ -7616,39 +7649,6 @@ }, "share-span": "共享" }, - "span-filters": { - "aria-label-select-max-span-operator": "选择最大跨度运算符", - "aria-label-select-min-span-operator": "选择最小跨度运算符", - "aria-label-select-service-name": "选择服务名称", - "aria-label-select-service-name-operator": "选择服务名称运算符", - "aria-label-select-span-name": "选择跨度名称", - "aria-label-select-span-name-operator": "选择跨度名称运算符", - "ariaLabel-select-max-span-duration": "选择最大跨度持续时间", - "ariaLabel-select-min-span-duration": "选择最小跨度持续时间", - "label-collapse": "跨度筛选器", - "label-duration": "持续时间", - "label-service-name": "服务名称", - "label-span-name": "跨度名称", - "label-tags": "标签", - "placeholder-all-service-names": "所有服务名称", - "placeholder-all-span-names": "所有跨度名称", - "tooltip-collapse": "在下方筛选您的跨度。您可以继续应用筛选条件,直到将结果跨度缩小到您最感兴趣的少数几个。", - "tooltip-duration": "按持续时间筛选。可接受的单位是 {{units}}", - "tooltip-tags": "根据跨度中的标记、流程标记或日志字段进行筛选。" - }, - "span-filters-tags": { - "aria-label-add-tag": "添加标记", - "aria-label-input-tag-value": "输入标记值", - "aria-label-remove-tag": "移除标记", - "aria-label-select-tag-key": "选择标记键", - "aria-label-select-tag-operator": "选择标记运算符", - "aria-label-select-tag-value": "选择标记值", - "placeholder-select-tag": "选择标记", - "placeholder-select-value": "选择值", - "placeholder-tag-value": "标记值", - "tooltip-add-tag": "添加标记", - "tooltip-remove-tag": "移除标记" - }, "span-flame-graph": { "flame-graph": "火焰图" }, @@ -7847,23 +7847,18 @@ "label-upsample": "升高采样", "tooltip-s-m-h": "10 秒、1 分钟、30 分钟、1 小时" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "运行查询", - "modal-title": "SQL 编辑器", "tooltip-experimental": "SQL 表达式 LLM 集成是实验性的。若有任何问题,请向 Grafana 团队报告。" }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "输入" @@ -7938,11 +7933,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9358,6 +9349,7 @@ "name-unit": "单位", "name-value-name": "值名称", "name-y-axis-scale": "Y 轴比例", + "name-y-bucket-scale": "", "placeholder-axis-label": "自动", "placeholder-axis-width": "自动", "placeholder-decimals": "自动", @@ -9387,6 +9379,18 @@ "label-all": "全部", "label-hidden": "隐藏", "label-single": "单一" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11157,9 +11161,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11921,7 +11930,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "查看详情", "loading-finished-job": "正在加载已完成的作业...", @@ -12027,6 +12039,9 @@ "webhook-last-event": "最后一个事件:", "webhook-url": "查看 Webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "回到存储库", "cleaning-up-resources": "清理存储库资源", @@ -12131,6 +12146,9 @@ "tooltip-unhealthy-repository": "无法拉取状态不良的存储库" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12150,10 +12168,15 @@ }, "warning-title-default": "警告", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "此过程的持续时间取决于所涉及资源的数量。", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12172,6 +12195,7 @@ "step-finish": "选择附加设置", "step-synchronize": "与外部存储同步", "sync-description": "将资源与外部存储同步。完成此一次性步骤后,所有后续更新都将自动保存到存储库中,并预配回实例。", + "sync-option-migrate-resources": "", "title-bootstrap": "选择要同步的内容", "title-connect": "连接到外部存储", "title-finish": "选择附加设置", @@ -12408,16 +12432,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "", diff --git a/public/locales/zh-Hant/grafana.json b/public/locales/zh-Hant/grafana.json index df0a64f1c1e..dc05987a2e6 100644 --- a/public/locales/zh-Hant/grafana.json +++ b/public/locales/zh-Hant/grafana.json @@ -2655,6 +2655,35 @@ "text-federated": "聯合", "text-provisioned": "已佈建" }, + "saved-searches": { + "actions-aria-label": "", + "apply-aria-label": "", + "apply-tooltip": "", + "button-label": "", + "cancel": "", + "default-indicator": "", + "delete": "", + "delete-button": "", + "dropdown-aria-label": "", + "empty-state": "", + "error-load-description": "", + "error-load-title": "", + "error-name-duplicate": "", + "error-name-required": "", + "error-rename-description": "", + "error-rename-title": "", + "error-save-description": "", + "error-save-title": "", + "list-aria-label": "", + "name-placeholder": "", + "remove-default": "", + "rename": "", + "rename-button": "", + "save-button": "", + "save-current-search": "", + "save-disabled-tooltip": "", + "set-default": "" + }, "search": { "property": { "data-source": "資料來源", @@ -3701,6 +3730,7 @@ "text": "未找到您的查詢結果" }, "recently-viewed": { + "clear": "", "empty": "", "title": "" }, @@ -6159,7 +6189,7 @@ "title-someone-else-has-updated-this-dashboard": "其他人已更新此儀表板", "would-still-dashboard": "仍要儲存此儀表板嗎?" }, - "save-and-overwrite": "「儲存並覆寫」" + "save-and-overwrite": "" }, "library-viz-panel-info": { "last-edited": "", @@ -7142,6 +7172,9 @@ "time-range-label": "鎖定時間範圍" } }, + "embedded-panel": { + "powered-by": "" + }, "empty-list-cta": { "pro-tip": "專業提示:{{proTip}}" }, @@ -7616,39 +7649,6 @@ }, "share-span": "分享" }, - "span-filters": { - "aria-label-select-max-span-operator": "選擇最大範圍的運算子", - "aria-label-select-min-span-operator": "選取最小範圍的運算子", - "aria-label-select-service-name": "選取服務名稱", - "aria-label-select-service-name-operator": "選取服務名稱運算子", - "aria-label-select-span-name": "選取範圍名稱", - "aria-label-select-span-name-operator": "選擇範圍名稱運算子", - "ariaLabel-select-max-span-duration": "選擇最大跨度持續時間", - "ariaLabel-select-min-span-duration": "選取最小跨度持續時間", - "label-collapse": "範圍篩選器", - "label-duration": "持續時間", - "label-service-name": "服務名稱", - "label-span-name": "範圍名稱", - "label-tags": "標籤", - "placeholder-all-service-names": "所有服務名稱", - "placeholder-all-span-names": "所有範圍名稱", - "tooltip-collapse": "篩選下方的範圍。您可以繼續套用篩選條件,直到將結果範圍縮小到您最感興趣的幾個範圍。", - "tooltip-duration": "依持續時間篩選。可接受的單元為 {{units}}", - "tooltip-tags": "按範圍中的標記、流程標記或紀錄欄位篩選。" - }, - "span-filters-tags": { - "aria-label-add-tag": "新增標記", - "aria-label-input-tag-value": "輸入標記值", - "aria-label-remove-tag": "移除標記", - "aria-label-select-tag-key": "選擇標記鍵", - "aria-label-select-tag-operator": "選擇標記運算子", - "aria-label-select-tag-value": "選擇標記值", - "placeholder-select-tag": "選擇標記", - "placeholder-select-value": "選擇值", - "placeholder-tag-value": "標記值", - "tooltip-add-tag": "新增標記", - "tooltip-remove-tag": "移除標記" - }, "span-flame-graph": { "flame-graph": "火焰圖" }, @@ -7847,23 +7847,18 @@ "label-upsample": "向上取樣", "tooltip-s-m-h": "10 秒、1 分鐘、30 分鐘、1 小時" }, - "schema-inspector-panel": { - "aria-label-close-schema-inspector": "" - }, "sql-expr": { "button-run-query": "執行查詢", - "modal-title": "SQL 編輯器", "tooltip-experimental": "SQL 運算式 LLM 整合為實驗性功能。如有任何問題,請向 Grafana 團隊回報。" }, "sql-schema": { - "close-schema-inspector": "", "error-title": "", - "inspect-button": "", "loading": "", "no-data-title": "", "no-fields-desc": "", "no-fields-title": "", - "query-error-title": "" + "query-error-title": "", + "schema-inspector": "" }, "threshold": { "label-input": "輸入" @@ -7938,11 +7933,7 @@ "suggestions": { "arc": "", "circular": "", - "no-thresholds": "", - "style": { - "circular": "", - "simple": "" - } + "no-thresholds": "" }, "threshold": "" }, @@ -9358,6 +9349,7 @@ "name-unit": "單位", "name-value-name": "值名稱", "name-y-axis-scale": "Y 軸刻度", + "name-y-bucket-scale": "", "placeholder-axis-label": "自動", "placeholder-axis-width": "自動", "placeholder-decimals": "自動", @@ -9387,6 +9379,18 @@ "label-all": "全部", "label-hidden": "隱藏", "label-single": "單一" + }, + "y-bucket-scale-editor": { + "linear-threshold-description": "", + "linear-threshold-label": "", + "linear-threshold-placeholder": "", + "log-base-label": "", + "scale-options": { + "label-auto": "", + "label-linear": "", + "label-log": "", + "label-symlog": "" + } } }, "help-modal": { @@ -11157,9 +11161,14 @@ }, "visualization-suggestions": { "apply-suggestion-aria-label": "", + "error-loading-some-suggestions": { + "message": "" + }, "error-loading-suggestions": { "message": "", - "title": "" + "plugin-failed": "", + "title": "", + "try-again-button": "" }, "unknown-viz-type": "", "use-this-suggestion": "" @@ -11921,7 +11930,10 @@ "resource-not-found": "", "unsupported-repository-type": "" }, - "inline-secure-values-warning": "", + "instance-sync-deprecation": { + "message": "", + "title": "" + }, "job-status": { "label-view-details": "檢視詳細資料", "loading-finished-job": "正在載入已完成的作業…", @@ -12027,6 +12039,9 @@ "webhook-last-event": "上次事件:", "webhook-url": "檢視 Webhook" }, + "repository-status": { + "error": "" + }, "repository-status-page": { "back-to-repositories": "返回至儲存庫", "cleaning-up-resources": "清理儲存庫資源", @@ -12131,6 +12146,9 @@ "tooltip-unhealthy-repository": "無法拉取狀態不佳的儲存庫" }, "synchronize-step": { + "instance-migrate-resources-description": "", + "migrate-resources-description": "", + "options": "", "repository-error": "", "repository-error-message": "", "repository-unhealthy": "" @@ -12150,10 +12168,15 @@ }, "warning-title-default": "警告", "wizard": { + "alert-intro": "", "alert-point-1": "", - "alert-point-2": "", "alert-point-3": "此流程的持續時間取決於所涉及的資源數量。", "alert-point-4": "", + "alert-point-folder-cleanup": "", + "alert-point-folder-structure": "", + "alert-point-instance-alerts": "", + "alert-point-permissions": "", + "alert-point-unsupported": "", "alert-title": "", "button-cancel": "", "button-cancelling": "", @@ -12172,6 +12195,7 @@ "step-finish": "選擇附加設定", "step-synchronize": "與外部儲存空間同步", "sync-description": "將資源與外部儲存空間同步。在此一次性步驟之後,未來的所有更新都將自動儲存到儲存庫中,並佈建回執行個體。", + "sync-option-migrate-resources": "", "title-bootstrap": "選擇要同步的內容", "title-connect": "連接到外部儲存空間", "title-finish": "選擇附加設定", @@ -12408,16 +12432,21 @@ }, "radialbar": { "config": { + "bar-shape": "", + "bar-shape-flat": "", + "bar-shape-rounded": "", "bar-width": "", "effects": { "bar-glow": "", "center-glow": "", "gradient": "", - "label": "", - "rounded-bars": "", - "spotlight": "", - "spotlight-tooltip": "" + "label": "" }, + "endpoint-marker": "", + "endpoint-marker-description": "", + "endpoint-marker-glow": "", + "endpoint-marker-none": "", + "endpoint-marker-point": "", "segment-count": "", "segment-spacing": "", "shape": "",