Merge remote-tracking branch 'origin/main' into ds-apiserver-with-configs

This commit is contained in:
Ryan McKinley
2025-08-21 14:27:49 +03:00
503 changed files with 11523 additions and 19843 deletions
+9 -1
View File
@@ -6,6 +6,7 @@ const jsxA11yPlugin = require('eslint-plugin-jsx-a11y');
const lodashPlugin = require('eslint-plugin-lodash');
const barrelPlugin = require('eslint-plugin-no-barrel-files');
const reactPlugin = require('eslint-plugin-react');
const hooksPlugin = require('eslint-plugin-react-hooks');
const testingLibraryPlugin = require('eslint-plugin-testing-library');
const grafanaConfig = require('@grafana/eslint-config/flat');
@@ -16,7 +17,7 @@ const grafanaI18nPlugin = require('@grafana/i18n/eslint-plugin');
// as we just want to pull in all of the necessary configuration but not run the rules
// (this should only be concerned with checking rules that we want to improve,
// so there's no need to try and run the rules that will be linted properly anyway)
const { rules, ...baseConfig } = grafanaConfig;
const { rules, ...baseConfig } = grafanaConfig.find((config) => config?.name === '@grafana/eslint-config/flat');
/**
* @type {Array<import('eslint').Linter.Config>}
@@ -53,6 +54,13 @@ module.exports = [
// @ts-ignore - not sure why but flat config is typed as a maybe?
...reactPlugin.configs.flat['jsx-runtime'],
},
// FIXME: Remove once eslint-config-grafana is updated to include correct plugin
{
name: 'react-hooks-plugin',
plugins: {
'react-hooks': hooksPlugin,
},
},
{
files: ['**/*.{ts,tsx,js}'],
...baseConfig,
-38
View File
@@ -1,38 +0,0 @@
# To generate the .drone.yml file:
# 1. Modify the *.star definitions
# 2. Login to drone and export the env variables (token and server) shown here: https://drone.grafana.net/account
# 3. Run `make drone`
# More information about this process here: https://github.com/grafana/deployment_tools/blob/master/docs/infrastructure/drone/signing.md
"""
This module returns a Drone configuration including pipelines and secrets.
"""
load("scripts/drone/events/main.star", "main_pipelines")
load(
"scripts/drone/events/release.star",
"publish_artifacts_pipelines",
"publish_npm_pipelines",
"publish_packages_pipeline",
)
load("scripts/drone/events/rrc-patch.star", "rrc_patch_pipelines")
load(
"scripts/drone/pipelines/publish_images.star",
"publish_image_pipelines_public",
)
load(
"scripts/drone/rgm.star",
"rgm",
)
load("scripts/drone/vault.star", "secrets")
def main(_ctx):
return (
main_pipelines() +
rrc_patch_pipelines() +
publish_image_pipelines_public() +
publish_artifacts_pipelines("public") +
publish_npm_pipelines() +
publish_packages_pipeline() +
rgm() +
secrets()
)
-1880
View File
File diff suppressed because it is too large Load Diff
+45 -7
View File
@@ -328,9 +328,6 @@
# Continuous Integration
.drone.yml @grafana/grafana-developer-enablement-squad
.drone.star @grafana/grafana-developer-enablement-squad
/scripts/drone/ @grafana/grafana-developer-enablement-squad
/pkg/build/ @grafana/grafana-developer-enablement-squad
/.dockerignore @grafana/grafana-developer-enablement-squad
/Dockerfile @grafana/grafana-developer-enablement-squad
@@ -411,9 +408,14 @@
/public/locales/i18next-parser-enterprise.config.cjs @grafana/grafana-frontend-platform
/public/app/core/internationalization/ @grafana/grafana-frontend-platform
/e2e/ @grafana/grafana-frontend-platform
/e2e-playwright/ @grafana/grafana-frontend-platform
/e2e-playwright/cloud-plugins-suite/ @grafana/partner-datasources
/e2e-playwright/dashboard-new-layouts @grafana/dashboards-squad
/e2e-playwright/dashboard-new-layouts/ @grafana/dashboards-squad
/e2e-playwright/dashboards-search-suite/ @grafana/dashboards-squad
/e2e-playwright/dashboards/DashboardLiveTest.json @grafana/dashboards-squad
/e2e-playwright/dashboards/DataLinkWithoutSlugTest.json @grafana/dashboards-squad
/e2e-playwright/dashboards/PanelSandboxDashboard.json @grafana/plugins-platform-frontend
/e2e-playwright/dashboards/TestDashboard.json @grafana/dashboards-squad @grafana/grafana-search-navigate-organise
/e2e-playwright/dashboards/TestV2Dashboard.json @grafana/dashboards-squad
/e2e-playwright/dashboards-suite/dashboard-browse-nested.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/dashboards-suite/dashboard-browse.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/dashboards-suite/dashboard-export-image.spec.ts @grafana/sharing-squad
@@ -447,6 +449,9 @@
/e2e-playwright/dashboards-suite/templating-dashboard-links-and-variables.spec.ts @grafana/dashboards-squad
/e2e-playwright/dashboards-suite/textbox-variables.spec.ts @grafana/dashboards-squad
/e2e-playwright/dashboards-suite/utils/makeDashboard.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/fixtures/exemplars-query-response.json @grafana/observability-traces-and-profiling
/e2e-playwright/fixtures/long-trace-response.json @grafana/observability-traces-and-profiling
/e2e-playwright/fixtures/tempo-response.json @grafana/oss-big-tent
/e2e-playwright/panels-suite/dashlist.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/panels-suite/datagrid-data-change.spec.ts @grafana/dataviz-squad
/e2e-playwright/panels-suite/datagrid-editing-features.spec.ts @grafana/dataviz-squad
@@ -458,10 +463,43 @@
/e2e-playwright/panels-suite/panelEdit_queries.spec.ts @grafana/dashboards-squad
/e2e-playwright/panels-suite/panelEdit_transforms.spec.ts @grafana/datapro
/e2e-playwright/panels-suite/table-kitchenSink.spec.ts @grafana/dataviz-squad
/e2e-playwright/panels-suite/table-markdown.spec.ts @grafana/dataviz-squad
/e2e-playwright/panels-suite/table-sparkline.spec.ts @grafana/dataviz-squad
/e2e-playwright/plugin-e2e/ @grafana/oss-big-tent @grafana/partner-datasources
/e2e-playwright/plugin-e2e/plugin-e2e-api-tests/ @grafana/plugins-platform-frontend
/e2e-playwright/test-plugins/grafana-extensionstest-app/ @grafana/plugins-platform-frontend
/e2e-playwright/smoke-tests-suite/ @grafana/grafana-frontend-platform
/e2e-playwright/start-server @grafana/grafana-frontend-platform
/e2e-playwright/storybook/ @grafana/grafana-frontend-platform
/e2e-playwright/test-plugins/ @grafana/plugins-platform-frontend
/e2e-playwright/unauthenticated/login.spec.ts @grafana/grafana-frontend-platform
/e2e-playwright/utils/ @grafana/grafana-frontend-platform
/e2e-playwright/various-suite/bar-gauge.spec.ts @grafana/dataviz-squad
/e2e-playwright/various-suite/bookmarks.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/various-suite/exemplars.spec.ts @grafana/observability-traces-and-profiling
/e2e-playwright/various-suite/explore.spec.ts @grafana/observability-traces-and-profiling
/e2e-playwright/various-suite/filter-annotations.spec.ts @grafana/dashboards-squad
/e2e-playwright/various-suite/frontend-sandbox-app.spec.ts @grafana/plugins-platform-frontend
/e2e-playwright/various-suite/frontend-sandbox-datasource.spec.ts @grafana/plugins-platform-frontend
/e2e-playwright/various-suite/gauge.spec.ts @grafana/dataviz-squad
/e2e-playwright/various-suite/graph-auto-migrate.spec.ts @grafana/dataviz-squad
/e2e-playwright/various-suite/inspect-drawer.spec.ts @grafana/dashboards-squad
/e2e-playwright/various-suite/keybinds.spec.ts @grafana/grafana-frontend-platform
/e2e-playwright/various-suite/loki-query-builder.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/loki-table-explore-to-dash.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/migrate-to-cloud.spec.ts @grafana/grafana-operator-experience-squad
/e2e-playwright/various-suite/navigation.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/various-suite/pie-chart.spec.ts @grafana/dataviz-squad
/e2e-playwright/various-suite/prometheus-annotations.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/prometheus-config.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/prometheus-editor.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/prometheus-variable-editor.spec.ts @grafana/oss-big-tent
/e2e-playwright/various-suite/query-editor.spec.ts @grafana/observability-traces-and-profiling
/e2e-playwright/various-suite/return-to-previous.spec.ts @grafana/grafana-search-navigate-organise
/e2e-playwright/various-suite/solo-route.spec.ts @grafana/dashboards-squad
/e2e-playwright/various-suite/trace-view-scrolling.spec.ts @grafana/observability-traces-and-profiling
/e2e-playwright/various-suite/verify-i18n.spec.ts @grafana/grafana-frontend-platform
/e2e-playwright/various-suite/visualization-suggestions.spec.ts @grafana/dashboards-squad
/e2e-playwright/various-suite/perf-test.spec.ts @grafana/grafana-frontend-platform
# Packages
/packages/README.md @grafana/grafana-frontend-platform
@@ -639,7 +677,6 @@
/packages/grafana-schema/src/**/nodegraph @grafana/observability-traces-and-profiling @grafana/app-o11y-visualizations
/packages/grafana-schema/src/**/parca @grafana/oss-big-tent
/packages/grafana-schema/src/**/piechart @grafana/dataviz-squad
/packages/grafana-schema/src/**/publicdashboard @grafana/grafana-operator-experience-squad
/packages/grafana-schema/src/**/stat @grafana/dataviz-squad
/packages/grafana-schema/src/**/statetimeline @grafana/dataviz-squad
/packages/grafana-schema/src/**/statushistory @grafana/dataviz-squad
@@ -1216,6 +1253,7 @@ embed.go @grafana/grafana-as-code
/.github/workflows/analytics-events-report.yml @grafana/grafana-frontend-platform
/.github/workflows/pr-e2e-tests.yml @grafana/grafana-developer-enablement-squad
/.github/workflows/skye-add-to-project.yml @grafana/grafana-frontend-platform
/.github/workflows/frontend-perf-tests.yaml @grafana/grafana-frontend-platform
/.github/zizmor.yml @grafana/grafana-developer-enablement-squad
/.github/license_finder.yaml @bergquist
/.github/actionlint.yaml @grafana/grafana-developer-enablement-squad
+67
View File
@@ -139,3 +139,70 @@ jobs:
cache-dependency-path: 'yarn.lock'
- run: yarn install --immutable --check-cache
- run: yarn run betterer:ci
lint-frontend-api-clients:
permissions:
contents: read
id-token: write
# Run this workflow only for PRs from forks; if it gets merged into `main` or `release-*`,
# the `lint-frontend-api-clients-enterprise` workflow will run instead
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
name: Verify API clients
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- run: yarn install --immutable --check-cache
- name: Generate API clients
run: |
extract_error_message='ERROR! API client generation failed!'
yarn generate-apis || (echo "${extract_error_message}" && false)
- name: Verify generated clients
run: |
uncommited_error_message="ERROR! API client generation has not been committed. Please run 'yarn generate-apis', commit the changes and push again."
file_diff="$(git diff ':!conf')"
if [ -n "$file_diff" ]; then
echo "$file_diff"
echo "${uncommited_error_message}"
exit 1
fi
lint-frontend-api-clients-enterprise:
permissions:
contents: read
id-token: write
# Run this workflow for non-PR events (like pushes to `main` or `release-*`) OR for internal PRs (PRs not from forks)
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false
name: Verify API clients (enterprise)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
cache-dependency-path: 'yarn.lock'
- name: Setup Enterprise
uses: ./.github/actions/setup-enterprise
with:
github-app-name: 'grafana-ci-bot'
- run: yarn install --immutable --check-cache
- name: Generate API clients
run: |
extract_error_message='ERROR! API client generation failed!'
yarn generate-apis || (echo "${extract_error_message}" && false)
- name: Verify generated clients
run: |
uncommited_error_message="ERROR! API client generation has not been committed. Please run 'yarn generate-apis', commit the changes and push again."
file_diff="$(git diff ':!conf')"
if [ -n "$file_diff" ]; then
echo "$file_diff"
echo "${uncommited_error_message}"
exit 1
fi
+133
View File
@@ -0,0 +1,133 @@
name: Frontend performance tests
on:
schedule:
- cron: "0 * * * *" # Run hourly
workflow_dispatch: # Allow manual triggering
jobs:
performance-tests:
permissions:
contents: read
id-token: write
runs-on: ubuntu-x64-large
steps:
- name: Checkout repo
uses: actions/checkout@v4
with:
persist-credentials: false
- id: get-secrets
uses: grafana/shared-workflows/actions/get-vault-secrets@62722333225a1fae03ae27a63d638f9bc2176edb #get-vault-secrets-v1.2.0
with:
repo_secrets: |
PROMETHEUS_URL=frontend_perf_tests:prometheus_push_url
PROMETHEUS_USER=frontend_perf_tests:prometheus_user
PROMETHEUS_TOKEN=frontend_perf_tests:prometheus_token
FSPERFBASELINE_USERNAME=frontend_perf_tests:fsperfbaseline_username
FSPERFBASELINE_PASSWORD=frontend_perf_tests:fsperfbaseline_password
FSPERF_USERNAME=frontend_perf_tests:fsperf_username
FSPERF_PASSWORD=frontend_perf_tests:fsperf_password
- name: Authenticate Docker
uses: grafana/shared-workflows/actions/login-to-gar@main
id: login-to-gar
with:
registry: 'us-docker.pkg.dev'
- name: Setup Node.js
uses: ./.github/actions/setup-node
- name: Yarn install
run: yarn install --immutable
env:
PUPPETEER_SKIP_DOWNLOAD: true
CYPRESS_INSTALL_BINARY: 0
- name: Install Playwright browsers
run: yarn playwright install chromium --with-deps
- name: Run Playwright tests (fsperfbaseline)
id: pw-fsperfbaseline
continue-on-error: true
env:
PLAYWRIGHT_JSON_OUTPUT_NAME: ./fsperfbaseline-pw-results.json
METRICS_OUTPUT_PATH: ./fsperfbaseline-metrics.txt
GRAFANA_URL: https://fsperfbaseline.grafana-dev.net
GRAFANA_ADMIN_USER: ${{ env.FSPERFBASELINE_USERNAME }}
GRAFANA_ADMIN_PASSWORD: ${{ env.FSPERFBASELINE_PASSWORD }}
run: yarn e2e:playwright --grep @performance --reporter json
- name: Run Playwright tests (fsperf)
id: pw-fsperf
continue-on-error: true
env:
PLAYWRIGHT_JSON_OUTPUT_NAME: ./fsperf-pw-results.json
METRICS_OUTPUT_PATH: ./fsperf-metrics.txt
GRAFANA_URL: https://fsperf.grafana-dev.net
GRAFANA_ADMIN_USER: ${{ env.FSPERF_USERNAME }}
GRAFANA_ADMIN_PASSWORD: ${{ env.FSPERF_PASSWORD }}
run: yarn e2e:playwright --grep @performance --reporter json
- name: Bench report (fsperfbaseline)
id: bench-fsperfbaseline
if: always()
continue-on-error: true
run: |
docker run \
--rm \
--volume="./fsperfbaseline-pw-results.json:/pw-results.json" \
--volume="./fsperfbaseline-metrics.txt:/metrics.txt" \
-e PROMETHEUS_URL="$PROMETHEUS_URL" \
-e PROMETHEUS_USER="$PROMETHEUS_USER" \
-e PROMETHEUS_PASSWORD="$PROMETHEUS_TOKEN" \
us-docker.pkg.dev/grafanalabs-global/docker-grafana-bench-prod/grafana-bench:v0.6.0 report \
--grafana-url "http://fsperfbaseline.grafana-dev.net" \
--test-suite-name "FrontendPerfTests" \
--report-input playwright \
--report-output log \
--prometheus-metrics \
--run-metrics-file "/metrics.txt" \
--log-level DEBUG \
/pw-results.json
- name: Bench report (fsperf)
id: bench-fsperf
if: always()
continue-on-error: true
run: |
docker run \
--rm \
--volume="./fsperf-pw-results.json:/pw-results.json" \
--volume="./fsperf-metrics.txt:/metrics.txt" \
-e PROMETHEUS_URL="$PROMETHEUS_URL" \
-e PROMETHEUS_USER="$PROMETHEUS_USER" \
-e PROMETHEUS_PASSWORD="$PROMETHEUS_TOKEN" \
us-docker.pkg.dev/grafanalabs-global/docker-grafana-bench-prod/grafana-bench:v0.6.0 report \
--grafana-url "http://fsperf.grafana-dev.net" \
--test-suite-name "FrontendPerfTests" \
--report-input playwright \
--report-output log \
--prometheus-metrics \
--run-metrics-file "/metrics.txt" \
--log-level DEBUG \
/pw-results.json
- name: Check status
env:
FSPERF_PW_OUTCOME: ${{ steps.pw-fsperf.outcome }}
FSPERF_PW_BASELINE_OUTCOME: ${{ steps.pw-fsperfbaseline.outcome }}
FSPERF_BENCH_OUTCOME: ${{ steps.bench-fsperf.outcome }}
FSPERF_BENCH_BASELINE_OUTCOME: ${{ steps.bench-fsperfbaseline.outcome }}
run: |
echo "FSPERF_PW_OUTCOME: $FSPERF_PW_OUTCOME"
echo "FSPERF_PW_BASELINE_OUTCOME: $FSPERF_PW_BASELINE_OUTCOME"
echo "FSPERF_BENCH_OUTCOME: $FSPERF_BENCH_OUTCOME"
echo "FSPERF_BENCH_BASELINE_OUTCOME: $FSPERF_BENCH_BASELINE_OUTCOME"
if [[ "$FSPERF_PW_OUTCOME" != "success" || "$FSPERF_PW_BASELINE_OUTCOME" != "success" || "$FSPERF_BENCH_OUTCOME" != "success" || "$FSPERF_BENCH_BASELINE_OUTCOME" != "success" ]]; then
echo "One or more test steps failed."
exit 1
fi
+3 -26
View File
@@ -283,13 +283,9 @@ run-bra: ## [Deprecated] Build and run web server on filesystem changes. See /.b
frontend-service-check:
./devenv/frontend-service/local-init.sh
.PHONY: frontend-service-up
frontend-service-up: frontend-service-check
tilt up -f devenv/frontend-service/Tiltfile
.PHONY: frontend-service-down
frontend-service-down: frontend-service-check
tilt down -f devenv/frontend-service/Tiltfile
.PHONY: frontend-service
frontend-service: frontend-service-check
bash ./devenv/frontend-service/run.sh
##@ Testing
@@ -528,25 +524,6 @@ gen-ts:
tscriptify -interface -package=github.com/grafana/grafana/pkg/services/live/pipeline -import="import { FieldConfig } from '@grafana/data'" -target=public/app/features/live/pipeline/models.gen.ts pkg/services/live/pipeline/config.go
go mod tidy
# This repository's configuration is protected (https://readme.drone.io/signature/).
# Use this make target to regenerate the configuration YAML files when
# you modify starlark files.
.PHONY: drone
drone: $(DRONE)
bash scripts/drone/env-var-check.sh
$(DRONE) starlark --format
$(DRONE) lint .drone.yml --trusted
$(DRONE) --server https://drone.grafana.net sign --save grafana/grafana
# Generate an Emacs tags table (https://www.gnu.org/software/emacs/manual/html_node/emacs/Tags-Tables.html) for Starlark files.
.PHONY: scripts/drone/TAGS
scripts/drone/TAGS: $(shell find scripts/drone -name '*.star')
etags --lang none --regex="/def \(\w+\)[^:]+:/\1/" --regex="/\s*\(\w+\) =/\1/" $^ -o $@
.PHONY: format-drone
format-drone:
buildifier --lint=fix -r scripts/drone
.PHONY: go-race-is-enabled
go-race-is-enabled:
@if [ -n "$(GO_RACE)" ]; then \
+5 -4
View File
@@ -82,13 +82,14 @@ require (
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
+12 -12
View File
@@ -252,8 +252,8 @@ go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
@@ -270,8 +270,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
@@ -288,14 +288,14 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -308,8 +308,8 @@ golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtn
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+6 -6
View File
@@ -110,15 +110,15 @@ require (
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // indirect
golang.org/x/mod v0.26.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/mod v0.27.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.35.0 // indirect
golang.org/x/tools v0.36.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+6 -12
View File
@@ -314,15 +314,13 @@ golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -341,14 +339,11 @@ golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -356,8 +351,7 @@ golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -0,0 +1,79 @@
package schemaversion
// migration_utils.go contains shared utility functions used across multiple schema version migrations.
// GetStringValue safely extracts a string value from a map, returning empty string if not found or not a string
func GetStringValue(m map[string]interface{}, key string) string {
if value, ok := m[key]; ok {
if s, ok := value.(string); ok {
return s
}
}
return ""
}
// GetBoolValue safely extracts a boolean value from a map, returning false if not found or not a boolean
func GetBoolValue(m map[string]interface{}, key string) bool {
if value, ok := m[key]; ok {
if b, ok := value.(bool); ok {
return b
}
}
return false
}
// GetIntValue safely extracts an integer value from a map, returning defaultValue if not found or not convertible
func GetIntValue(m map[string]interface{}, key string, defaultValue int) int {
if value, ok := m[key]; ok {
if i, ok := ConvertToInt(value); ok {
return i
}
}
return defaultValue
}
// GetFloatValue safely extracts a float value from a map, returning defaultValue if not found or not convertible
func GetFloatValue(m map[string]interface{}, key string, defaultValue float64) float64 {
if value, ok := m[key]; ok {
if f, ok := ConvertToFloat(value); ok {
return f
}
}
return defaultValue
}
// ConvertToFloat converts various numeric types to float64
func ConvertToFloat(value interface{}) (float64, bool) {
switch v := value.(type) {
case float64:
return v, true
case int:
return float64(v), true
case int64:
return float64(v), true
case float32:
return float64(v), true
case int32:
return float64(v), true
default:
return 0, false
}
}
// ConvertToInt converts various numeric types to int
func ConvertToInt(value interface{}) (int, bool) {
switch v := value.(type) {
case int:
return v, true
case float64:
return int(v), true
case int64:
return int(v), true
case float32:
return int(v), true
case int32:
return int(v), true
default:
return 0, false
}
}
@@ -5,7 +5,7 @@ import (
)
const (
MIN_VERSION = 16
MIN_VERSION = 14
LATEST_VERSION = 41
)
@@ -38,6 +38,8 @@ type PanelPluginInfoProvider interface {
func GetMigrations(dsInfoProvider DataSourceInfoProvider, panelProvider PanelPluginInfoProvider) map[int]SchemaVersionMigrationFunc {
return map[int]SchemaVersionMigrationFunc{
15: V15,
16: V16,
17: V17,
18: V18,
19: V19,
@@ -0,0 +1,25 @@
package schemaversion
// V15 migration is a no-op migration
// It only updates the schema version to 15
// It's created to keep the migration history consistent with frontend migrator
// No specific migration logic is needed between schema version 14 and 15
// Example before migration:
// {
// "schemaVersion": 14,
// "title": "My Dashboard",
// "panels": [...]
// }
// Example after migration:
// {
// "schemaVersion": 15,
// "title": "My Dashboard",
// "panels": [...]
// }
func V15(dashboard map[string]interface{}) error {
dashboard["schemaVersion"] = 15
return nil
}
@@ -0,0 +1,38 @@
package schemaversion_test
import (
"testing"
"github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion"
)
func TestV15(t *testing.T) {
tests := []migrationTestCase{
{
name: "v15 no-op migration, updates schema version only",
input: map[string]interface{}{
"title": "V15 No-Op Migration Test Dashboard",
"schemaVersion": 14,
"panels": []interface{}{
map[string]interface{}{
"type": "graph",
"title": "Panel remains unchanged",
"id": 1,
},
},
},
expected: map[string]interface{}{
"title": "V15 No-Op Migration Test Dashboard",
"schemaVersion": 15,
"panels": []interface{}{
map[string]interface{}{
"type": "graph",
"title": "Panel remains unchanged",
"id": 1,
},
},
},
},
}
runMigrationTests(t, tests, schemaversion.V15)
}
@@ -0,0 +1,308 @@
package schemaversion
import (
"math"
)
const (
gridColumnCount = 24.0
defaultPanelSpan = 4.0
defaultRowHeight = 250.0
gridCellHeight = 30.0
gridCellVMargin = 8.0
minPanelHeight = gridCellHeight * 3.0
panelHeightStep = gridCellHeight + gridCellVMargin
)
// V16 migrates dashboard layout from the old row-based system to the modern grid-based layout.
// This migration follows the exact logic from DashboardMigrator.ts to ensure consistency between frontend and backend.
func V16(dashboard map[string]interface{}) error {
dashboard["schemaVersion"] = 16
upgradeToGridLayout(dashboard)
return nil
}
func upgradeToGridLayout(dashboard map[string]interface{}) {
rowsInterface, ok := dashboard["rows"]
if !ok {
return
}
rows, ok := rowsInterface.([]interface{})
if !ok {
return
}
// Handle empty rows
if len(rows) == 0 {
dashboard["panels"] = []interface{}{}
delete(dashboard, "rows")
return
}
yPos := 0
widthFactor := gridColumnCount / 12.0
// Find max panel ID (lines 1014-1021 in TS)
maxPanelID := getMaxPanelID(rows)
nextRowID := maxPanelID + 1
// Get existing panels
var finalPanels []interface{}
if existingPanels, ok := dashboard["panels"].([]interface{}); ok {
finalPanels = existingPanels
}
// Add special "row" panels if even one row is collapsed, repeated or has visible title (line 1028 in TS)
showRows := shouldShowRows(rows)
// Process each row (line 1030 in TS)
for _, rowInterface := range rows {
row, ok := rowInterface.(map[string]interface{})
if !ok {
continue
}
// Skip repeated rows (line 1031-1033 in TS)
if _, hasRepeatIteration := row["repeatIteration"]; hasRepeatIteration {
continue
}
height := getRowHeight(row)
rowGridHeight := getGridHeight(height)
isCollapsed := GetBoolValue(row, "collapse")
var rowPanel map[string]interface{}
// First pass: assign IDs to panels that don't have them
panelsInRow, ok := row["panels"].([]interface{})
if !ok {
panelsInRow = []interface{}{}
}
for _, panelInterface := range panelsInRow {
panel, ok := panelInterface.(map[string]interface{})
if !ok {
continue
}
// Assign ID if missing
if _, hasID := panel["id"]; !hasID {
panel["id"] = nextRowID
nextRowID++
}
}
if showRows {
// add special row panel (lines 1041-1058 in TS)
rowPanel = map[string]interface{}{
"id": nextRowID,
"type": "row",
"title": GetStringValue(row, "title"),
"collapsed": isCollapsed,
"repeat": GetStringValue(row, "repeat"),
"panels": []interface{}{},
"gridPos": map[string]interface{}{
"x": 0,
"y": yPos,
"w": int(gridColumnCount),
"h": rowGridHeight,
},
}
nextRowID++
yPos++
}
rowArea := newRowArea(rowGridHeight, gridColumnCount, yPos)
// Process all panels in this row (lines 1062-1087 in TS)
for _, panelInterface := range panelsInRow {
panel, ok := panelInterface.(map[string]interface{})
if !ok {
continue
}
// Set default span (line 1063 in TS)
span := GetFloatValue(panel, "span", defaultPanelSpan)
// Handle minSpan conversion (lines 1064-1066 in TS)
if minSpan, hasMinSpan := panel["minSpan"]; hasMinSpan {
if minSpanFloat, ok := ConvertToFloat(minSpan); ok && minSpanFloat > 0 {
panel["minSpan"] = int(math.Min(float64(gridColumnCount), (float64(gridColumnCount)/12.0)*minSpanFloat))
}
}
panelWidth := int(math.Floor(span * widthFactor))
panelHeight := rowGridHeight
if panelHeightValue, hasHeight := panel["height"]; hasHeight {
if h, ok := ConvertToFloat(panelHeightValue); ok {
panelHeight = getGridHeight(h)
}
}
panelPos := rowArea.getPanelPosition(panelHeight, panelWidth)
yPos = rowArea.yPos
// Set gridPos (lines 1072-1077 in TS)
panel["gridPos"] = map[string]interface{}{
"x": GetIntValue(panelPos, "x", 0),
"y": yPos + GetIntValue(panelPos, "y", 0),
"w": panelWidth,
"h": panelHeight,
}
rowArea.addPanel(panel["gridPos"].(map[string]interface{}))
// Remove span (line 1080 in TS)
delete(panel, "span")
// Exact logic from lines 1082-1086 in TS
if rowPanel != nil && isCollapsed {
// Add to collapsed row's nested panels
if rowPanelPanels, ok := rowPanel["panels"].([]interface{}); ok {
rowPanel["panels"] = append(rowPanelPanels, panel)
}
} else {
// Add directly to dashboard panels
finalPanels = append(finalPanels, panel)
}
}
// Add row panel after processing all panels (lines 1089-1091 in TS)
if rowPanel != nil {
finalPanels = append(finalPanels, rowPanel)
}
// Update yPos (lines 1093-1095 in TS)
if rowPanel == nil || !isCollapsed {
yPos += rowGridHeight
}
}
// Update the dashboard
dashboard["panels"] = finalPanels
delete(dashboard, "rows")
}
// rowArea represents dashboard row filled by panels
type rowArea struct {
area []int
yPos int
height int
}
func newRowArea(height int, width int, rowYPos int) *rowArea {
area := make([]int, width)
return &rowArea{
area: area,
yPos: rowYPos,
height: height,
}
}
func (r *rowArea) reset() {
for i := range r.area {
r.area[i] = 0
}
}
func (r *rowArea) addPanel(gridPos map[string]interface{}) {
x := GetIntValue(gridPos, "x", 0)
y := GetIntValue(gridPos, "y", 0)
w := GetIntValue(gridPos, "w", 0)
h := GetIntValue(gridPos, "h", 0)
for i := x; i < x+w && i < len(r.area); i++ {
newHeight := y + h - r.yPos
if newHeight > r.area[i] {
r.area[i] = newHeight
}
}
}
func (r *rowArea) getPanelPosition(panelHeight int, panelWidth int) map[string]interface{} {
var startPlace, endPlace int
found := false
// Find available space from right to left
for i := len(r.area) - 1; i >= 0; i-- {
if r.height-r.area[i] > 0 {
if !found {
endPlace = i
found = true
} else {
if i < len(r.area)-1 && r.area[i] <= r.area[i+1] {
startPlace = i
} else {
break
}
}
} else {
break
}
}
if found && endPlace-startPlace >= panelWidth-1 {
// Find max height in the range
yPos := 0
for i := startPlace; i <= endPlace && i < len(r.area); i++ {
if r.area[i] > yPos {
yPos = r.area[i]
}
}
return map[string]interface{}{
"x": startPlace,
"y": yPos,
}
}
// Wrap to next row
r.yPos += r.height
r.reset()
return r.getPanelPosition(panelHeight, panelWidth)
}
func getMaxPanelID(rows []interface{}) int {
maxID := 0
for _, rowInterface := range rows {
if row, ok := rowInterface.(map[string]interface{}); ok {
if panels, ok := row["panels"].([]interface{}); ok {
for _, panelInterface := range panels {
if panel, ok := panelInterface.(map[string]interface{}); ok {
if id := GetIntValue(panel, "id", 0); id > maxID {
maxID = id
}
}
}
}
}
}
return maxID
}
func shouldShowRows(rows []interface{}) bool {
for _, rowInterface := range rows {
if row, ok := rowInterface.(map[string]interface{}); ok {
if GetBoolValue(row, "collapse") || GetBoolValue(row, "showTitle") || GetStringValue(row, "repeat") != "" {
return true
}
}
}
return false
}
func getRowHeight(row map[string]interface{}) float64 {
if height, ok := row["height"]; ok {
if h, ok := ConvertToFloat(height); ok {
return h
}
}
return defaultRowHeight
}
func getGridHeight(height float64) int {
if height < minPanelHeight {
height = minPanelHeight
}
return int(math.Ceil(height / panelHeightStep))
}
File diff suppressed because it is too large Load Diff
@@ -63,16 +63,9 @@ func migrateMinSpanToMaxPerRow(panel map[string]interface{}) {
return
}
// Convert minSpan to a number (could be int, float64, etc.)
var minSpan float64
switch v := minSpanValue.(type) {
case int:
minSpan = float64(v)
case float64:
minSpan = v
case int64:
minSpan = float64(v)
default:
// Convert minSpan to a number using shared utility
minSpan, ok := ConvertToFloat(minSpanValue)
if !ok {
// If we can't convert minSpan to a number, just delete it and return
delete(panel, "minSpan")
return
@@ -84,8 +84,8 @@ func upgradePanelLink(link map[string]interface{}) map[string]interface{} {
result := map[string]interface{}{
"url": url,
"title": getStringValue(link, "title"),
"targetBlank": getBoolValue(link, "targetBlank"),
"title": GetStringValue(link, "title"),
"targetBlank": GetBoolValue(link, "targetBlank"),
}
return result
@@ -111,11 +111,11 @@ func buildPanelLinkURL(link map[string]interface{}) string {
// Add query parameters
params := []string{}
if getBoolValue(link, "keepTime") {
if GetBoolValue(link, "keepTime") {
params = append(params, "$__url_time_range")
}
if getBoolValue(link, "includeVars") {
if GetBoolValue(link, "includeVars") {
params = append(params, "$__all_variables")
}
@@ -150,17 +150,3 @@ func slugifyForURL(name string) string {
name = reSpaces.ReplaceAllString(name, "-")
return name
}
func getStringValue(m map[string]interface{}, key string) string {
if v, ok := m[key].(string); ok {
return v
}
return ""
}
func getBoolValue(m map[string]interface{}, key string) bool {
if v, ok := m[key].(bool); ok {
return v
}
return false
}
@@ -117,7 +117,7 @@ func removeRepeatedPanels(panels []interface{}) []interface{} {
// Filter out repeats in collapsed rows
if p["type"] == "row" {
if nestedPanels, ok := p["panels"].([]interface{}); ok {
var filteredNestedPanels []interface{}
filteredNestedPanels := []interface{}{}
for _, nestedPanel := range nestedPanels {
if np, ok := nestedPanel.(map[string]interface{}); ok {
if _, hasRepeatPanelId := np["repeatPanelId"]; !hasRepeatPanelId {
@@ -0,0 +1,58 @@
{
"title": "V15 No-Op Migration Test Dashboard",
"schemaVersion": 14,
"panels": [
{
"type": "graph",
"title": "CPU Usage",
"id": 1,
"yAxes": [
{
"show": true,
"min": null,
"max": null
}
]
},
{
"type": "singlestat",
"title": "Memory Usage",
"id": 2,
"valueMaps": [
{
"op": "=",
"text": "N/A",
"value": "null"
}
]
}
],
"templating": {
"list": [
{
"name": "server",
"type": "query",
"datasource": "prometheus",
"query": "label_values(server)",
"refresh": 1,
"options": []
}
]
},
"annotations": {
"list": [
{
"name": "Annotations & Alerts",
"datasource": "grafana",
"enable": true
}
]
},
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {
"refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"]
}
}
@@ -0,0 +1,119 @@
{
"title": "V16 Grid Layout Migration Test Dashboard",
"schemaVersion": 15,
"rows": [
{
"collapse": false,
"height": 250,
"panels": [
{
"id": 1,
"type": "graph",
"title": "CPU Usage",
"span": 6
},
{
"id": 2,
"type": "singlestat",
"title": "Memory Usage",
"span": 6
}
]
},
{
"collapse": true,
"height": 300,
"title": "Collapsed Row",
"panels": [
{
"id": 3,
"type": "table",
"title": "Process List",
"span": 12
},
{
"id": 4,
"type": "graph",
"title": "Network I/O",
"span": 6,
"height": 200
},
{
"id": 5,
"type": "graph",
"title": "Disk I/O",
"span": 6,
"height": 200
}
]
},
{
"showTitle": true,
"title": "Visible Row Title",
"height": 200,
"panels": [
{
"id": 6,
"type": "gauge",
"title": "Temperature",
"span": 4,
"minSpan": 2
},
{
"id": 7,
"type": "stat",
"title": "Uptime",
"span": 4
},
{
"id": 8,
"type": "bargauge",
"title": "Load Average",
"span": 4
}
]
},
{
"height": 150,
"panels": [
{
"id": 9,
"type": "text",
"title": "Description Panel",
"span": 8
},
{
"id": 10,
"type": "logs",
"title": "System Logs",
"span": 4,
"height": 100
}
]
},
{
"repeat": "server",
"height": 250,
"panels": [
{
"id": 11,
"type": "graph",
"title": "Server Metrics",
"span": 12
}
]
},
{
"repeatIteration": true,
"height": 250,
"panels": [
{
"id": 12,
"type": "graph",
"title": "Should be skipped",
"span": 12
}
]
}
]
}
@@ -0,0 +1,145 @@
{
"annotations": {
"list": [
{
"datasource": {
"uid": "grafana"
},
"enable": true,
"name": "Annotations \u0026 Alerts"
}
]
},
"panels": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"id": 1,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "CPU Usage",
"type": "graph",
"yAxes": [
{
"max": null,
"min": null,
"show": true
}
]
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"fieldConfig": {
"defaults": {
"mappings": [
{
"options": {
"match": "null",
"result": {
"color": null,
"text": "N/A"
}
},
"type": "special"
}
],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"id": 2,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"pluginVersion": "1.0.0",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Memory Usage",
"type": "stat"
}
],
"refresh": "",
"schemaVersion": 41,
"templating": {
"list": [
{
"datasource": {
"uid": "prometheus"
},
"name": "server",
"options": [],
"query": "label_values(server)",
"refresh": 1,
"type": "query"
}
]
},
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
},
"title": "V15 No-Op Migration Test Dashboard"
}
@@ -0,0 +1,487 @@
{
"panels": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 1
},
"id": 1,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "CPU Usage",
"type": "graph"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"fieldConfig": {
"defaults": {
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 1
},
"id": 2,
"options": {
"colorMode": "none",
"graphMode": "none",
"justifyMode": "auto",
"orientation": "horizontal",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": [
"mean"
],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"pluginVersion": "1.0.0",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Memory Usage",
"type": "stat"
},
{
"collapsed": false,
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 7,
"w": 24,
"x": 0,
"y": 0
},
"id": 13,
"panels": [],
"repeat": "",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "",
"type": "row"
},
{
"collapsed": true,
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 8
},
"id": 14,
"panels": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 9
},
"id": 3,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Process List",
"type": "table"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 12,
"x": 0,
"y": 17
},
"height": 200,
"id": 4,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Network I/O",
"type": "graph"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 12,
"x": 12,
"y": 17
},
"height": 200,
"id": 5,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Disk I/O",
"type": "graph"
}
],
"repeat": "",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Collapsed Row",
"type": "row"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 8,
"x": 0,
"y": 18
},
"id": 6,
"maxPerRow": 6,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Temperature",
"type": "gauge"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 8,
"x": 8,
"y": 18
},
"id": 7,
"options": {
"justifyMode": "auto",
"percentChangeColorMode": "standard",
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Uptime",
"type": "stat"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 8,
"x": 16,
"y": 18
},
"id": 8,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Load Average",
"type": "bargauge"
},
{
"collapsed": false,
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 6,
"w": 24,
"x": 0,
"y": 17
},
"id": 15,
"panels": [],
"repeat": "",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Visible Row Title",
"type": "row"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 4,
"w": 16,
"x": 0,
"y": 25
},
"id": 9,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Description Panel",
"type": "text"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 3,
"w": 8,
"x": 16,
"y": 25
},
"height": 100,
"id": 10,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "System Logs",
"type": "logs"
},
{
"collapsed": false,
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 4,
"w": 24,
"x": 0,
"y": 24
},
"id": 16,
"panels": [],
"repeat": "",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "",
"type": "row"
},
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 7,
"w": 24,
"x": 0,
"y": 30
},
"id": 11,
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "Server Metrics",
"type": "graph"
},
{
"collapsed": false,
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"gridPos": {
"h": 7,
"w": 24,
"x": 0,
"y": 29
},
"id": 17,
"panels": [],
"repeat": "server",
"targets": [
{
"datasource": {
"apiVersion": "v1",
"type": "prometheus",
"uid": "default-ds-uid"
},
"refId": "A"
}
],
"title": "",
"type": "row"
}
],
"refresh": "",
"schemaVersion": 41,
"title": "V16 Grid Layout Migration Test Dashboard"
}
+4 -4
View File
@@ -47,11 +47,11 @@ require (
go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
+8 -8
View File
@@ -122,8 +122,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -132,14 +132,14 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+44 -1
View File
@@ -1,5 +1,7 @@
include ../sdk.mk
OPERATOR_DOCKERIMAGE := "github.com/grafana/grafana/apps/iam/operator"
.PHONY: generate
generate: install-app-sdk update-app-sdk ## Run Grafana App SDK code generation
@$(APP_SDK_BIN) generate \
@@ -8,4 +10,45 @@ generate: install-app-sdk update-app-sdk ## Run Grafana App SDK code generation
--grouping=group \
--defencoding=none \
--noschemasinmanifest \
--postprocess \
--postprocess
.PHONY: deps
deps:
@go mod tidy
@GOWORK=off go mod vendor
.PHONY: build
build: build/operator
.PHONY: build/operator
build/operator:
docker build -t $(OPERATOR_DOCKERIMAGE) -f cmd/operator/Dockerfile .
.PHONY: local/up
local/up:
@./local/scripts/cluster.sh create "local/k3d-config.json"
@cd local && tilt up
.PHONY: local/generate
local/generate:
@grafana-app-sdk project local generate
.PHONY: local/down
local/down:
@cd local && tilt down
.PHONY: local/deploy_plugin
local/deploy_plugin:
-tilt disable grafana
cp -R plugin/dist local/mounted-files/plugin/dist
-tilt enable grafana
.PHONY: local/push_operator
local/push_operator: build/operator
# Tag the docker image as part of localhost, which is what the generated k8s uses to avoid confusion with the real operator image
@docker tag "$(OPERATOR_DOCKERIMAGE):latest" "localhost/$(OPERATOR_DOCKERIMAGE):latest"
@./local/scripts/push_image.sh "localhost/$(OPERATOR_DOCKERIMAGE):latest"
.PHONY: local/clean
local/clean: local/down
@./local/scripts/cluster.sh delete
+16
View File
@@ -0,0 +1,16 @@
FROM golang:1.24-alpine AS builder
WORKDIR /build
COPY go.mod go.sum ./
COPY vendor* ./vendor
RUN test -f vendor/modules.txt || go mod download
COPY cmd cmd
COPY pkg pkg
RUN go build -o "target/operator" cmd/operator/*.go
FROM alpine AS runtime
COPY --from=builder /build/target/operator /usr/bin/operator
ENTRYPOINT ["/usr/bin/operator"]
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"fmt"
"net/http"
utilnet "k8s.io/apimachinery/pkg/util/net"
"github.com/grafana/authlib/authn"
)
type authRoundTripper struct {
tokenExchangeClient *authn.TokenExchangeClient
transport http.RoundTripper
}
func (t *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
tokenResponse, err := t.tokenExchangeClient.Exchange(req.Context(), authn.TokenExchangeRequest{
Audiences: []string{"folder.grafana.app"},
Namespace: "*",
})
if err != nil {
return nil, fmt.Errorf("failed to exchange token: %w", err)
}
// clone the request as RTs are not expected to mutate the passed request
req = utilnet.CloneRequest(req)
req.Header.Set("X-Access-Token", "Bearer "+tokenResponse.Token)
return t.transport.RoundTrip(req)
}
+120
View File
@@ -0,0 +1,120 @@
package main
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/grafana/grafana-app-sdk/plugin/kubeconfig"
"github.com/grafana/grafana-app-sdk/simple"
)
const (
ConnTypeGRPC = "grpc"
ConnTypeHTTP = "http"
)
type Config struct {
OTelConfig simple.OpenTelemetryConfig
WebhookServer WebhookServerConfig
KubeConfig *kubeconfig.NamespacedConfig
ZanzanaClient ZanzanaClientConfig
FolderReconciler FolderReconcilerConfig
}
type WebhookServerConfig struct {
Port int
TLSCertPath string
TLSKeyPath string
}
type ZanzanaClientConfig struct {
Addr string
}
type FolderReconcilerConfig struct {
Namespace string
}
func LoadConfigFromEnv() (*Config, error) {
cfg := Config{}
cfg.OTelConfig.ServiceName = os.Getenv("OTEL_SERVICE_NAME")
switch strings.ToLower(os.Getenv("OTEL_CONN_TYPE")) {
case ConnTypeGRPC:
cfg.OTelConfig.ConnType = ConnTypeGRPC
case ConnTypeHTTP:
cfg.OTelConfig.ConnType = ConnTypeHTTP
case "":
// Default
cfg.OTelConfig.ConnType = ConnTypeHTTP
default:
return nil, fmt.Errorf("unknown OTEL_CONN_TYPE '%s'", os.Getenv("OTEL_CONN_TYPE"))
}
cfg.OTelConfig.Host = os.Getenv("OTEL_HOST")
portStr := os.Getenv("OTEL_PORT")
if portStr == "" {
if cfg.OTelConfig.ConnType == ConnTypeGRPC {
// Default OTel GRPC port
cfg.OTelConfig.Port = 4317
} else {
// Default OTel HTTP port
cfg.OTelConfig.Port = 4318
}
} else {
var err error
cfg.OTelConfig.Port, err = strconv.Atoi(portStr)
if err != nil {
return nil, fmt.Errorf("invalid OTEL_PORT '%s': %w", portStr, err)
}
}
whPortStr := os.Getenv("WEBHOOK_PORT")
if whPortStr == "" {
cfg.WebhookServer.Port = 8443
} else {
var err error
cfg.WebhookServer.Port, err = strconv.Atoi(whPortStr)
if err != nil {
return nil, fmt.Errorf("invalid WEBHOOK_PORT '%s': %w", whPortStr, err)
}
}
cfg.WebhookServer.TLSCertPath = os.Getenv("WEBHOOK_CERT_PATH")
cfg.WebhookServer.TLSKeyPath = os.Getenv("WEBHOOK_KEY_PATH")
// Load the kube config
kubeConfigFile := os.Getenv("KUBE_CONFIG_FILE")
if kubeConfigFile != "" {
kubeConfig, err := LoadKubeConfigFromFile(kubeConfigFile)
if err != nil {
return nil, fmt.Errorf("unable to load kubernetes configuration from file '%s': %w", kubeConfigFile, err)
}
cfg.KubeConfig = kubeConfig
} else if folderAppURL := os.Getenv("FOLDER_APP_URL"); folderAppURL != "" {
exchangeUrl := os.Getenv("AUTH_TOKEN_EXCHANGE_URL")
authToken := os.Getenv("AUTH_TOKEN")
namespace := os.Getenv("FOLDER_APP_NAMESPACE")
if exchangeUrl == "" || authToken == "" {
return nil, fmt.Errorf("AUTH_TOKEN_EXCHANGE_URL and AUTH_TOKEN must be set when FOLDER_APP_URL is set")
}
kubeConfig, err := LoadKubeConfigFromFolderAppURL(folderAppURL, exchangeUrl, authToken, namespace)
if err != nil {
return nil, fmt.Errorf("unable to load kubernetes configuration from folder app URL '%s': %w", folderAppURL, err)
}
cfg.KubeConfig = kubeConfig
} else {
kubeConfig, err := LoadInClusterConfig()
if err != nil {
return nil, fmt.Errorf("unable to load in-cluster kubernetes configuration: %w", err)
}
cfg.KubeConfig = kubeConfig
}
cfg.ZanzanaClient.Addr = os.Getenv("ZANZANA_ADDR")
cfg.FolderReconciler.Namespace = os.Getenv("FOLDER_RECONCILER_NAMESPACE")
return &cfg, nil
}
+85
View File
@@ -0,0 +1,85 @@
package main
import (
"fmt"
"net/http"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/transport"
"github.com/grafana/authlib/authn"
"github.com/grafana/grafana-app-sdk/plugin/kubeconfig"
)
// LoadInClusterConfig loads a kubernetes in-cluster config.
// Since the in-cluster config doesn't have a namespace, it defaults to "default"
func LoadInClusterConfig() (*kubeconfig.NamespacedConfig, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
cfg.APIPath = "/apis"
return &kubeconfig.NamespacedConfig{
RestConfig: *cfg,
Namespace: "default",
}, nil
}
// LoadKubeConfigFromEnv loads a NamespacedConfig from the value of an environment variable
func LoadKubeConfigFromFolderAppURL(folderAppURL, exchangeUrl, authToken, namespace string) (*kubeconfig.NamespacedConfig, error) {
tokenExchangeClient, err := authn.NewTokenExchangeClient(authn.TokenExchangeConfig{
TokenExchangeURL: exchangeUrl,
Token: authToken,
})
if err != nil {
return nil, fmt.Errorf("failed to create token exchange client: %w", err)
}
return &kubeconfig.NamespacedConfig{
RestConfig: rest.Config{
APIPath: "/apis",
Host: folderAppURL,
WrapTransport: transport.WrapperFunc(func(rt http.RoundTripper) http.RoundTripper {
return &authRoundTripper{
tokenExchangeClient: tokenExchangeClient,
transport: rt,
}
}),
TLSClientConfig: rest.TLSClientConfig{
Insecure: true,
},
},
Namespace: namespace,
}, nil
}
// LoadKubeConfigFromFile loads a NamespacedConfig from a file on-disk (such as a mounted secret)
func LoadKubeConfigFromFile(configPath string) (*kubeconfig.NamespacedConfig, error) {
// Load the kubeconfig file
config, err := clientcmd.LoadFromFile(configPath)
if err != nil {
return nil, fmt.Errorf("failed to load kubeconfig from %s: %w", configPath, err)
}
// Build the REST config from the kubeconfig
restConfig, err := clientcmd.NewDefaultClientConfig(*config, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
return nil, fmt.Errorf("failed to create REST config: %w", err)
}
// Get the namespace from the current context, default to "default" if not set
namespace := "default"
if config.CurrentContext != "" {
if context, exists := config.Contexts[config.CurrentContext]; exists && context.Namespace != "" {
namespace = context.Namespace
}
}
restConfig.APIPath = "/apis"
return &kubeconfig.NamespacedConfig{
RestConfig: *restConfig,
Namespace: namespace,
}, nil
}
+82
View File
@@ -0,0 +1,82 @@
package main
import (
"context"
"log/slog"
"os"
"os/signal"
"github.com/grafana/grafana-app-sdk/k8s"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/operator"
"github.com/grafana/grafana-app-sdk/simple"
"github.com/grafana/grafana/apps/iam/pkg/app"
)
func main() {
// Configure the default logger to use slog
logging.DefaultLogger = logging.NewSLogLogger(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelDebug,
}))
//Load the config from the environment
cfg, err := LoadConfigFromEnv()
if err != nil {
logging.DefaultLogger.With("error", err).Error("Unable to load config from environment")
panic(err)
}
// Set up tracing
if cfg.OTelConfig.Host != "" {
err = simple.SetTraceProvider(simple.OpenTelemetryConfig{
Host: cfg.OTelConfig.Host,
Port: cfg.OTelConfig.Port,
ConnType: cfg.OTelConfig.ConnType,
ServiceName: cfg.OTelConfig.ServiceName,
})
if err != nil {
logging.DefaultLogger.With("error", err).Error("Unable to set trace provider")
panic(err)
}
}
// Create the operator config and the runner
operatorConfig := operator.RunnerConfig{
KubeConfig: cfg.KubeConfig.RestConfig,
WebhookConfig: operator.RunnerWebhookConfig{
Port: cfg.WebhookServer.Port,
TLSConfig: k8s.TLSConfig{
CertPath: cfg.WebhookServer.TLSCertPath,
KeyPath: cfg.WebhookServer.TLSKeyPath,
},
},
MetricsConfig: operator.RunnerMetricsConfig{
Enabled: true,
},
}
runner, err := operator.NewRunner(operatorConfig)
if err != nil {
logging.DefaultLogger.With("error", err).Error("Unable to create operator runner")
panic(err)
}
// Context and cancel for the operator's Run method
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
// Create app config from operator config
appCfg := app.AppConfig{
ZanzanaAddr: cfg.ZanzanaClient.Addr,
FolderReconcilerNamespace: cfg.FolderReconciler.Namespace,
}
// Run
logging.DefaultLogger.Info("Starting operator")
err = runner.Run(ctx, app.Provider(appCfg))
if err != nil {
logging.DefaultLogger.With("error", err).Error("Operator exited with error")
panic(err)
}
logging.DefaultLogger.Info("Normal operator exit")
}
+295 -8
View File
@@ -2,65 +2,352 @@ module github.com/grafana/grafana/apps/iam
go 1.24.6
replace github.com/grafana/grafana => ../../
replace github.com/grafana/grafana/apps/folder => ../folder
replace github.com/grafana/grafana/apps/dashboard => ../dashboard
replace github.com/grafana/grafana/apps/secret => ../secret
replace github.com/grafana/grafana/apps/provisioning => ../provisioning
replace github.com/grafana/grafana/pkg/apimachinery => ../../pkg/apimachinery
replace github.com/grafana/grafana/pkg/apiserver => ../../pkg/apiserver
replace github.com/grafana/grafana/pkg/aggregator => ../../pkg/aggregator
replace github.com/prometheus/alertmanager => github.com/grafana/prometheus-alertmanager v0.25.1-0.20250620093340-be61a673dee6
require (
github.com/grafana/authlib v0.0.0-20250710201142-9542f2f28d43
github.com/grafana/grafana v0.0.0-00010101000000-000000000000
github.com/grafana/grafana-app-sdk v0.40.3
github.com/grafana/grafana/pkg/apimachinery v0.0.0-20250514132646-acbc7b54ed9e
github.com/grafana/grafana-app-sdk/logging v0.40.2
github.com/grafana/grafana-app-sdk/plugin v0.40.3
github.com/grafana/grafana/apps/folder v0.0.0
github.com/grafana/grafana/pkg/apimachinery v0.0.0
google.golang.org/grpc v1.74.2
k8s.io/apimachinery v0.33.3
k8s.io/client-go v0.33.3
k8s.io/kube-openapi v0.0.0-20250318190949-c8a335a9a2ff
)
require (
cel.dev/expr v0.24.0 // indirect
cloud.google.com/go/compute/metadata v0.7.0 // indirect
cuelang.org/go v0.11.1 // indirect
dario.cat/mergo v1.0.1 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/BurntSushi/toml v1.5.0 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.4.0 // indirect
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
github.com/Masterminds/squirrel v1.5.4 // indirect
github.com/ProtonMail/go-crypto v1.1.6 // indirect
github.com/VividCortex/mysqlerr v0.0.0-20170204212430-6c6b55f8796f // indirect
github.com/Yiling-J/theine-go v0.6.1 // indirect
github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/arrow-go/v18 v18.3.0 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/at-wat/mqtt-go v0.19.4 // indirect
github.com/aws/aws-sdk-go v1.55.7 // indirect
github.com/aws/aws-sdk-go-v2 v1.36.5 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.17.70 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.36 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.36 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.4 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.17 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.34.0 // indirect
github.com/aws/smithy-go v1.22.4 // indirect
github.com/barkimedes/go-deepcopy v0.0.0-20220514131651-17c30cfc62df // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/blang/semver v3.5.1+incompatible // indirect
github.com/blang/semver/v4 v4.0.0 // indirect
github.com/bluele/gcache v0.0.2 // indirect
github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874 // indirect
github.com/bufbuild/protocompile v0.4.0 // indirect
github.com/bwmarrin/snowflake v0.3.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cenkalti/backoff/v5 v5.0.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cheekybits/genny v1.0.0 // indirect
github.com/chromedp/cdproto v0.0.0-20250429231605-6ed5b53462d4 // indirect
github.com/cloudflare/circl v1.6.1 // indirect
github.com/cockroachdb/apd/v3 v3.2.1 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/diegoholiveira/jsonlogic/v3 v3.7.4 // indirect
github.com/dlmiddlecote/sqlstats v1.0.2 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2 // indirect
github.com/dolthub/go-icu-regex v0.0.0-20250327004329-6799764f2dad // indirect
github.com/dolthub/go-mysql-server v0.19.1-0.20250410182021-5632d67cd46e // indirect
github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 // indirect
github.com/dolthub/vitess v0.0.0-20250410090211-143e6b272ad4 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/elazarl/goproxy v1.7.2 // indirect
github.com/emicklei/go-restful/v3 v3.12.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/fullstorydev/grpchan v1.1.1 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/gchaincl/sqlhooks v1.3.0 // indirect
github.com/getkin/kin-openapi v0.132.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/analysis v0.23.0 // indirect
github.com/go-openapi/errors v0.22.0 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.21.0 // indirect
github.com/go-openapi/loads v0.22.0 // indirect
github.com/go-openapi/runtime v0.28.0 // indirect
github.com/go-openapi/spec v0.21.0 // indirect
github.com/go-openapi/strfmt v0.23.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-test/deep v1.1.1 // indirect
github.com/go-openapi/validate v0.24.0 // indirect
github.com/go-sql-driver/mysql v1.9.3 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/go-viper/mapstructure/v2 v2.3.0 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/gofrs/uuid v4.4.0+incompatible // indirect
github.com/gogo/googleapis v1.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/gogo/status v1.1.1 // indirect
github.com/golang-migrate/migrate/v4 v4.7.0 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/cel-go v0.25.0 // indirect
github.com/google/flatbuffers v25.2.10+incompatible // indirect
github.com/google/gnostic-models v0.6.9 // indirect
github.com/grafana/grafana-app-sdk/logging v0.40.2 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/google/wire v0.6.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/grafana/alerting v0.0.0-20250812203446-a38b2187d4e1 // indirect
github.com/grafana/authlib/types v0.0.0-20250710201142-9542f2f28d43 // indirect
github.com/grafana/dataplane/sdata v0.0.9 // indirect
github.com/grafana/dskit v0.0.0-20250611075409-46f51e1ce914 // indirect
github.com/grafana/grafana-aws-sdk v1.1.0 // indirect
github.com/grafana/grafana-azure-sdk-go/v2 v2.2.0 // indirect
github.com/grafana/grafana-plugin-sdk-go v0.278.0 // indirect
github.com/grafana/grafana/apps/dashboard v0.0.0 // indirect
github.com/grafana/grafana/pkg/apiserver v0.0.0 // indirect
github.com/grafana/otel-profiling-go v0.5.1 // indirect
github.com/grafana/pyroscope-go/godeltaprof v0.1.8 // indirect
github.com/grafana/sqlds/v4 v4.2.4 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-metrics v0.5.4 // indirect
github.com/hashicorp/go-msgpack/v2 v2.1.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-plugin v1.6.3 // indirect
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hashicorp/memberlist v0.5.2 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.5 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jaegertracing/jaeger-idl v0.5.0 // indirect
github.com/jessevdk/go-flags v1.6.1 // indirect
github.com/jhump/protoreflect v1.15.1 // indirect
github.com/jmespath-community/go-jmespath v1.1.1 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/jszwedko/go-datemath v0.1.1-0.20230526204004-640a500621d6 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/lestrrat-go/strftime v1.0.4 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/magefile/mage v1.15.0 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
github.com/mattetti/filebuffer v1.0.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mdlayher/socket v0.4.1 // indirect
github.com/mdlayher/vsock v1.2.1 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/miekg/dns v1.1.63 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.1-0.20231216201459-8508981c8b6c // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/mithrandie/csvq v1.18.1 // indirect
github.com/mithrandie/csvq-driver v1.7.0 // indirect
github.com/mithrandie/go-file/v2 v2.1.0 // indirect
github.com/mithrandie/go-text v1.6.0 // indirect
github.com/mithrandie/ternary v1.1.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect
github.com/natefinch/wrap v0.2.0 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/nikunjy/rules v1.5.0 // indirect
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/oklog/ulid v1.3.1 // indirect
github.com/oklog/ulid/v2 v2.1.0 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/open-feature/go-sdk v1.14.1 // indirect
github.com/open-feature/go-sdk-contrib/providers/go-feature-flag v0.2.3 // indirect
github.com/open-feature/go-sdk-contrib/providers/ofrep v0.1.5 // indirect
github.com/openfga/api/proto v0.0.0-20250127102726-f9709139a369 // indirect
github.com/openfga/language/pkg/go v0.2.0-beta.2.0.20250220223040-ed0cfba54336 // indirect
github.com/openfga/openfga v1.8.13 // indirect
github.com/opentracing-contrib/go-stdlib v1.0.0 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/perimeterx/marshmallow v1.1.5 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pressly/goose/v3 v3.24.3 // indirect
github.com/prometheus/alertmanager v0.28.0 // indirect
github.com/prometheus/client_golang v1.23.0 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.65.0 // indirect
github.com/prometheus/common/sigv4 v0.1.0 // indirect
github.com/prometheus/exporter-toolkit v0.14.0 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/puzpuzpuz/xsync/v2 v2.5.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rs/cors v1.11.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c // indirect
github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.12.0 // indirect
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/pflag v1.0.7 // indirect
github.com/spf13/viper v1.20.1 // indirect
github.com/stoewer/go-strcase v1.3.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/stretchr/testify v1.10.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tetratelabs/wazero v1.8.2 // indirect
github.com/thomaspoignant/go-feature-flag v1.42.0 // indirect
github.com/tjhop/slog-gokit v0.1.3 // indirect
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
github.com/unknwon/bra v0.0.0-20200517080246-1e3013ecaff8 // indirect
github.com/unknwon/com v1.0.1 // indirect
github.com/unknwon/log v0.0.0-20200308114134-929b1006e34a // indirect
github.com/urfave/cli v1.22.16 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/zeebo/xxh3 v1.0.2 // indirect
go.mongodb.org/mongo-driver v1.17.3 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/bridges/prometheus v0.61.0 // indirect
go.opentelemetry.io/contrib/exporters/autoexport v0.61.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.61.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 // indirect
go.opentelemetry.io/contrib/propagators/jaeger v1.36.0 // indirect
go.opentelemetry.io/contrib/samplers/jaegerremote v0.30.0 // indirect
go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.12.2 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.12.2 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.37.0 // indirect
go.opentelemetry.io/otel/exporters/prometheus v0.59.0 // indirect
go.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.12.2 // indirect
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 // indirect
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.37.0 // indirect
go.opentelemetry.io/otel/log v0.12.2 // indirect
go.opentelemetry.io/otel/metric v1.37.0 // indirect
go.opentelemetry.io/otel/sdk v1.37.0 // indirect
go.opentelemetry.io/otel/sdk/log v0.12.2 // indirect
go.opentelemetry.io/otel/sdk/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/mock v0.5.2 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // indirect
golang.org/x/mod v0.27.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
gonum.org/v1/gonum v0.16.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/fsnotify/fsnotify.v1 v1.4.7 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/mail.v2 v2.3.1 // indirect
gopkg.in/src-d/go-errors.v1 v1.0.0 // indirect
gopkg.in/telebot.v3 v3.2.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/client-go v0.33.3 // indirect
k8s.io/api v0.33.3 // indirect
k8s.io/apiextensions-apiserver v0.33.3 // indirect
k8s.io/apiserver v0.33.3 // indirect
k8s.io/component-base v0.33.3 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/utils v0.0.0-20241210054802-24370beab758 // indirect
modernc.org/libc v1.65.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.10.0 // indirect
modernc.org/sqlite v1.37.0 // indirect
sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
sigs.k8s.io/randfill v1.0.0 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.7.0 // indirect
sigs.k8s.io/yaml v1.5.0 // indirect
xorm.io/builder v0.3.6 // indirect
)
+1844 -10
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -10,7 +10,7 @@ manifest: {
v0alpha1: {
kinds: [
globalrolev0alpha1,
globalrolev0alpha1,
globalrolebindingv0alpha1,
corerolev0alpha1,
rolev0alpha1,
@@ -21,4 +21,4 @@ v0alpha1: {
teambindingv0alpha1,
serviceaccountv0alpha1,
]
}
}
+57
View File
@@ -0,0 +1,57 @@
# version_settings() enforces a minimum Tilt version
# https://docs.tilt.dev/api.html#api.version_settings
version_settings(constraint='>=0.22.2')
def name(c):
return c['metadata']['name']
def namespace(c):
if 'namespace' in c['metadata']:
return c['metadata']['namespace']
return ''
def decode(yaml):
resources = decode_yaml_stream(yaml)
# workaround a bug in decode_yaml_stream where it returns duplicates
# This bug has been fixed in Tilt v0.17.3+
filtered = []
names = {}
for r in resources:
if r == None:
continue
n = '%s:%s:%s' % (name(r), r['kind'], namespace(r))
if n in names:
continue
names[n] = True
filtered.append(r)
return filtered
def find_overlapping(o, yamls):
for elem in yamls:
if name(o) == name(elem) and o['kind'] == elem['kind'] and namespace(o) == namespace(elem):
return elem
return None
yaml_objects = []
# Parse all YAML files in our "yamls" directory
for filename in listdir('yamls'):
if filename.lower().endswith(('.yaml', '.yml')):
decoded = decode(read_file(filename))
for o in decoded:
present = find_overlapping(o, yaml_objects)
if present != None:
print("Overlapping resource found: %s", filename)
exit(1)
yaml_objects += decoded
bundle = encode_yaml_stream(yaml_objects)
# k8s_yaml automatically creates resources in Tilt for the entities
# and will inject any images referenced in the Tiltfile when deploying
# https://docs.tilt.dev/api.html#api.k8s_yaml
k8s_yaml(bundle)
+16
View File
@@ -0,0 +1,16 @@
{
"apiVersion": "k3d.io/v1alpha3",
"kind": "Simple",
"kubeAPI": {
"hostPort": "8556"
},
"options": {
"k3d": {
"wait": true
},
"kubeconfig": {
"switchCurrentContext": true,
"updateDefaultKubeconfig": true
}
}
}
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env bash
set -eufo pipefail
CLUSTER_NAME="grafana-iam-operator"
create_cluster() {
K3D_CONFIG="${1:-k3d-config.json}"
if ! k3d cluster list "${CLUSTER_NAME}" >/dev/null 2>&1; then
# Array of extra options to add to the k3d cluster create command
EXTRA_K3D_OPTS=()
# Bug in k3d for btrfs filesystems workaround, see https://k3d.io/v5.2.2/faq/faq/#issues-with-btrfs
# Apple is APFS/HFS and stat has a different API, so we might as well skip that
if [[ "${OSTYPE}" != "darwin*" ]]; then
ROOTFS="$(stat -f --format="%T" "/")"
if [[ "${ROOTFS}" == "btrfs" ]]; then
EXTRA_K3D_OPTS+=("-v" "/dev/mapper:/dev/mapper")
fi
fi
k3d cluster create "${CLUSTER_NAME}" --config "${K3D_CONFIG}" ${EXTRA_K3D_OPTS[@]+"${EXTRA_K3D_OPTS[@]}"}
else
echo "Cluster already exists"
fi
}
delete_cluster() {
k3d cluster delete "${CLUSTER_NAME}"
}
if [ $# -lt 1 ]; then
echo "Usage: ./cluster.sh [create|delete]"
exit 1
fi
if [ $1 == "create" ]; then
create_cluster $2
elif [ $1 == "delete" ]; then
delete_cluster
else
echo "Unknown argument ${1}"
fi
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -eufo pipefail
CLUSTER_NAME="grafana-iam-operator"
IMAGE="$1"
if [[ "$IMAGE" == "" ]]; then
echo "usage: push_image.sh <image_name:tag>"
exit 1
fi
k3d image import "${IMAGE}" -c "${CLUSTER_NAME}"
+45
View File
@@ -0,0 +1,45 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: operator
namespace: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: iam-app-operator
namespace: default
spec:
minReadySeconds: 10
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
name: iam-app-operator
template:
metadata:
labels:
name: iam-app-operator
spec:
serviceAccount: operator
containers:
- image: localhost/github.com/grafana/grafana/apps/iam/operator:latest
imagePullPolicy: IfNotPresent
name: iam-app-operator
command: ["/bin/sh"]
args:
- -c
- exec /usr/bin/operator
env:
- name: ZANZANA_ADDR
value: zanzana.default.svc.cluster.local:50051
- name: FOLDER_APP_URL
value: https://host.docker.internal:6446
- name: AUTH_TOKEN_EXCHANGE_URL
value: http://host.docker.internal:8080/v1/sign-access-token
- name: AUTH_TOKEN
value: ""
- name: FOLDER_APP_NAMESPACE
value: "grafana-folder"
- name: FOLDER_RECONCILER_NAMESPACE
value: "default"
+177
View File
@@ -0,0 +1,177 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:15.7
env:
- name: POSTGRES_USER
value: grafana
- name: POSTGRES_PASSWORD
value: password
- name: POSTGRES_DB
value: grafana
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
ports:
- containerPort: 5432
name: postgres
volumeMounts:
- name: postgres-storage
mountPath: /var/lib/postgresql/data
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
readinessProbe:
exec:
command:
- /bin/sh
- -c
- pg_isready -U $POSTGRES_USER -d $POSTGRES_DB
initialDelaySeconds: 15
periodSeconds: 5
livenessProbe:
exec:
command:
- /bin/sh
- -c
- pg_isready -U $POSTGRES_USER -d $POSTGRES_DB
initialDelaySeconds: 30
periodSeconds: 10
volumes:
- name: postgres-storage
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: default
spec:
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
name: postgres
type: ClusterIP
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: zanzana
namespace: default
---
apiVersion: v1
kind: ConfigMap
metadata:
name: zanzana-config
namespace: default
labels:
name: zanzana
data:
grafana.ini: |
app_mode = development
target = zanzana-server
[log]
level = info
[database]
type = postgres
host = postgres.default.svc:5432
name = grafana
user = grafana
password = password
[feature_toggles]
zanzana = true
authZGRPCServer = true
[zanzana.server]
allow_insecure = true
check_query_cache = true
http_addr = 0.0.0.0:8080
[grpc_server]
enabled = true
address = 0.0.0.0:50051
enable_logging = true
---
apiVersion: v1
kind: Service
metadata:
name: zanzana
namespace: default
labels:
name: zanzana
spec:
ports:
- name: http
port: 8080
targetPort: 8080
- name: grpc
port: 50051
targetPort: 50051
selector:
name: zanzana
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: zanzana
namespace: default
spec:
minReadySeconds: 10
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
name: zanzana
template:
metadata:
labels:
name: zanzana
spec:
containers:
- command:
- grafana-server
- target
- --config=/etc/grafana-config/grafana.ini
- --homepath=/usr/share/grafana
env:
- name: GF_PATHS_CONFIG
value: /etc/grafana-config/grafana.ini
image: grafana/grafana-oss-dev:12.2.0-257970
imagePullPolicy: IfNotPresent
name: zanzana
volumeMounts:
- mountPath: /etc/grafana-config
name: zanzana-config
- mountPath: /var/lib/grafana
name: zanzana-storage
serviceAccount: zanzana
volumes:
- configMap:
name: zanzana-config
name: zanzana-config
- emptyDir: {}
name: zanzana-storage
---
+63
View File
@@ -0,0 +1,63 @@
package app
import (
"context"
"fmt"
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/simple"
foldersKind "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1"
"github.com/grafana/grafana/apps/iam/pkg/reconcilers"
)
type AppConfig = reconcilers.AppConfig
var appManifestData = app.ManifestData{
AppName: "iam-folder-reconciler",
Group: "iam.grafana.app",
}
func Provider(appCfg AppConfig) app.Provider {
return simple.NewAppProvider(app.NewEmbeddedManifest(appManifestData), appCfg, New)
}
func New(cfg app.Config) (app.App, error) {
folderReconciler, err := reconcilers.NewFolderReconciler(cfg)
if err != nil {
return nil, fmt.Errorf("unable to create FolderReconciler: %w", err)
}
logging.DefaultLogger.Info("FolderReconciler created")
config := simple.AppConfig{
Name: cfg.ManifestData.AppName,
KubeConfig: cfg.KubeConfig,
InformerConfig: simple.AppInformerConfig{
ErrorHandler: func(ctx context.Context, err error) {
// FIXME: add your own error handling here
logging.FromContext(ctx).With("error", err).Error("Informer processing error")
},
},
UnmanagedKinds: []simple.AppUnmanagedKind{
{
Kind: foldersKind.FolderKind(),
Reconciler: folderReconciler,
ReconcileOptions: simple.BasicReconcileOptions{
Namespace: cfg.SpecificConfig.(AppConfig).FolderReconcilerNamespace,
},
},
},
}
// Create the App
a, err := simple.NewApp(config)
if err != nil {
return nil, err
}
// Validate the capabilities against the provided manifest to make sure there isn't a mismatch
err = a.ValidateManifest(cfg.ManifestData)
return a, err
}
@@ -0,0 +1,173 @@
package reconcilers
import (
"context"
"fmt"
"time"
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/operator"
foldersKind "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1"
"github.com/grafana/grafana/pkg/services/authz/zanzana"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// FolderStore interface for retrieving folder information
type FolderStore interface {
GetFolderParent(ctx context.Context, namespace, uid string) (string, error)
}
// PermissionStore interface for managing folder permissions
type PermissionStore interface {
GetFolderParents(ctx context.Context, namespace, folderUID string) ([]string, error)
SetFolderParent(ctx context.Context, namespace, folderUID, parentUID string) error
DeleteFolderParents(ctx context.Context, namespace, folderUID string) error
}
// AppConfig represents the app-specific configuration
type AppConfig struct {
ZanzanaAddr string
FolderReconcilerNamespace string
}
type FolderReconciler struct {
permissionStore PermissionStore
folderStore FolderStore
}
func NewFolderReconciler(cfg app.Config) (operator.Reconciler, error) {
// Extract Zanzana address from config
appCfg, ok := cfg.SpecificConfig.(AppConfig)
if !ok {
return nil, fmt.Errorf("invalid config type: expected AppConfig, got %T", cfg.SpecificConfig)
}
// Create Zanzana client
zanzanaClient, err := getZanzanaClient(appCfg.ZanzanaAddr)
if err != nil {
return nil, fmt.Errorf("unable to create zanzana client: %w", err)
}
// Create dependencies
folderStore := NewAPIFolderStore(&cfg.KubeConfig)
permissionStore := NewZanzanaPermissionStore(zanzanaClient)
folderReconciler := &FolderReconciler{
permissionStore: permissionStore,
folderStore: folderStore,
}
reconciler := &operator.TypedReconciler[*foldersKind.Folder]{
ReconcileFunc: folderReconciler.reconcile,
}
return reconciler, nil
}
func getZanzanaClient(addr string) (zanzana.Client, error) {
transportCredentials := insecure.NewCredentials()
dialOptions := []grpc.DialOption{
grpc.WithTransportCredentials(transportCredentials),
}
conn, err := grpc.NewClient(addr, dialOptions...)
if err != nil {
return nil, fmt.Errorf("failed to create zanzana client to remote server: %w", err)
}
client, err := zanzana.NewClient(conn)
if err != nil {
return nil, fmt.Errorf("failed to initialize zanzana client: %w", err)
}
return client, nil
}
func (r *FolderReconciler) reconcile(ctx context.Context, req operator.TypedReconcileRequest[*foldersKind.Folder]) (operator.ReconcileResult, error) {
// Add timeout to prevent hanging operations
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
logger := logging.FromContext(ctx)
logger.Info("Reconciling request", "req", req)
err := validateFolder(req.Object)
if err != nil {
return operator.ReconcileResult{}, err
}
switch req.Action {
case operator.ReconcileActionCreated:
return r.handleUpdateFolder(ctx, req.Object)
case operator.ReconcileActionUpdated:
return r.handleUpdateFolder(ctx, req.Object)
case operator.ReconcileActionDeleted:
return r.handleDeleteFolder(ctx, req.Object)
default:
return operator.ReconcileResult{}, nil
}
}
func (r *FolderReconciler) handleUpdateFolder(ctx context.Context, folder *foldersKind.Folder) (operator.ReconcileResult, error) {
logger := logging.FromContext(ctx)
folderUID := folder.Name
namespace := folder.Namespace
parentUID, err := r.folderStore.GetFolderParent(ctx, namespace, folderUID)
if err != nil {
return operator.ReconcileResult{}, err
}
parents, err := r.permissionStore.GetFolderParents(ctx, namespace, folderUID)
if err != nil {
return operator.ReconcileResult{}, err
}
if (len(parents) == 0 && parentUID == "") || (len(parents) == 1 && parents[0] == parentUID) {
// Folder is already reconciled
logger.Info("Folder is already reconciled", "folder", folderUID, "parent", parentUID, "namespace", namespace)
return operator.ReconcileResult{}, nil
}
err = r.permissionStore.SetFolderParent(ctx, namespace, folderUID, parentUID)
if err != nil {
return operator.ReconcileResult{}, err
}
logger.Info("Folder parent set in permission store", "folder", folderUID, "parent", parentUID, "namespace", namespace)
return operator.ReconcileResult{}, nil
}
func (r *FolderReconciler) handleDeleteFolder(ctx context.Context, folder *foldersKind.Folder) (operator.ReconcileResult, error) {
logger := logging.FromContext(ctx)
namespace := folder.Namespace
folderUID := folder.Name
err := r.permissionStore.DeleteFolderParents(ctx, namespace, folderUID)
if err != nil {
return operator.ReconcileResult{}, err
}
logger.Info("Folder deleted from permission store", "folder", folderUID, "namespace", namespace)
return operator.ReconcileResult{}, nil
}
func validateFolder(folder *foldersKind.Folder) error {
if folder == nil {
return fmt.Errorf("folder is nil")
}
if folder.Name == "" {
return fmt.Errorf("folder UID (ObjectMeta.Name) is empty")
}
if folder.Namespace == "" {
return fmt.Errorf("folder namespace is empty")
}
return nil
}
@@ -0,0 +1,50 @@
package reconcilers
import (
"context"
"fmt"
foldersKind "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1"
"github.com/grafana/grafana/pkg/apimachinery/utils"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
var _ FolderStore = (*APIFolderStore)(nil)
func NewAPIFolderStore(config *rest.Config) FolderStore {
return &APIFolderStore{config}
}
type APIFolderStore struct {
config *rest.Config
}
func (s *APIFolderStore) GetFolderParent(ctx context.Context, namespace, uid string) (string, error) {
client, err := s.client(namespace)
if err != nil {
return "", fmt.Errorf("create resource client: %w", err)
}
// Get the folder by UID
unstructuredObj, err := client.Get(ctx, uid, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("get folder %s: %w", uid, err)
}
object, err := utils.MetaAccessor(unstructuredObj)
if err != nil {
return "", fmt.Errorf("get meta accessor: %w", err)
}
return object.GetFolder(), nil
}
func (s *APIFolderStore) client(namespace string) (dynamic.ResourceInterface, error) {
client, err := dynamic.NewForConfig(s.config)
if err != nil {
return nil, err
}
return client.Resource(foldersKind.FolderResourceInfo.GroupVersionResource()).Namespace(namespace), nil
}
+163
View File
@@ -0,0 +1,163 @@
package reconcilers
import (
"context"
"fmt"
"strings"
authzextv1 "github.com/grafana/grafana/pkg/services/authz/proto/v1"
"github.com/grafana/grafana/pkg/services/authz/zanzana"
)
type ZanzanaPermissionStore struct {
zanzanaClient zanzana.Client
}
var _ PermissionStore = (*ZanzanaPermissionStore)(nil)
func NewZanzanaPermissionStore(zanzanaClient zanzana.Client) PermissionStore {
return &ZanzanaPermissionStore{zanzanaClient}
}
func (c *ZanzanaPermissionStore) SetFolderParent(ctx context.Context, namespace, folderUID, parentUID string) error {
err := c.DeleteFolderParents(ctx, namespace, folderUID)
if err != nil {
return err
}
user, err := toFolderTuple(parentUID)
if err != nil {
return err
}
object, err := toFolderTuple(folderUID)
if err != nil {
return err
}
if err := c.zanzanaClient.Write(ctx, &authzextv1.WriteRequest{
Namespace: namespace,
Writes: &authzextv1.WriteRequestWrites{
TupleKeys: []*authzextv1.TupleKey{{
User: user,
Relation: zanzana.RelationParent,
Object: object,
}},
},
}); err != nil {
return err
}
return nil
}
func (c *ZanzanaPermissionStore) GetFolderParents(ctx context.Context, namespace, folderUID string) ([]string, error) {
tuples, err := c.listFolderParentRelations(ctx, namespace, folderUID)
if err != nil {
return nil, err
}
parents := make([]string, 0, len(tuples))
for _, t := range tuples {
// Extract UID from format "folder:UID" or "folder:UID#relation"
userParts := strings.Split(t.Key.User, ":")
if len(userParts) == 2 {
// Remove any relation part after #
uidAndRelationParts := strings.Split(userParts[1], "#")
if len(uidAndRelationParts) > 0 {
parents = append(parents, uidAndRelationParts[0])
} else {
return nil, fmt.Errorf("invalid user format: %s, expected format: folder:UID or folder:UID#relation", t.Key.User)
}
} else {
return nil, fmt.Errorf("invalid user format: %s, expected format: folder:UID or folder:UID#relation", t.Key.User)
}
}
return parents, nil
}
func (c *ZanzanaPermissionStore) DeleteFolderParents(ctx context.Context, namespace, folderUID string) error {
tuples, err := c.listFolderParentRelations(ctx, namespace, folderUID)
if err != nil {
return err
}
if len(tuples) > 0 {
err = c.deleteTuples(ctx, namespace, tuples)
if err != nil {
return err
}
}
return nil
}
// listFolderParentRelations lists parent relations where the given folder is the object.
// It returns tuples where other folders are parents of this folder, not children.
func (c *ZanzanaPermissionStore) listFolderParentRelations(ctx context.Context, namespace, folderUID string) ([]*authzextv1.Tuple, error) {
object, err := toFolderTuple(folderUID)
if err != nil {
return nil, err
}
relation := zanzana.RelationParent
list, err := c.zanzanaClient.Read(ctx, &authzextv1.ReadRequest{
Namespace: namespace,
TupleKey: &authzextv1.ReadRequestTupleKey{
Object: object,
Relation: relation,
},
})
if err != nil {
return nil, err
}
continuationToken := list.ContinuationToken
for continuationToken != "" {
res, err := c.zanzanaClient.Read(ctx, &authzextv1.ReadRequest{
ContinuationToken: continuationToken,
Namespace: namespace,
TupleKey: &authzextv1.ReadRequestTupleKey{
Object: object,
Relation: relation,
},
})
if err != nil {
return nil, err
}
continuationToken = res.ContinuationToken
list.Tuples = append(list.Tuples, res.Tuples...)
}
return list.Tuples, nil
}
func (c *ZanzanaPermissionStore) deleteTuples(ctx context.Context, namespace string, tuples []*authzextv1.Tuple) error {
tupleKeys := make([]*authzextv1.TupleKeyWithoutCondition, 0, len(tuples))
for _, t := range tuples {
tupleKeys = append(tupleKeys, &authzextv1.TupleKeyWithoutCondition{
User: t.Key.User,
Relation: t.Key.Relation,
Object: t.Key.Object,
})
}
return c.zanzanaClient.Write(ctx, &authzextv1.WriteRequest{
Namespace: namespace,
Deletes: &authzextv1.WriteRequestDeletes{
TupleKeys: tupleKeys,
},
})
}
func toFolderTuple(UID string) (string, error) {
if strings.ContainsAny(UID, "#:") {
return "", fmt.Errorf("UID contains invalid characters: %s", UID)
}
return zanzana.NewTupleEntry(zanzana.TypeFolder, UID, ""), nil
}
+5 -4
View File
@@ -65,13 +65,14 @@ require (
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+10 -10
View File
@@ -159,8 +159,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -171,22 +171,22 @@ golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+5 -4
View File
@@ -65,13 +65,14 @@ require (
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+10 -10
View File
@@ -159,8 +159,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -171,22 +171,22 @@ golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+6 -5
View File
@@ -71,14 +71,15 @@ require (
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+12 -12
View File
@@ -171,8 +171,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -185,8 +185,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -206,23 +206,23 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -231,8 +231,8 @@ golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roY
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+5 -4
View File
@@ -55,12 +55,13 @@ require (
go.opentelemetry.io/otel v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
+10 -10
View File
@@ -130,8 +130,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -140,22 +140,22 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -17,9 +17,23 @@ type Repository struct {
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec RepositorySpec `json:"spec,omitempty"`
Secure SecureValues `json:"secure,omitzero,omitempty"`
Status RepositoryStatus `json:"status,omitempty"`
}
// NOT YET USED FOR REAL -- testing secure value workflow
type SecureValues struct {
// Token used to connect the configured repository
Token common.InlineSecureValue `json:"token,omitzero,omitempty"`
// Some webhooks (github) require a secret key value
WebhookSecret common.InlineSecureValue `json:"webhookSecret,omitzero,omitempty"`
}
func (v SecureValues) IsZero() bool {
return v.Token.IsZero() && v.WebhookSecret.IsZero()
}
type LocalRepositoryConfig struct {
Path string `json:"path,omitempty"`
}
@@ -228,10 +242,22 @@ type RepositoryStatus struct {
Webhook *WebhookStatus `json:"webhook"`
}
// HealthFailureType represents different types of repository failures
// +enum
type HealthFailureType string
const (
HealthFailureHook HealthFailureType = "hook"
HealthFailureHealth HealthFailureType = "health"
)
type HealthStatus struct {
// When not healthy, requests will not be executed
Healthy bool `json:"healthy"`
// The type of the error
Error HealthFailureType `json:"error,omitempty"`
// When the health was checked last time
Checked int64 `json:"checked,omitempty"`
@@ -665,6 +665,7 @@ func (in *Repository) DeepCopyInto(out *Repository) {
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
out.Secure = in.Secure
in.Status.DeepCopyInto(&out.Status)
return
}
@@ -1085,6 +1086,24 @@ func (in *ResourceWrapper) DeepCopyObject() runtime.Object {
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SecureValues) DeepCopyInto(out *SecureValues) {
*out = *in
out.Token = in.Token
out.WebhookSecret = in.WebhookSecret
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecureValues.
func (in *SecureValues) DeepCopy() *SecureValues {
if in == nil {
return nil
}
out := new(SecureValues)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SyncJobOptions) DeepCopyInto(out *SyncJobOptions) {
*out = *in
@@ -57,6 +57,7 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ResourceStats": schema_pkg_apis_provisioning_v0alpha1_ResourceStats(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ResourceType": schema_pkg_apis_provisioning_v0alpha1_ResourceType(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ResourceWrapper": schema_pkg_apis_provisioning_v0alpha1_ResourceWrapper(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SecureValues": schema_pkg_apis_provisioning_v0alpha1_SecureValues(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SyncJobOptions": schema_pkg_apis_provisioning_v0alpha1_SyncJobOptions(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SyncOptions": schema_pkg_apis_provisioning_v0alpha1_SyncOptions(ref),
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SyncStatus": schema_pkg_apis_provisioning_v0alpha1_SyncStatus(ref),
@@ -570,6 +571,14 @@ func schema_pkg_apis_provisioning_v0alpha1_HealthStatus(ref common.ReferenceCall
Format: "",
},
},
"error": {
SchemaProps: spec.SchemaProps{
Description: "The type of the error\n\nPossible enum values:\n - `\"health\"`\n - `\"hook\"`",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"health", "hook"},
},
},
"checked": {
SchemaProps: spec.SchemaProps{
Description: "When the health was checked last time",
@@ -1435,6 +1444,12 @@ func schema_pkg_apis_provisioning_v0alpha1_Repository(ref common.ReferenceCallba
Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.RepositorySpec"),
},
},
"secure": {
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SecureValues"),
},
},
"status": {
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
@@ -1445,7 +1460,7 @@ func schema_pkg_apis_provisioning_v0alpha1_Repository(ref common.ReferenceCallba
},
},
Dependencies: []string{
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.RepositorySpec", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.RepositoryStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
"github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.RepositorySpec", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.RepositoryStatus", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SecureValues", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
}
}
@@ -2359,6 +2374,35 @@ func schema_pkg_apis_provisioning_v0alpha1_ResourceWrapper(ref common.ReferenceC
}
}
func schema_pkg_apis_provisioning_v0alpha1_SecureValues(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "NOT YET USED FOR REAL -- testing secure value workflow",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"token": {
SchemaProps: spec.SchemaProps{
Description: "Token used to connect the configured repository",
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1.InlineSecureValue"),
},
},
"webhookSecret": {
SchemaProps: spec.SchemaProps{
Description: "Some webhooks (github) require a secret key value",
Default: map[string]interface{}{},
Ref: ref("github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1.InlineSecureValue"),
},
},
},
},
},
Dependencies: []string{
"github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1.InlineSecureValue"},
}
}
func schema_pkg_apis_provisioning_v0alpha1_SyncJobOptions(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@@ -4,12 +4,17 @@
package v0alpha1
import (
provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1"
)
// HealthStatusApplyConfiguration represents a declarative configuration of the HealthStatus type for use
// with apply.
type HealthStatusApplyConfiguration struct {
Healthy *bool `json:"healthy,omitempty"`
Checked *int64 `json:"checked,omitempty"`
Message []string `json:"message,omitempty"`
Healthy *bool `json:"healthy,omitempty"`
Error *provisioningv0alpha1.HealthFailureType `json:"error,omitempty"`
Checked *int64 `json:"checked,omitempty"`
Message []string `json:"message,omitempty"`
}
// HealthStatusApplyConfiguration constructs a declarative configuration of the HealthStatus type for use with
@@ -26,6 +31,14 @@ func (b *HealthStatusApplyConfiguration) WithHealthy(value bool) *HealthStatusAp
return b
}
// WithError sets the Error field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Error field is set to the value of the last call.
func (b *HealthStatusApplyConfiguration) WithError(value provisioningv0alpha1.HealthFailureType) *HealthStatusApplyConfiguration {
b.Error = &value
return b
}
// WithChecked sets the Checked field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Checked field is set to the value of the last call.
@@ -16,6 +16,7 @@ type RepositoryApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"`
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
Spec *RepositorySpecApplyConfiguration `json:"spec,omitempty"`
Secure *SecureValuesApplyConfiguration `json:"secure,omitempty"`
Status *RepositoryStatusApplyConfiguration `json:"status,omitempty"`
}
@@ -196,6 +197,14 @@ func (b *RepositoryApplyConfiguration) WithSpec(value *RepositorySpecApplyConfig
return b
}
// WithSecure sets the Secure field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Secure field is set to the value of the last call.
func (b *RepositoryApplyConfiguration) WithSecure(value *SecureValuesApplyConfiguration) *RepositoryApplyConfiguration {
b.Secure = value
return b
}
// WithStatus sets the Status field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Status field is set to the value of the last call.
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v0alpha1
import (
commonv0alpha1 "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1"
)
// SecureValuesApplyConfiguration represents a declarative configuration of the SecureValues type for use
// with apply.
type SecureValuesApplyConfiguration struct {
Token *commonv0alpha1.InlineSecureValue `json:"token,omitempty"`
WebhookSecret *commonv0alpha1.InlineSecureValue `json:"webhookSecret,omitempty"`
}
// SecureValuesApplyConfiguration constructs a declarative configuration of the SecureValues type for use with
// apply.
func SecureValues() *SecureValuesApplyConfiguration {
return &SecureValuesApplyConfiguration{}
}
// WithToken sets the Token field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Token field is set to the value of the last call.
func (b *SecureValuesApplyConfiguration) WithToken(value commonv0alpha1.InlineSecureValue) *SecureValuesApplyConfiguration {
b.Token = &value
return b
}
// WithWebhookSecret sets the WebhookSecret field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the WebhookSecret field is set to the value of the last call.
func (b *SecureValuesApplyConfiguration) WithWebhookSecret(value commonv0alpha1.InlineSecureValue) *SecureValuesApplyConfiguration {
b.WebhookSecret = &value
return b
}
@@ -62,6 +62,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} {
return &provisioningv0alpha1.ResourceCountApplyConfiguration{}
case v0alpha1.SchemeGroupVersion.WithKind("ResourceRef"):
return &provisioningv0alpha1.ResourceRefApplyConfiguration{}
case v0alpha1.SchemeGroupVersion.WithKind("SecureValues"):
return &provisioningv0alpha1.SecureValuesApplyConfiguration{}
case v0alpha1.SchemeGroupVersion.WithKind("SyncJobOptions"):
return &provisioningv0alpha1.SyncJobOptionsApplyConfiguration{}
case v0alpha1.SchemeGroupVersion.WithKind("SyncOptions"):
+4 -4
View File
@@ -52,11 +52,11 @@ require (
go.opentelemetry.io/otel/sdk/metric v1.37.0 // indirect
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
+8 -8
View File
@@ -134,8 +134,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -144,14 +144,14 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+5 -4
View File
@@ -66,13 +66,14 @@ require (
go.opentelemetry.io/otel/trace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/net v0.42.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/text v0.27.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.36.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
+10 -10
View File
@@ -159,8 +159,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -171,22 +171,22 @@ golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-17
View File
@@ -1,17 +0,0 @@
# Making changes to the Drone pipeline
> Only members of the Grafana organization can make changes to the Drone pipeline.
The Drone pipelines are built with [Starlark](https://github.com/bazelbuild/starlark), a similar language to Python. The Starlark files are located in [`scripts/drone`](https://github.com/grafana/grafana/tree/main/scripts/drone).
## Drone setup
1. Set environment variables `DRONE_SERVER` and `DRONE_TOKEN` found in your [Drone account](https://drone.grafana.net/account). These environment variables are used to verify that only Grafana employees can make changes to the pipelines.
1. Install [buildifier](https://github.com/bazelbuild/buildtools/blob/master/buildifier/README.md), and use it to format the Starlark files you want to edit.
## Drone development
1. Open a pull request where you can do test runs for your changes. If you need to experiment with secrets, create a pull request in the [`grafana-ci-sandbox repo`](https://github.com/grafana/grafana-ci-sandbox) before opening a pull request in the main repo.
1. Run `make drone` after making changes to the Starlark files. This builds the `.drone.yml` file.
For further questions, reach out to the `grafana-release-guild` squad.
+45
View File
@@ -171,6 +171,51 @@ datasources:
- name: gdev-loki
type: loki
uid: gdev-loki
access: proxy
url: http://loki:3100
editable: false
- name: gdev-pyroscope
type: grafana-pyroscope-datasource
uid: gdev-pyroscope
access: proxy
url: http://pyroscope:4040
editable: false
- name: gdev-tempo
type: tempo
uid: gdev-tempo
access: proxy
url: http://tempo:3200
editable: false
correlations:
- targetUID: gdev-loki
label: 'Logs (correlation)'
description: 'Correlation to logs stored in Loki'
config:
type: query
target:
expr: '{ job="job" }'
field: 'traceID'
jsonData:
tracesToLogsV2:
datasourceUid: gdev-loki
spanStartTimeShift: '5m'
spanEndTimeShift: '-5m'
customQuery: true
query: '{filename="/var/log/grafana/grafana.log"} |="$${__span.traceId}"'
tracesToProfiles:
datasourceUid: gdev-pyroscope
profileTypeId: 'process_cpu:cpu:nanoseconds:cpu:nanoseconds'
tracesToMetrics:
datasourceUid: gdev-prometheus
spanStartTimeShift: '1h'
spanEndTimeShift: '-1h'
tags: [{ key: 'job' }]
queries:
- name: 'Metrics'
query: 'sum(rate({$$__tags}[5m]))'
serviceMap:
datasourceUid: 'gdev-prometheus'
histogramType: 'both' # 'classic' or 'native' or 'both'
@@ -0,0 +1,98 @@
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "grafana",
"uid": "-- Grafana --"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 0,
"id": 10,
"links": [],
"panels": [
{
"datasource": {
"type": "datasource",
"uid": "-- Dashboard --"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": 0
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 10,
"w": 24,
"x": 0,
"y": 0
},
"id": 1,
"maxDataPoints": 10,
"options": {
"counters": {
"dataChanged": true,
"render": true,
"schemaChanged": true
},
"mode": "events",
"stateView": ""
},
"pluginVersion": "12.2.0-16975765900",
"targets": [
{
"datasource": {
"type": "datasource",
"uid": "-- Dashboard --"
},
"refId": "A"
}
],
"title": "Panel Title",
"type": "debug"
}
],
"preload": false,
"refresh": "",
"schemaVersion": 41,
"tags": [],
"templating": {
"list": []
},
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {},
"timezone": "browser",
"title": "Mostly blank dashboard",
"uid": "bds35fot3cv7kb",
"version": 3
}
+13
View File
@@ -0,0 +1,13 @@
# Script called from makefile to auto down the tilt environment on ctrl + c.
# Paths are relative to the makefile
function tilt_down()
{
echo "Tearing down Tilt environment... (this might take a little while)"
tilt down -f devenv/frontend-service/Tiltfile
}
trap tilt_down SIGINT
tilt up -f devenv/frontend-service/Tiltfile
+1
View File
@@ -69,6 +69,7 @@
"loki_fakedata": (import '../dev-dashboards/datasource-loki/loki_fakedata.json'),
"loki_query_splitting": (import '../dev-dashboards/datasource-loki/loki_query_splitting.json'),
"migrations": (import '../dev-dashboards/migrations/migrations.json'),
"mostly-blank-dashboard": (import '../dev-dashboards/scenarios/mostly-blank-dashboard.json'),
"mssql_fakedata": (import '../dev-dashboards/datasource-mssql/mssql_fakedata.json'),
"mssql_unittest": (import '../dev-dashboards/datasource-mssql/mssql_unittest.json'),
"mysql_fakedata": (import '../dev-dashboards/datasource-mysql/mysql_fakedata.json'),
@@ -5,6 +5,7 @@ description: Describes provisioning settings for Grafana using configuration fil
keywords:
- grafana
- provisioning
- provision
labels:
products:
- enterprise
@@ -15,8 +16,7 @@ weight: 600
# Provision Grafana
Grafana has an active provisioning system that uses configuration files.
This makes GitOps more natural since data sources and dashboards can be defined using files that can be version controlled.
Grafana has an active provisioning system that uses configuration files. You can define data sources and dashboards using files that can be version controlled, making GitOps more natural.
## Configuration file
@@ -25,22 +25,22 @@ Refer to [Configuration](../../setup-grafana/configure-grafana/) for more inform
### Configuration file locations
Grafana reads its default configuration from `<WORKING DIRECTORY>/conf/defaults.ini`.
By default, Grafana reads custom configuration from `<WORKING DIRECTORY>/conf/custom.ini`.
You can override the custom configuration path with the `--config` option.
Grafana reads custom configuration from `<WORKING DIRECTORY>/conf/custom.ini`. You can override the custom configuration path with the `--config` option.
{{< admonition type="note" >}}
The Deb and RPM packages install the configuration file at `/etc/grafana/grafana.ini`.
The Grafana init.d script sets the `--config` option to that path.
{{< /admonition >}}
### Use environment variables
## Use environment variables
You can use environment variable lookups in all provisioning configuration.
The syntax for an environment variable is `$ENV_VAR_NAME` or `${ENV_VAR_NAME}`.
If the environment variable value has a `$` in it (for example, `Pa$sw0rd`), use the `$ENV_VAR_NAME` syntax to avoid double expansion.
You can only use environment variables for configuration values and not for keys or bigger parts of the configuration file structure.
You can use environment variable lookups in all provisioning configuration. The syntax for an environment variable is `$ENV_VAR_NAME` or `${ENV_VAR_NAME}`.
You can use environment variables in dashboard provisioning configuration but not the dashboard definition files themselves.
The following applies:
- Only use environment variables for configuration values. Do not use it for keys or bigger parts of the configuration file structure.
- Use environment variables in dashboard provisioning configuration, but not in the dashboard definition files themselves.
The following example looks up the data source URL port, user, and password using environment variables:
@@ -53,7 +53,30 @@ datasources:
password: $PASSWORD
```
To escape a literal `$` in your provisioning file values, use `$$`.
### Use of the special character `$`
Grafana's provisioning system considers any set of characters after an `$` a variable name.
During the replacement process, Grafana:
1. Replaces the variables that use the syntax `${ENV_VAR_NAME}`.
1. Next, it replaces the variables that use the syntax `$ENV_VAR_NAME`.
If your data contains the character `$`, for example `Pa$sw0rd`, and you're using an environment variable, use the `$ENV_VAR_NAME` syntax to avoid double expansion. If you use the `${ENV_VAR_NAME}` syntax, the value will be first replaced as `Pa$sw0rd` and then again as `Pa` since `$sw0rd` will be considered another variable.
If you want to use the literal value `Pa$sw0rd`, you need to escape the character `$` using a double `$$`: `Pa$$sw0rd`.
The following example shows how variables are replaced, assuming `PASSWORD=Pa$sw0rd`:
```yaml
datasources:
- name: Graphite
secureJsonData:
password1: $PASSWORD # Resolved as Pa$sw0rd
password2: ${PASSWORD} # Resolved as Pa
password3: 'Pa$$sw0rd' # Resolved as Pa$sw0rd
password4: 'Pa$sw0rd' # Resolved as Pa
```
## Configuration management tools
@@ -685,6 +685,13 @@
}
}
}
},
"languages": {
"type": "array",
"description": "The list of languages supported by the plugin. Each entry should be a locale identifier in the format `language-COUNTRY` (e.g., `en-US`, `fr-FR`, `es-ES`).",
"items": {
"type": "string"
}
}
}
}
@@ -796,7 +796,7 @@ The following example limits access to the backend of a single plugin:
#### `angular_support_enabled`
This is set to false by default, meaning that the angular framework and support components aren't be loaded.
This is set to false by default, meaning that the angular framework and support components aren't loaded.
This means that all [plugins](../../developers/angular_deprecation/angular-plugins/) and core features that depend on angular support won't work.
The core features that depend on angular are:
+164
View File
@@ -0,0 +1,164 @@
import { Page, Response, Request } from '@playwright/test';
import * as prom from 'prom-client';
/**
* Records and tracks network request body sizes.
*
* You must call listen() before page.goto() for accurate results - this ensures all responses
* for a page are tracked.
*/
export class RequestsRecorder {
#page: Page;
#documentUrl: string | undefined;
#requestsInFlight = 0;
#currentRequests: Set<Request> = new Set<Request>();
#inflatedSizeBytesCounter: prom.Counter<'type' | 'host_type'>;
#transferSizeBytesCounter: prom.Counter<'type' | 'host_type'>;
#requestCountCounter: prom.Counter<'type' | 'host_type'>;
#resolve?: () => void;
constructor(page: Page) {
this.#page = page;
this.#inflatedSizeBytesCounter = new prom.Counter({
name: 'fe_perf_inflated_size_bytes',
help: 'The size of the inflated response body in bytes',
labelNames: ['type', 'host_type'],
registers: [],
});
this.#transferSizeBytesCounter = new prom.Counter({
name: 'fe_perf_transfer_size_bytes',
help: 'The size of the transfered response body in bytes',
labelNames: ['type', 'host_type'],
registers: [],
});
this.#requestCountCounter = new prom.Counter({
name: 'fe_perf_request_count',
help: 'The number of requests made',
labelNames: ['type', 'host_type'],
registers: [],
});
}
listen() {
const handler = this.#handleResponse.bind(this);
const reqHandler = this.#handleRequest.bind(this);
this.#page.on('request', reqHandler);
this.#page.on('response', handler);
return () => {
this.#page.off('response', handler);
this.#page.off('request', reqHandler);
if (this.#requestsInFlight === 0) {
return Promise.resolve();
}
console.log('waiting for', this.#requestsInFlight, 'requests to finish');
return new Promise<void>((resolve) => {
this.#resolve = resolve;
});
};
}
async #handleRequest(request: Request) {
const type = request.resourceType();
// Once we've recieved a document response, create a list of requests that we'll count the responses of.
// We also want to count the document request itself.
if (this.#documentUrl || type === 'document') {
this.#currentRequests.add(request);
}
}
/*
* The Playwright page object has have multiple page loads, and responses for one page may come in after the page
* has been navigated away from. Attempting to get the body of these responses will results in an error, but is also
* not what we want to track.
*
* To solve this, we wait for the 'document' response to come in (a new page has loaded) and then keep track of all
* future requests. We only record responses for requests that were made after the document response.
*/
async #handleResponse(response: Response) {
const request = response.request();
const url = response.url();
const type = response.request().resourceType();
// Record when a document response comes in so we can keep track of future requests
if (type === 'document') {
if (this.#documentUrl) {
console.warn('recieved additional document response', url);
}
this.#documentUrl = url;
}
// Disregard responses that for requests that were initiated before the current page
if (!this.#currentRequests.has(request)) {
return;
}
this.#requestsInFlight += 1;
const hostType = getHostType(response.url(), this.#documentUrl ?? '');
// Attempting to get the body of an empty response results in an error, so guess if the response will be empty or not
const statusCode = response.status();
const noBodyStatusCode = statusCode <= 199 || statusCode === 204 || statusCode === 205 || statusCode === 304;
if (!noBodyStatusCode) {
const body = await response.body();
this.#inflatedSizeBytesCounter.inc({ type, host_type: hostType }, body.length);
}
const sizes = await response.request().sizes();
this.#transferSizeBytesCounter.inc(
{ type, host_type: hostType },
sizes.responseBodySize + sizes.responseHeadersSize
);
this.#requestCountCounter.inc({ type, host_type: hostType });
this.#requestsInFlight -= 1;
if (this.#requestsInFlight === 0 && this.#resolve) {
this.#resolve();
}
}
getMetrics() {
return [this.#inflatedSizeBytesCounter, this.#transferSizeBytesCounter, this.#requestCountCounter];
}
}
/**
* Instead of setting the request host as a label, which may have too high cardinality, we categorise
* the host into a limited set of types.
*/
function getHostType(requestUrl: string, documentUrl: string) {
const url = new URL(requestUrl);
const hostname = url.hostname; // FYI `hostname` doesn't include port, `host` does
const documentHost = new URL(documentUrl).hostname;
if (hostname.match(/^grafana-assets\.grafana(-\w+)?\.net$/)) {
return 'assets_cdn';
}
if (hostname.match(/^plugins-cdn\.grafana(-\w+)?\.net$/)) {
return 'plugin_cdn';
}
if (hostname === documentHost) {
return 'self';
}
return 'other';
}
@@ -0,0 +1,58 @@
import fs from 'fs';
import * as prom from 'prom-client';
import { test, expect } from '@grafana/plugin-e2e';
import { RequestsRecorder } from '../utils/RequestsRecorder';
const DASH_PATH = '/d/bds35fot3cv7kb/mostly-blank-dashboard';
test('payload-size', { tag: '@performance' }, async ({ page }) => {
const promRegistry = new prom.Registry();
const testRunTimeGauge = new prom.Gauge({
name: 'fe_perf_test_run_time_seconds',
help: 'The time it took for the performance test to run',
registers: [promRegistry],
});
const usedJSHeapSizeGauge = new prom.Gauge({
name: 'fe_perf_used_js_heap_size_bytes',
help: 'The amount of memory used by the JavaScript heap',
registers: [promRegistry],
});
const recorder = new RequestsRecorder(page);
const stopListening = recorder.listen();
let start = performance.now();
await page.goto(DASH_PATH);
let el = page.getByTestId('data-testid header-container');
await el.waitFor();
await expect(el).toBeVisible();
let end = performance.now();
let client = await page.context().newCDPSession(page);
await client.send('HeapProfiler.collectGarbage');
let usedJSHeapSize = (await client.send('Runtime.getHeapUsage')).usedSize;
const responseMetrics = recorder.getMetrics();
for (const metric of responseMetrics) {
promRegistry.registerMetric(metric);
}
testRunTimeGauge.set(Math.round(end - start) / 1000);
usedJSHeapSizeGauge.set(+usedJSHeapSize.toFixed(1));
const instance = new URL(process.env.GRAFANA_URL || 'http://undefined').host;
promRegistry.setDefaultLabels({ instance });
const metricsText = await promRegistry.metrics();
console.log(metricsText);
fs.writeFileSync(process.env.METRICS_OUTPUT_PATH || '/tmp/asset-metrics.txt', metricsText);
await stopListening();
page.close();
});
@@ -35,12 +35,12 @@ test.describe(
test('Can view solo repeated panel in scenes', async ({ page, selectors }) => {
// open Panel Tests - Graph NG
const soloPanelUrl = selectors.pages.SoloPanel.url(
'templating-repeating-panels/templating-repeating-panels?orgId=1&from=1699934989607&to=1699956589607&panelId=panel-2-clone-1&__feature.dashboardSceneSolo=true'
'templating-repeating-panels/templating-repeating-panels?orgId=1&from=1699934989607&to=1699956589607&panelId=A$panel-2&__feature.dashboardSceneSolo=true'
);
await page.goto(soloPanelUrl);
// Check that the panel title exists
const panelTitle = page.getByTestId(selectors.components.Panels.Panel.title('server=B'));
const panelTitle = page.getByTestId(selectors.components.Panels.Panel.title('server=A'));
await expect(panelTitle).toBeVisible();
// Check that uplot-main-div does not exist
@@ -51,7 +51,7 @@ test.describe(
test('Can view solo in repeated row and panel in scenes', async ({ page, selectors }) => {
// open Panel Tests - Graph NG
const soloPanelUrl = selectors.pages.SoloPanel.url(
'Repeating-rows-uid/repeating-rows?orgId=1&var-server=A&var-server=B&var-server=D&var-pod=1&var-pod=2&var-pod=3&panelId=panel-16-clone-1/grid-item-2/panel-2-clone-1&__feature.dashboardSceneSolo=true'
'Repeating-rows-uid/repeating-rows?orgId=1&var-server=A&var-server=B&var-server=D&var-pod=1&var-pod=2&var-pod=3&panelId=B$2$panel-2&__feature.dashboardSceneSolo=true'
);
await page.goto(soloPanelUrl);
@@ -1,34 +0,0 @@
import { e2e } from '../utils';
describe('Select focus/unfocus tests', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it.skip('Tests select focus/unfocus scenarios', () => {
e2e.flows.openDashboard({ uid: '5SdHCadmz' });
e2e.components.PageToolbar.item('Dashboard settings').click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('be.visible').click();
});
e2e.components.Select.option().should('be.visible').first().click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('exist').should('have.focus');
});
e2e.pages.Dashboard.Settings.General.title().click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('exist').should('not.have.focus');
});
});
});
@@ -25,17 +25,17 @@ describe('Solo Route', () => {
it('Can view solo repeated panel in scenes', () => {
// open Panel Tests - Graph NG
e2e.pages.SoloPanel.visit(
'templating-repeating-panels/templating-repeating-panels?orgId=1&from=1699934989607&to=1699956589607&panelId=panel-2-clone-1&__feature.dashboardSceneSolo=true'
'templating-repeating-panels/templating-repeating-panels?orgId=1&from=1699934989607&to=1699956589607&panelId=A$panel-2&__feature.dashboardSceneSolo=true'
);
e2e.components.Panels.Panel.title('server=B').should('exist');
e2e.components.Panels.Panel.title('server=A').should('exist');
cy.contains('uplot-main-div').should('not.exist');
});
it('Can view solo in repeated row and panel in scenes', () => {
// open Panel Tests - Graph NG
e2e.pages.SoloPanel.visit(
'Repeating-rows-uid/repeating-rows?orgId=1&var-server=A&var-server=B&var-server=D&var-pod=1&var-pod=2&var-pod=3&panelId=panel-16-clone-1/grid-item-2/panel-2-clone-1&__feature.dashboardSceneSolo=true'
'Repeating-rows-uid/repeating-rows?orgId=1&var-server=A&var-server=B&var-server=D&var-pod=1&var-pod=2&var-pod=3&panelId=B$2$panel-2&__feature.dashboardSceneSolo=true'
);
e2e.components.Panels.Panel.title('server = B, pod = Rob').should('exist');
-20
View File
@@ -1,20 +0,0 @@
import { selectors } from '@grafana/e2e-selectors';
import { e2e } from '../utils';
describe('Bar Gauge Panel', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Bar Gauge rendering e2e tests', () => {
// open Panel Tests - Bar Gauge
e2e.flows.openDashboard({ uid: 'O6f11TZWk' });
cy.get(
`[data-viz-panel-key="panel-6"] [data-testid^="${selectors.components.Panels.Visualization.BarGauge.valueV2}"]`
)
.should('have.css', 'color', 'rgb(242, 73, 92)')
.contains('100');
});
});
-75
View File
@@ -1,75 +0,0 @@
import { e2e } from '../utils';
import { fromBaseUrl } from '../utils/support/url';
describe('Pin nav items', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
afterEach(() => {
e2e.flows.setDefaultUserPreferences();
});
it('should pin the selected menu item and add it as a Bookmarks menu item child', () => {
cy.visit(fromBaseUrl('/'), {
onBeforeLoad: (win) => {
win.localStorage.setItem('grafana.navigation.docked', 'true'); // Make sure the menu is docked
},
});
e2e.components.NavMenu.Menu()
.should('be.visible')
.within(() => {
cy.get('ul[aria-label="Navigation"]').should('be.visible').as('navList');
// Check if the Bookmark section is visible
cy.get('@navList').children().eq(1).should('be.visible').as('bookmarksItem');
cy.get('@bookmarksItem').should('contain.text', 'Bookmarks');
// Check if the Adminstration section is visible
cy.get('@navList').children().last().should('be.visible').as('adminItem');
cy.get('@adminItem').should('contain.text', 'Administration');
cy.get('@adminItem').within(() => {
cy.get('button[aria-label="Add to Bookmarks"]').should('exist').click({ force: true });
});
// Check if the Administration menu item is visible in the Bookmarks section
cy.get('@bookmarksItem').within(() => {
// Expand the Bookmarks section
cy.get('button[aria-label="Expand section: Bookmarks"]').should('exist').click({ force: true });
cy.get('a').should('contain.text', 'Administration').should('be.visible');
});
});
});
it('should unpin the item and remove it from the Bookmarks section', () => {
// Set Administration as a pinned item and reload the page
e2e.flows.setUserPreferences({ navbar: { bookmarkUrls: ['/admin'] } });
cy.visit(fromBaseUrl('/'), {
onBeforeLoad: (win) => {
win.localStorage.setItem('grafana.navigation.docked', 'true'); // Make sure the menu is docked
},
});
e2e.components.NavMenu.Menu()
.should('be.visible')
.within(() => {
cy.get('ul[aria-label="Navigation"]').should('be.visible').as('navList');
// Check if the Bookmark section is visible
cy.get('@navList').children().eq(1).should('be.visible').as('bookmarksItem');
cy.get('@bookmarksItem').should('contain.text', 'Bookmarks');
cy.get('@bookmarksItem').within(() => {
// Expand the Bookmarks section
cy.get('button[aria-label="Expand section: Bookmarks"]').should('exist').click({ force: true });
cy.get('a').should('contain.text', 'Administration').should('be.visible');
cy.get('button[aria-label="Remove from Bookmarks"]').should('exist').click({ force: true });
});
cy.get('@bookmarksItem', { timeout: 60000 }).within(() => {
cy.get('a').should('have.length', 1).should('not.contain.text', 'Administration');
});
});
});
});
-76
View File
@@ -1,76 +0,0 @@
import { e2e } from '../utils';
import { waitForMonacoToLoad } from '../utils/support/monaco';
const dataSourceName = 'PromExemplar';
const addDataSource = () => {
e2e.flows.addDataSource({
type: 'Prometheus',
expectedAlertMessage: 'Prometheus',
name: dataSourceName,
form: () => {
e2e.components.DataSource.Prometheus.configPage.exemplarsAddButton().click();
e2e.components.DataSource.Prometheus.configPage.internalLinkSwitch().check({ force: true });
e2e.components.DataSource.Prometheus.configPage.connectionSettings().type('http://prom-url:9090');
cy.get('[data-testid="data-testid Data source picker select container"]').click();
cy.contains('gdev-tempo').scrollIntoView().should('be.visible').click();
},
});
};
// Skipping due to race conditions with same old arch test e2e/various-suite/exemplars.spec.ts
describe.skip('Exemplars', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.request({
url: `${Cypress.env('BASE_URL')}/api/datasources/name/${dataSourceName}`,
failOnStatusCode: false,
}).then((response) => {
if (response.isOkStatusCode) {
return;
}
addDataSource();
});
});
it('should be able to navigate to configured data source', () => {
cy.intercept(
{
pathname: '/api/ds/query',
},
(req) => {
const datasourceType = req.body.queries[0].datasource.type;
if (datasourceType === 'prometheus') {
req.reply({ fixture: 'exemplars-query-response.json' });
} else if (datasourceType === 'tempo') {
req.reply({ fixture: 'tempo-response.json' });
} else {
req.reply({});
}
}
);
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').click();
cy.contains(dataSourceName).scrollIntoView().should('be.visible').click();
// Switch to code editor
e2e.components.RadioButton.container().filter(':contains("Code")').click();
// Wait for lazy loading Monaco
waitForMonacoToLoad();
e2e.components.TimePicker.openButton().click();
e2e.components.TimePicker.fromField().clear().type('2021-07-10 17:10:00');
e2e.components.TimePicker.toField().clear().type('2021-07-10 17:30:00');
e2e.components.TimePicker.applyTimeRange().click();
e2e.components.QueryField.container().should('be.visible').type('exemplar-query_bucket{shift}{enter}');
cy.get(`[data-testid="time-series-zoom-to-data"]`).click();
e2e.components.DataSource.Prometheus.exemplarMarker().first().trigger('mousemove', { force: true });
cy.contains('Query with gdev-tempo').click();
e2e.components.TraceViewer.spanBar().should('have.length', 11);
});
});
-22
View File
@@ -1,22 +0,0 @@
import { e2e } from '../utils';
describe('Explore', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Basic path through Explore.', () => {
e2e.pages.Explore.visit();
e2e.pages.Explore.General.container().should('have.length', 1);
e2e.components.RefreshPicker.runButtonV2().should('have.length', 1);
e2e.components.DataSource.TestData.QueryTab.scenarioSelectContainer()
.scrollIntoView()
.should('be.visible')
.within(() => {
cy.get('input[id*="test-data-scenario-select-"]').should('be.visible').click();
});
cy.contains('CSV Metric Values').scrollIntoView().should('be.visible').click();
});
});
@@ -1,73 +0,0 @@
import { e2e } from '../utils';
const DASHBOARD_ID = 'ed155665';
// Skipping due to race conditions with same old arch test e2e/various-suite/filter-annotations.spec.ts
describe.skip('Annotations filtering', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Tests switching filter type updates the UI accordingly', () => {
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
e2e.components.NavToolbar.editDashboard.editButton().should('be.visible').click();
e2e.components.NavToolbar.editDashboard.settingsButton().should('be.visible').click();
e2e.components.Tab.title('Annotations').click();
cy.contains('New query').click();
e2e.pages.Dashboard.Settings.Annotations.Settings.name().clear().type('Red - Panel two');
e2e.pages.Dashboard.Settings.Annotations.NewAnnotation.showInLabel()
.should('be.visible')
.within(() => {
// All panels
e2e.components.Annotations.annotationsTypeInput().find('input').type('All panels{enter}', { force: true });
e2e.components.Annotations.annotationsChoosePanelInput().should('not.exist');
// All panels except
e2e.components.Annotations.annotationsTypeInput()
.find('input')
.type('All panels except{enter}', { force: true });
e2e.components.Annotations.annotationsChoosePanelInput().should('be.visible');
// Selected panels
e2e.components.Annotations.annotationsTypeInput().find('input').type('Selected panels{enter}', { force: true });
e2e.components.Annotations.annotationsChoosePanelInput()
.should('be.visible')
.find('input')
.type('Panel two{enter}', { force: true });
});
cy.get('body').click();
e2e.components.NavToolbar.editDashboard.backToDashboardButton().should('be.visible').click();
e2e.pages.Dashboard.Controls()
.should('be.visible')
.within(() => {
e2e.pages.Dashboard.SubMenu.submenuItemLabels('Red - Panel two')
.should('be.visible')
.parent()
.within((el) => {
cy.get('input')
.should('be.checked')
.uncheck({ force: true })
.should('not.be.checked')
.check({ force: true });
});
e2e.pages.Dashboard.SubMenu.submenuItemLabels('Red, only panel 1')
.should('be.visible')
.parent()
.within((el) => {
cy.get('input').should('be.checked');
});
});
e2e.components.Panels.Panel.title('Panel one')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist').should('have.length', 4);
});
});
});
@@ -1,71 +0,0 @@
import { e2e } from '../utils';
const APP_ID = 'sandbox-app-test';
describe('Datasource sandbox', () => {
before(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'), true);
cy.request({
url: `${Cypress.env('BASE_URL')}/api/plugins/${APP_ID}/settings`,
method: 'POST',
body: {
enabled: true,
},
});
});
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'), true);
});
describe('App Page', () => {
describe('Sandbox disabled', () => {
beforeEach(() => {
cy.window().then((win) => {
win.localStorage.setItem('grafana.featureToggles', 'pluginsFrontendSandbox=0');
});
});
it('Loads the app page without the sandbox div wrapper', () => {
cy.visit(`/a/${APP_ID}`);
cy.wait(200); // wait to prevent false positives because cypress checks too fast
cy.get('div[data-plugin-sandbox="sandbox-app-test"]').should('not.exist');
cy.get('div[data-testid="sandbox-app-test-page-one"]').should('exist');
});
it('Loads the app configuration without the sandbox div wrapper', () => {
cy.visit(`/plugins/${APP_ID}`);
cy.wait(200); // wait to prevent false positives because cypress checks too fast
cy.get('div[data-plugin-sandbox="sandbox-app-test"]').should('not.exist');
cy.get('div[data-testid="sandbox-app-test-config-page"]').should('exist');
});
});
describe('Sandbox enabled', () => {
beforeEach(() => {
cy.window().then((win) => {
win.localStorage.setItem('grafana.featureToggles', 'pluginsFrontendSandbox=1');
});
});
it('Loads the app page with the sandbox div wrapper', () => {
cy.visit(`/a/${APP_ID}`);
cy.get('div[data-plugin-sandbox="sandbox-app-test"]').should('exist');
cy.get('div[data-testid="sandbox-app-test-page-one"]').should('exist');
});
it('Loads the app configuration with the sandbox div wrapper', () => {
cy.visit(`/plugins/${APP_ID}`);
cy.get('div[data-plugin-sandbox="sandbox-app-test"]').should('exist');
cy.get('div[data-testid="sandbox-app-test-config-page"]').should('exist');
});
});
});
afterEach(() => {
e2e.flows.revertAllChanges();
});
after(() => {
cy.clearCookies();
});
});
-18
View File
@@ -1,18 +0,0 @@
import { e2e } from '../utils';
describe('Gauge Panel', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Gauge rendering e2e tests', () => {
// open Panel Tests - Gauge
e2e.flows.openDashboard({ uid: '_5rDmaQiz' });
// check that gauges are rendered
cy.get('body').find(`.flot-base`).should('have.length', 16);
// check that no panel errors exist
e2e.components.Panels.Panel.headerCornerInfo('error').should('not.exist');
});
});
@@ -1,61 +0,0 @@
import { e2e } from '../utils';
const DASHBOARD_ID = 'XMjIZPmik';
const DASHBOARD_NAME = 'Panel Tests - Graph Time Regions';
const UPLOT_MAIN_DIV_SELECTOR = '[data-testid="uplot-main-div"]';
describe('Auto-migrate graph panel', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Graph panel is auto-migrated', () => {
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
cy.contains(DASHBOARD_NAME).should('be.visible');
cy.get(UPLOT_MAIN_DIV_SELECTOR).should('not.exist');
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
cy.get(UPLOT_MAIN_DIV_SELECTOR).should('exist');
});
it('Annotation markers exist for time regions', () => {
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
cy.contains(DASHBOARD_NAME).should('be.visible');
cy.get(UPLOT_MAIN_DIV_SELECTOR).should('not.exist');
e2e.flows.openDashboard({ uid: DASHBOARD_ID });
e2e.components.Panels.Panel.title('Business Hours')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title("Sunday's 20-23")
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title('Each day of week')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
cy.scrollTo('bottom');
e2e.components.Panels.Panel.title('05:00')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
e2e.components.Panels.Panel.title('From 22:00 to 00:30 (crossing midnight)')
.should('exist')
.within(() => {
e2e.pages.Dashboard.Annotations.marker().should('exist');
});
});
});
-125
View File
@@ -1,125 +0,0 @@
import { e2e } from '../utils';
const PANEL_UNDER_TEST = 'Value reducers 1';
describe('Inspect drawer tests', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Tests various Inspect Drawer scenarios', () => {
// @ts-ignore some typing issue
cy.on('uncaught:exception', (err) => {
if (err.stack?.indexOf("TypeError: Cannot read property 'getText' of null") !== -1) {
// On occasion monaco editor will not have the time to be properly unloaded when we change the tab
// and then the e2e test fails with the uncaught:exception:
// TypeError: Cannot read property 'getText' of null
// at Object.ai [as getFoldingRanges] (http://localhost:3001/public/build/monaco-json.worker.js:2:215257)
// at e.getFoldingRanges (http://localhost:3001/public/build/monaco-json.worker.js:2:221188)
// at e.fmr (http://localhost:3001/public/build/monaco-json.worker.js:2:116605)
// at e._handleMessage (http://localhost:3001/public/build/monaco-json.worker.js:2:7414)
// at Object.handleMessage (http://localhost:3001/public/build/monaco-json.worker.js:2:7018)
// at e._handleMessage (http://localhost:3001/public/build/monaco-json.worker.js:2:5038)
// at e.handleMessage (http://localhost:3001/public/build/monaco-json.worker.js:2:4606)
// at e.onmessage (http://localhost:3001/public/build/monaco-json.worker.js:2:7097)
// at Tt.self.onmessage (http://localhost:3001/public/build/monaco-json.worker.js:2:117109)
// return false to prevent the error from
// failing this test
return false;
}
return true;
});
e2e.flows.openDashboard({ uid: 'wfTJJL5Wz' });
e2e.components.Panels.Panel.title(PANEL_UNDER_TEST).scrollIntoView().should('be.visible');
e2e.components.Panels.Panel.menu(PANEL_UNDER_TEST).click({ force: true }); // force click because menu is hidden and show on hover
e2e.components.Panels.Panel.menuItems('Inspect').trigger('mouseover', { force: true });
e2e.components.Panels.Panel.menuItems('Data').click({ force: true });
expectDrawerTabsAndContent();
expectDrawerClose();
expectSubMenuScenario('Data');
expectSubMenuScenario('Query');
expectSubMenuScenario('Panel JSON', 'JSON');
e2e.flows.openPanelMenuItem(e2e.flows.PanelMenuItems.Edit, PANEL_UNDER_TEST);
e2e.components.QueryTab.queryInspectorButton().should('be.visible').click();
e2e.components.Drawer.General.title(`Inspect: ${PANEL_UNDER_TEST}`)
.should('be.visible')
.within(() => {
e2e.components.Tab.title('Query').should('be.visible');
// query should be the active tab
e2e.components.Tab.active().should('have.text', 'Query');
});
e2e.components.PanelInspector.Query.content().should('be.visible');
});
});
const expectDrawerTabsAndContent = () => {
e2e.components.Drawer.General.title(`Inspect: ${PANEL_UNDER_TEST}`)
.should('be.visible')
.within(() => {
e2e.components.Tab.title('Data').should('be.visible');
// data should be the active tab
e2e.components.Tab.active().within((li: JQuery<HTMLLIElement>) => {
expect(li.text()).equals('Data');
});
e2e.components.PanelInspector.Data.content().should('be.visible');
e2e.components.PanelInspector.Stats.content().should('not.exist');
e2e.components.PanelInspector.Json.content().should('not.exist');
e2e.components.PanelInspector.Query.content().should('not.exist');
// other tabs should also be visible, click on each to see if we get any console errors
e2e.components.Tab.title('Stats').should('be.visible').click();
e2e.components.PanelInspector.Stats.content().should('be.visible');
e2e.components.PanelInspector.Data.content().should('not.exist');
e2e.components.PanelInspector.Json.content().should('not.exist');
e2e.components.PanelInspector.Query.content().should('not.exist');
e2e.components.Tab.title('JSON').should('be.visible').click();
e2e.components.PanelInspector.Json.content().should('be.visible');
e2e.components.PanelInspector.Data.content().should('not.exist');
e2e.components.PanelInspector.Stats.content().should('not.exist');
e2e.components.PanelInspector.Query.content().should('not.exist');
e2e.components.Tab.title('Query').should('be.visible').click();
e2e.components.PanelInspector.Query.content().should('be.visible');
e2e.components.PanelInspector.Data.content().should('not.exist');
e2e.components.PanelInspector.Stats.content().should('not.exist');
e2e.components.PanelInspector.Json.content().should('not.exist');
});
};
const expectDrawerClose = () => {
// close using close button
e2e.components.Drawer.General.close().click();
e2e.components.Drawer.General.title(`Inspect: ${PANEL_UNDER_TEST}`).should('not.exist');
};
const expectSubMenuScenario = (subMenu: string, tabTitle?: string) => {
tabTitle = tabTitle ?? subMenu;
// testing opening inspect drawer from sub menus under Inspect in header menu
e2e.components.Panels.Panel.title(PANEL_UNDER_TEST).scrollIntoView().should('be.visible');
e2e.components.Panels.Panel.menu(PANEL_UNDER_TEST).click({ force: true }); // force click because menu is hidden and show on hover
// sub menus are in the DOM but not visible and because there is no hover support in Cypress force click
// https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/testing-dom__hover-hidden-elements/cypress/integration/hover-hidden-elements-spec.js
// simulate hover on Inspector menu item to display sub menus
e2e.components.Panels.Panel.menuItems('Inspect').trigger('mouseover', { force: true });
e2e.components.Panels.Panel.menuItems(subMenu).click({ force: true });
// data should be the default tab
e2e.components.Tab.title(tabTitle).should('be.visible');
e2e.components.Tab.active().should('have.text', tabTitle);
expectDrawerClose();
};
-64
View File
@@ -1,64 +0,0 @@
import { e2e } from '../utils';
import { fromBaseUrl } from '../utils/support/url';
// Skipping due to race conditions with same old arch test e2e/various-suite/keybinds.spec.ts
describe.skip('Keyboard shortcuts', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.visit(fromBaseUrl('/'));
// wait for the page to load
e2e.components.Panels.Panel.title('Latest from the blog').should('be.visible');
});
it('sequence shortcuts should work', () => {
cy.get('body').type('ge');
e2e.pages.Explore.General.container().should('be.visible');
cy.get('body').type('gp');
e2e.components.UserProfile.preferencesSaveButton().should('be.visible');
cy.get('body').type('gh');
e2e.components.Panels.Panel.title('Latest from the blog').should('be.visible');
});
it('ctrl+z should zoom out the time range', () => {
cy.get('body').type('ge');
e2e.pages.Explore.General.container().should('be.visible');
// Time range is 1 minute, so each shortcut press should jump back or forward by 1 minute
e2e.flows.setTimeRange({
from: '2024-06-05 10:05:00',
to: '2024-06-05 10:06:00',
zone: 'Browser',
});
e2e.components.RefreshPicker.runButtonV2().should('have.text', 'Run query');
cy.get('body').type('{ctrl}z');
e2e.components.RefreshPicker.runButtonV2().should('have.text', 'Run query');
let expectedRange = `Time range selected: 2024-06-05 10:03:30 to 2024-06-05 10:07:30`;
e2e.components.TimePicker.openButton().should('have.attr', 'aria-label', expectedRange);
});
it('time range shortcuts should work', () => {
cy.get('body').type('ge');
e2e.pages.Explore.General.container().should('be.visible');
// Time range is 1 minute, so each shortcut press should jump back or forward by 1 minute
e2e.flows.setTimeRange({
from: '2024-06-05 10:05:00',
to: '2024-06-05 10:06:00',
zone: 'Browser',
});
e2e.components.RefreshPicker.runButtonV2().should('have.text', 'Run query');
let expectedRange = `Time range selected: 2024-06-05 10:05:00 to 2024-06-05 10:06:00`;
e2e.components.TimePicker.openButton().should('have.attr', 'aria-label', expectedRange);
cy.log('Trying one shift-left');
cy.get('body').type('t{leftarrow}');
e2e.components.RefreshPicker.runButtonV2().should('have.text', 'Run query');
expectedRange = `Time range selected: 2024-06-05 10:04:00 to 2024-06-05 10:05:00`; // 1 min back
e2e.components.TimePicker.openButton().should('have.attr', 'aria-label', expectedRange);
});
});
@@ -1,106 +0,0 @@
import { e2e } from '../utils';
const MISSING_LABEL_FILTER_ERROR_MESSAGE = 'Select at least 1 label filter (label and value)';
const dataSourceName = 'LokiBuilder';
const addDataSource = () => {
e2e.flows.addDataSource({
type: 'Loki',
expectedAlertMessage: 'Unable to connect with Loki. Please check the server logs for more details.',
name: dataSourceName,
form: () => {
cy.get('#connection-url').type('http://loki-url:3100');
},
});
};
const finalQuery = 'rate({instance=~"instance1|instance2"} | logfmt | __error__=`` [$__auto]';
describe('Loki query builder', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.request({
url: `${Cypress.env('BASE_URL')}/api/datasources/name/${dataSourceName}`,
failOnStatusCode: false,
}).then((response) => {
if (response.isOkStatusCode) {
return;
}
addDataSource();
});
});
it('should be able to use all modes', () => {
cy.intercept(/labels\?/, (req) => {
req.reply({ status: 'success', data: ['instance', 'job', 'source'] });
}).as('labelsRequest');
cy.intercept(/series?/, (req) => {
req.reply({ status: 'success', data: [{ instance: 'instance1' }] });
});
cy.intercept(/values/, (req) => {
req.reply({ status: 'success', data: ['instance1', 'instance2'] });
}).as('valuesRequest');
cy.intercept(/index\/stats/, (req) => {
req.reply({ streams: 2, chunks: 2660, bytes: 2721792, entries: 14408 });
});
// Go to Explore and choose Loki data source
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').click();
cy.contains(dataSourceName).scrollIntoView().should('be.visible').click();
// Start in builder mode, click and choose query pattern
e2e.components.QueryBuilder.queryPatterns().click();
cy.contains('Log query starters').click();
cy.contains('Use this query').click();
cy.contains('No pipeline errors').should('be.visible');
cy.contains('Logfmt').should('be.visible');
cy.contains('{} | logfmt | __error__=``').should('be.visible');
// Add operation
cy.contains('Operations').should('be.visible').click();
cy.contains('Range functions').should('be.visible').click();
cy.contains('Rate').should('be.visible').click();
cy.contains('rate({} | logfmt | __error__=`` [$__auto]').should('be.visible');
// Check for expected error
cy.contains(MISSING_LABEL_FILTER_ERROR_MESSAGE).should('be.visible');
// Add labels to remove error
e2e.components.QueryBuilder.labelSelect().should('be.visible').click();
// wait until labels are loaded and set on the component before starting to type
e2e.components.QueryBuilder.inputSelect().type('i');
cy.wait('@labelsRequest');
e2e.components.QueryBuilder.inputSelect().type('nstance{enter}');
e2e.components.QueryBuilder.matchOperatorSelect()
.should('be.visible')
.click({ force: true })
.children('div')
.children('input')
.type('=~{enter}', { force: true });
e2e.components.QueryBuilder.valueSelect().should('be.visible').click();
e2e.components.QueryBuilder.valueSelect().children('div').children('input').type('instance1{enter}');
cy.wait('@valuesRequest');
e2e.components.QueryBuilder.valueSelect().children('div').children('input').type('instance2{enter}');
cy.contains(MISSING_LABEL_FILTER_ERROR_MESSAGE).should('not.exist');
cy.contains(finalQuery).should('be.visible');
// Change to code editor
e2e.components.RadioButton.container().filter(':contains("Code")').click();
// We need to test this manually because the final query is split into separate DOM elements using cy.contains(finalQuery).should('be.visible'); does not detect the query.
cy.contains('rate').should('be.visible');
cy.contains('instance1|instance2').should('be.visible');
cy.contains('logfmt').should('be.visible');
cy.contains('__error__').should('be.visible');
cy.contains('$__auto').should('be.visible');
// Checks the explain mode toggle
cy.contains('label', 'Explain').click();
cy.contains('Fetch all log lines matching label filters.').should('be.visible');
});
});
@@ -1,225 +0,0 @@
import { e2e } from '../utils';
const dataSourceName = 'LokiEditor';
const addDataSource = () => {
e2e.flows.addDataSource({
type: 'Loki',
expectedAlertMessage: 'Unable to connect with Loki. Please check the server logs for more details.',
name: dataSourceName,
form: () => {
cy.get('#connection-url').type('http://loki-url:3100');
},
});
};
const lokiQueryResult = {
status: 'success',
results: {
A: {
status: 200,
frames: [
{
schema: {
refId: 'A',
meta: {
typeVersion: [0, 0],
custom: {
frameType: 'LabeledTimeValues',
},
stats: [
{
displayName: 'Summary: bytes processed per second',
unit: 'Bps',
value: 223921,
},
{
displayName: 'Summary: total bytes processed',
unit: 'decbytes',
value: 4156,
},
{
displayName: 'Summary: exec time',
unit: 's',
value: 0.01856,
},
],
executedQueryString: 'Expr: {targetLabelName="targetLabelValue"}',
},
fields: [
{
name: 'labels',
type: 'other',
typeInfo: {
frame: 'json.RawMessage',
},
},
{
name: 'Time',
type: 'time',
typeInfo: {
frame: 'time.Time',
},
},
{
name: 'Line',
type: 'string',
typeInfo: {
frame: 'string',
},
},
{
name: 'tsNs',
type: 'string',
typeInfo: {
frame: 'string',
},
},
{
name: 'id',
type: 'string',
typeInfo: {
frame: 'string',
},
},
],
},
data: {
values: [
[
{
targetLabelName: 'targetLabelValue',
instance: 'server\\1',
job: '"grafana/data"',
nonIndexed: 'value',
place: 'moon',
re: 'one.two$three^four',
source: 'data',
},
],
[1700077283237],
[
'{"_entry":"log text with ANSI \\u001b[31mpart of the text\\u001b[0m [149702545]","counter":"22292","float":"NaN","wave":-0.5877852522916832,"label":"val3","level":"info"}',
],
['1700077283237000000'],
['1700077283237000000_9b025d35'],
],
},
},
],
},
},
};
describe.skip('Loki Query Editor', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
afterEach(() => {
e2e.flows.revertAllChanges();
});
beforeEach(() => {
cy.setLocalStorage('grafana.featureToggles', 'logsExploreTableVisualisation=1');
});
it('Should be able to add explore table to dashboard', () => {
addDataSource();
cy.intercept(/labels?/, (req) => {
req.reply({ status: 'success', data: ['instance', 'job', 'source'] });
});
cy.intercept(/series?/, (req) => {
req.reply({ status: 'success', data: [{ instance: 'instance1' }] });
});
cy.intercept(/\/api\/ds\/query\?ds_type=loki?/, (req) => {
req.reply(lokiQueryResult);
});
// Go to Explore and choose Loki data source
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').click();
cy.contains(dataSourceName).scrollIntoView().should('be.visible').click();
cy.contains('Code').click({ force: true });
// Wait for lazy loading
// const monacoLoadingText = 'Loading...';
// e2e.components.QueryField.container().should('be.visible').should('have.text', monacoLoadingText);
e2e.components.QueryField.container()
.find('.view-overlays[role="presentation"]')
.get('.cdr')
.then(($el) => {
const win = $el[0].ownerDocument.defaultView;
const after = win.getComputedStyle($el[0], '::after');
const content = after.getPropertyValue('content');
expect(content).to.eq('"Enter a Loki query (run with Shift+Enter)"');
});
// Write a simple query
e2e.components.QueryField.container().type('query').type('{instance="instance1"');
cy.get('.monaco-editor textarea:first').should(($el) => {
expect($el.val()).to.eq('query{instance="instance1"}');
});
// Submit the query
e2e.components.QueryField.container().type('{shift+enter}');
// Assert the no-data message is not visible
cy.get('[data-testid="explore-no-data"]').should('not.exist');
// Click on the table toggle
cy.contains('Table').click({ force: true });
// One row with two cells
cy.get('[role="cell"]').should('have.length', 2);
cy.contains('label', 'targetLabelName').scrollIntoView();
cy.contains('label', 'targetLabelName').should('be.visible');
cy.contains('label', 'targetLabelName').click();
cy.contains('label', 'targetLabelName').within(() => {
cy.get('input[type="checkbox"]').check({ force: true });
});
cy.contains('label', 'targetLabelName').within(() => {
cy.get('input[type="checkbox"]').should('be.checked');
});
const exploreCells = cy.get('[role="cell"]');
// Now we should have a row with 3 columns
exploreCells.should('have.length', 3);
// And a value of "targetLabelValue"
exploreCells.should('contain', 'targetLabelValue');
const addToButton = cy.get('[aria-label="Add"]');
addToButton.should('be.visible');
addToButton.click();
const addToDashboardButton = cy.get('[aria-label="Add to dashboard"]');
// Now let's add this to a dashboard
addToDashboardButton.should('be.visible');
addToDashboardButton.click();
const addPanelToDashboardButton = cy.contains('Add panel to dashboard');
addPanelToDashboardButton.should('be.visible');
const openDashboardButton = cy.contains('Open dashboard');
openDashboardButton.should('be.visible');
openDashboardButton.click();
const panel = cy.get('[data-viz-panel-key="panel-1"]');
panel.should('be.visible');
const cells = panel.find('[role="table"] [role="cell"]');
// Should have 3 columns
cells.should('have.length', 3);
// Cells contain strings found in log line
cells.contains('"wave":-0.5877852522916832');
// column has correct value of "targetLabelValue", need to requery the DOM because of the .contains call above
cy.get('[data-viz-panel-key="panel-1"]').find('[role="table"] [role="cell"]').contains('targetLabelValue');
});
});
-60
View File
@@ -1,60 +0,0 @@
import { e2e } from '../utils';
import { fromBaseUrl } from '../utils/support/url';
describe('Docked Navigation', () => {
beforeEach(() => {
// This is a breakpoint where the mega menu can be docked (and docked is the default state)
cy.viewport(1280, 800);
cy.clearAllLocalStorage();
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.visit(fromBaseUrl('/'));
});
it('should remain un-docked when reloading the page', () => {
// Undock the menu
cy.get('[aria-label="Undock menu"]').click();
e2e.components.NavMenu.Menu().should('not.exist');
cy.reload();
e2e.components.NavMenu.Menu().should('not.exist');
});
it('Can re-dock after undock', () => {
// Undock the menu
cy.get('[aria-label="Undock menu"]').click();
cy.get('[aria-label="Open menu"]').click();
cy.get('[aria-label="Dock menu"]').click();
e2e.components.NavMenu.Menu().should('be.visible');
});
it('should remain in same state when navigating to another page', () => {
// Undock the menu
cy.get('[aria-label="Undock menu"]').click();
// Navigate
cy.get('[aria-label="Open menu"]').click();
cy.contains('a', 'Administration').click();
// Still undocked
e2e.components.NavMenu.Menu().should('not.exist');
// dock the menu
cy.get('[aria-label="Open menu"]').click();
cy.get('[aria-label="Dock menu"]').click();
// Navigate
cy.contains('a', 'Users').click();
// Still docked
e2e.components.NavMenu.Menu().should('be.visible');
});
it('should undock on smaller viewport sizes', () => {
cy.viewport(1120, 1080);
cy.reload();
e2e.components.NavMenu.Menu().should('not.exist');
});
});
-18
View File
@@ -1,18 +0,0 @@
import { selectors } from '@grafana/e2e-selectors';
import { e2e } from '../utils';
describe('Pie Chart Panel', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Pie Chart rendering e2e tests', () => {
// open Panel Tests - Pie Chart
e2e.flows.openDashboard({ uid: 'lVE-2YFMz' });
cy.get(
`[data-viz-panel-key="panel-11"] [data-testid^="${selectors.components.Panels.Visualization.PieChart.svgSlice}"]`
).should('have.length', 5);
});
});
@@ -1,74 +0,0 @@
import { e2e } from '../utils';
import { addDashboard } from '../utils/flows';
import { createPromDS, getResources } from './helpers/prometheus-helpers';
const DATASOURCE_ID = 'Prometheus';
const DATASOURCE_NAME = 'aprometheusAnnotationDS';
/**
* Click dashboard settings and then the variables tab
*
*/
function navigateToAnnotations() {
e2e.components.NavToolbar.editDashboard.editButton().should('be.visible').click();
e2e.components.NavToolbar.editDashboard.settingsButton().should('be.visible').click();
e2e.components.Tab.title('Annotations').click();
}
function addPrometheusAnnotation(annotationName: string) {
e2e.pages.Dashboard.Settings.Annotations.List.addAnnotationCTAV2().click();
getResources();
e2e.pages.Dashboard.Settings.Annotations.Settings.name().clear().type(annotationName);
e2e.components.DataSourcePicker.container().should('be.visible').click();
cy.contains(DATASOURCE_NAME).scrollIntoView().should('be.visible').click();
}
describe('Prometheus annotations', () => {
beforeEach(() => {
createPromDS(DATASOURCE_ID, DATASOURCE_NAME);
});
it('should navigate to variable query editor', () => {
const annotationName = 'promAnnotation';
addDashboard();
navigateToAnnotations();
addPrometheusAnnotation(annotationName);
e2e.components.DataSource.Prometheus.queryEditor.code.metricsBrowser
.openButton()
.contains('Metrics browser')
.click();
e2e.components.DataSource.Prometheus.queryEditor.code.metricsBrowser.selectMetric().should('exist').type('met');
e2e.components.DataSource.Prometheus.queryEditor.code.metricsBrowser
.metricList()
.should('exist')
.contains('metric1')
.click();
e2e.components.DataSource.Prometheus.queryEditor.code.metricsBrowser.useQuery().should('exist').click();
e2e.components.DataSource.Prometheus.queryEditor.code.queryField().should('exist').contains('metric1');
// check for other parts of the annotations
// min step
e2e.components.DataSource.Prometheus.annotations.minStep().should('exist');
// title
e2e.components.DataSource.Prometheus.annotations.title().scrollIntoView().should('exist');
// tags
e2e.components.DataSource.Prometheus.annotations.tags().scrollIntoView().should('exist');
// text
e2e.components.DataSource.Prometheus.annotations.text().scrollIntoView().should('exist');
// series value as timestamp
e2e.components.DataSource.Prometheus.annotations.seriesValueAsTimestamp().scrollIntoView().should('exist');
e2e.components.NavToolbar.editDashboard.backToDashboardButton().should('be.visible').click();
// check that annotation exists
cy.get('body').contains(annotationName);
});
});
-32
View File
@@ -1,32 +0,0 @@
import { e2e } from '../utils';
import { waitForMonacoToLoad } from '../utils/support/monaco';
describe('Query editor', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
// x-ing to bypass this flaky test.
// Will rewrite in plugin-e2e with this issue
xit('Undo should work in query editor for prometheus -- test CI.', () => {
e2e.pages.Explore.visit();
e2e.components.DataSourcePicker.container().should('be.visible').click();
cy.contains('gdev-prometheus').scrollIntoView().should('be.visible').click();
const queryText = `rate(http_requests_total{job="grafana"}[5m])`;
e2e.components.RadioButton.container().filter(':contains("Code")').should('be.visible').click();
waitForMonacoToLoad();
e2e.components.QueryField.container().type(queryText, { parseSpecialCharSequences: false }).type('{backspace}');
cy.contains(queryText.slice(0, -1)).should('be.visible');
e2e.components.QueryField.container().type(e2e.typings.undo());
cy.contains(queryText).should('be.visible');
e2e.components.Alert.alertV2('error').should('not.be.visible');
});
});
@@ -1,71 +0,0 @@
import { e2e } from '../utils';
describe('ReturnToPrevious button', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.visit('/alerting/list');
e2e.components.AlertRules.groupToggle().first().click();
e2e.components.AlertRules.toggle().click();
cy.get('a[title="View"]').click();
cy.url().as('alertRuleUrl');
cy.get('a').contains('View panel').click();
});
it('should appear when changing context and go back to alert rule when clicking "Back"', () => {
// check whether all elements of RTP are available
e2e.components.ReturnToPrevious.buttonGroup().should('be.visible');
e2e.components.ReturnToPrevious.dismissButton().should('be.visible');
e2e.components.ReturnToPrevious.backButton()
.find('span')
.contains('Back to e2e-ReturnToPrevious-test')
.should('be.visible')
.click();
// check whether the RTP button leads back to alert rule
cy.get('@alertRuleUrl').then((alertRuleUrl) => {
cy.url().should('eq', alertRuleUrl);
});
});
it('should disappear when clicking "Dismiss"', () => {
e2e.components.ReturnToPrevious.dismissButton().should('be.visible').click();
e2e.components.ReturnToPrevious.buttonGroup().should('not.exist');
});
it('should not persist when going back to the alert rule details view', () => {
e2e.components.ReturnToPrevious.buttonGroup().should('be.visible');
cy.visit('/alerting/list');
e2e.components.AlertRules.groupToggle().first().click();
cy.get('a[title="View"]').click();
e2e.components.ReturnToPrevious.buttonGroup().should('not.exist');
});
it('should override the button label and change the href when user changes alert rules', () => {
e2e.components.ReturnToPrevious.backButton()
.find('span')
.contains('Back to e2e-ReturnToPrevious-test')
.should('be.visible');
cy.visit('/alerting/list');
e2e.components.AlertRules.groupToggle().last().click();
cy.get('a[title="View"]').click();
cy.url().as('alertRule2Url');
cy.get('a').contains('View panel').click();
e2e.components.ReturnToPrevious.backButton()
.find('span')
.contains('Back to e2e-ReturnToPrevious-test-2')
.should('be.visible')
.click();
e2e.components.ReturnToPrevious.buttonGroup().should('not.exist');
// check whether the RTP button leads back to alert rule
cy.get('@alertRule2Url').then((alertRule2Url) => {
cy.url().should('eq', alertRule2Url);
});
});
});
-34
View File
@@ -1,34 +0,0 @@
import { e2e } from '../utils';
describe('Select focus/unfocus tests', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it.skip('Tests select focus/unfocus scenarios', () => {
e2e.flows.openDashboard({ uid: '5SdHCadmz' });
e2e.components.PageToolbar.item('Dashboard settings').click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('be.visible').click();
});
e2e.components.Select.option().should('be.visible').first().click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('exist').should('have.focus');
});
e2e.pages.Dashboard.Settings.General.title().click();
e2e.components.FolderPicker.containerV2()
.should('be.visible')
.within(() => {
cy.get('#dashboard-folder-input').should('exist').should('not.have.focus');
});
});
});
-44
View File
@@ -1,44 +0,0 @@
import { e2e } from '../utils';
describe('Solo Route', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Can view panels with shared queries in fullscreen', () => {
// open Panel Tests - Bar Gauge
e2e.pages.SoloPanel.visit('ZqZnVvFZz/datasource-tests-shared-queries?orgId=1&panelId=4');
cy.get('canvas').should('have.length', 6);
});
it('Can view solo panel in scenes', () => {
// open Panel Tests - Graph NG
e2e.pages.SoloPanel.visit(
'TkZXxlNG3/panel-tests-graph-ng?orgId=1&from=1699954597665&to=1699956397665&panelId=54&__feature.dashboardSceneSolo=true'
);
e2e.components.Panels.Panel.title('Interpolation: Step before').should('exist');
cy.contains('uplot-main-div').should('not.exist');
});
it('Can view solo repeated panel in scenes', () => {
// open Panel Tests - Graph NG
e2e.pages.SoloPanel.visit(
'templating-repeating-panels/templating-repeating-panels?orgId=1&from=1699934989607&to=1699956589607&panelId=panel-2-clone-1&__feature.dashboardSceneSolo=true'
);
e2e.components.Panels.Panel.title('server=B').should('exist');
cy.contains('uplot-main-div').should('not.exist');
});
it('Can view solo in repeated row and panel in scenes', () => {
// open Panel Tests - Graph NG
e2e.pages.SoloPanel.visit(
'Repeating-rows-uid/repeating-rows?orgId=1&var-server=A&var-server=B&var-server=D&var-pod=1&var-pod=2&var-pod=3&panelId=panel-16-clone-1/grid-item-2/panel-2-clone-1&__feature.dashboardSceneSolo=true'
);
e2e.components.Panels.Panel.title('server = B, pod = Rob').should('exist');
cy.contains('uplot-main-div').should('not.exist');
});
});
-64
View File
@@ -1,64 +0,0 @@
import { e2e } from '../utils';
import { fromBaseUrl } from '../utils/support/url';
describe('Verify i18n', () => {
const I18N_USER = 'i18n-test';
const I18N_PASSWORD = 'i18n-test';
// create a new user to isolate the language changes from other tests
before(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.request({
method: 'POST',
url: fromBaseUrl('/api/admin/users'),
body: {
email: I18N_USER,
login: I18N_USER,
name: I18N_USER,
password: I18N_PASSWORD,
},
}).then((response) => {
cy.wrap(response.body.uid).as('uid');
});
});
// remove the user created in the before hook
after(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
cy.get('@uid').then((uid) => {
cy.request({
method: 'DELETE',
url: fromBaseUrl(`/api/admin/users/${uid}`),
});
});
});
beforeEach(() => {
e2e.flows.login(I18N_USER, I18N_PASSWORD);
});
// map between languages in the language picker and the corresponding translation of the 'Language' label
const languageMap: Record<string, string> = {
Deutsch: 'Sprache',
English: 'Language',
Español: 'Idioma',
Français: 'Langue',
'Português Brasileiro': 'Idioma',
'中文(简体)': '语言',
};
// basic test which loops through the defined languages in the picker
// and verifies that the corresponding label is translated correctly
it('loads all the languages correctly', () => {
cy.visit('/profile');
const LANGUAGE_SELECTOR = '[id="language-preference-select"]';
cy.wrap(Object.entries(languageMap)).each(([language, label]: [string, string]) => {
cy.get(LANGUAGE_SELECTOR).should('not.be.disabled');
cy.get(LANGUAGE_SELECTOR).click();
cy.get(LANGUAGE_SELECTOR).clear().type(language).type('{downArrow}{enter}');
e2e.components.UserProfile.preferencesSaveButton().click();
cy.contains('label', label).should('be.visible');
cy.get(LANGUAGE_SELECTOR).should('have.value', language);
});
});
});
@@ -1,27 +0,0 @@
import { e2e } from '../utils';
describe('Visualization suggestions', () => {
beforeEach(() => {
e2e.flows.login(Cypress.env('USERNAME'), Cypress.env('PASSWORD'));
});
it('Should be shown and clickable', () => {
e2e.flows.openDashboard({ uid: 'aBXrJ0R7z', queryParams: { '__feature.tableNextGen': false, editPanel: 9 } });
// Try visualization suggestions
e2e.components.PanelEditor.toggleVizPicker().click();
e2e.components.RadioButton.container().filter(':contains("Suggestions")').click();
// Verify we see suggestions
e2e.components.VisualizationPreview.card('Line chart').should('be.visible');
// Verify search works
cy.get('[placeholder="Search for..."]').type('Table');
// Should no longer see line chart
e2e.components.VisualizationPreview.card('Line chart').should('not.exist');
// Select a visualisation
e2e.components.VisualizationPreview.card('Table').click();
e2e.components.Panels.Visualization.Table.header().should('be.visible');
});
});
+23 -4
View File
@@ -8,6 +8,8 @@ const jsxA11yPlugin = require('eslint-plugin-jsx-a11y');
const lodashPlugin = require('eslint-plugin-lodash');
const barrelPlugin = require('eslint-plugin-no-barrel-files');
const reactPlugin = require('eslint-plugin-react');
// FIXME: Remove once eslint-config-grafana is updated to include correct plugin
const hooksPlugin = require('eslint-plugin-react-hooks');
const testingLibraryPlugin = require('eslint-plugin-testing-library');
const unicornPlugin = require('eslint-plugin-unicorn');
@@ -58,13 +60,20 @@ module.exports = [
'public/build-swagger', // swagger build output
],
},
// FIXME: Remove once eslint-config-grafana is updated to include correct plugin
{
name: 'react-hooks-plugin',
plugins: {
'react-hooks': hooksPlugin,
},
},
// Conditionally run the betterer rules if enabled in dev's config
...(enableBettererRules ? bettererConfig : []),
grafanaConfig,
// FIXME: Remove filtering once eslint-config-grafana is updated to include correct plugin
...grafanaConfig.filter(Boolean),
{
name: 'react/jsx-runtime',
// @ts-ignore - not sure why but flat config is typed as a maybe?
...reactPlugin.configs.flat['jsx-runtime'],
name: 'react/jsx-runtime-rules',
rules: reactPlugin.configs.flat['jsx-runtime'].rules,
},
{
name: 'grafana/defaults',
@@ -165,6 +174,8 @@ module.exports = [
message: 'No bare anchor nodes containing only text. Use `TextLink` instead.',
},
],
// FIXME: Fix these in follow up PR
'react/no-unescaped-entities': 'off',
},
},
{
@@ -366,6 +377,14 @@ module.exports = [
'testing-library/no-container': 'off',
},
},
{
name: 'grafana/test-disables',
files: ['**/*.{spec,test}.{ts,tsx}'],
rules: {
'react/display-name': 'off',
'react/no-children-prop': 'off',
},
},
{
name: 'grafana/explore-traceview-overrides',
files: ['public/app/features/explore/TraceView/components/demo/**/*.{ts,tsx,js,jsx}'],
+7 -7
View File
@@ -197,15 +197,15 @@ require (
go.uber.org/zap v1.27.0 // @grafana/identity-access-team
gocloud.dev v0.42.0 // @grafana/grafana-app-platform-squad
gocloud.dev/secrets/hashivault v0.42.0 // @grafana/grafana-operator-experience-squad
golang.org/x/crypto v0.40.0 // @grafana/grafana-backend-group
golang.org/x/crypto v0.41.0 // @grafana/grafana-backend-group
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // @grafana/alerting-backend
golang.org/x/mod v0.26.0 // indirect; @grafana/grafana-backend-group
golang.org/x/net v0.42.0 // @grafana/oss-big-tent @grafana/partner-datasources
golang.org/x/mod v0.27.0 // indirect; @grafana/grafana-backend-group
golang.org/x/net v0.43.0 // @grafana/oss-big-tent @grafana/partner-datasources
golang.org/x/oauth2 v0.30.0 // @grafana/identity-access-team
golang.org/x/sync v0.16.0 // @grafana/alerting-backend
golang.org/x/text v0.27.0 // @grafana/grafana-backend-group
golang.org/x/text v0.28.0 // @grafana/grafana-backend-group
golang.org/x/time v0.11.0 // @grafana/grafana-backend-group
golang.org/x/tools v0.35.0 // indirect; @grafana/grafana-as-code
golang.org/x/tools v0.36.0 // indirect; @grafana/grafana-as-code
gonum.org/v1/gonum v0.16.0 // @grafana/oss-big-tent
google.golang.org/api v0.235.0 // @grafana/grafana-backend-group
google.golang.org/grpc v1.74.2 // @grafana/plugins-platform-backend
@@ -603,8 +603,8 @@ require (
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
go4.org/netipx v0.0.0-20230125063823-8449b0a6169f // indirect
golang.org/x/sys v0.34.0 // indirect
golang.org/x/term v0.33.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/term v0.34.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
gomodules.xyz/jsonpatch/v2 v2.5.0 // indirect
google.golang.org/genproto v0.0.0-20250603155806-513f23925822 // indirect

Some files were not shown because too many files have changed in this diff Show More