diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index d8a1e4104bf..7ef6be6644c 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -208,7 +208,7 @@ /pkg/tests/apis/shorturl @grafana/sharing-squad /pkg/tests/api/correlations/ @grafana/datapro /pkg/tsdb/grafanads/ @grafana/grafana-backend-group -/pkg/tsdb/opentsdb/ @grafana/partner-datasources +/pkg/tsdb/opentsdb/ @grafana/oss-big-tent /pkg/util/ @grafana/grafana-backend-group /pkg/web/ @grafana/grafana-backend-group @@ -260,7 +260,7 @@ /devenv/dev-dashboards/dashboards.go @grafana/dataviz-squad /devenv/dev-dashboards/home.json @grafana/dataviz-squad /devenv/dev-dashboards/datasource-elasticsearch/ @grafana/partner-datasources -/devenv/dev-dashboards/datasource-opentsdb/ @grafana/partner-datasources +/devenv/dev-dashboards/datasource-opentsdb/ @grafana/oss-big-tent /devenv/dev-dashboards/datasource-influxdb/ @grafana/partner-datasources /devenv/dev-dashboards/datasource-mssql/ @grafana/partner-datasources /devenv/dev-dashboards/datasource-loki/ @grafana/plugins-platform-frontend @@ -307,7 +307,7 @@ /devenv/docker/blocks/mysql_exporter/ @grafana/oss-big-tent /devenv/docker/blocks/mysql_opendata/ @grafana/oss-big-tent /devenv/docker/blocks/mysql_tests/ @grafana/oss-big-tent -/devenv/docker/blocks/opentsdb/ @grafana/partner-datasources +/devenv/docker/blocks/opentsdb/ @grafana/oss-big-tent /devenv/docker/blocks/postgres/ @grafana/oss-big-tent /devenv/docker/blocks/postgres_tests/ @grafana/oss-big-tent /devenv/docker/blocks/prometheus/ @grafana/oss-big-tent @@ -520,7 +520,7 @@ i18next.config.ts @grafana/grafana-frontend-platform /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/visualization-suggestions.spec.ts @grafana/dataviz-squad /e2e-playwright/various-suite/perf-test.spec.ts @grafana/grafana-frontend-platform # Packages @@ -956,6 +956,7 @@ playwright.storybook.config.ts @grafana/grafana-frontend-platform /public/app/features/notifications/ @grafana/grafana-search-navigate-organise /public/app/features/org/ @grafana/grafana-search-navigate-organise /public/app/features/panel/ @grafana/dashboards-squad +/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx @grafana/dataviz-squad /public/app/features/panel/suggestions/ @grafana/dataviz-squad /public/app/features/playlist/ @grafana/dashboards-squad /public/app/features/plugins/ @grafana/plugins-platform-frontend @@ -1100,7 +1101,7 @@ eslint-suppressions.json @grafanabot /public/app/plugins/datasource/mixed/ @grafana/dashboards-squad /public/app/plugins/datasource/mssql/ @grafana/partner-datasources /public/app/plugins/datasource/mysql/ @grafana/oss-big-tent -/public/app/plugins/datasource/opentsdb/ @grafana/partner-datasources +/public/app/plugins/datasource/opentsdb/ @grafana/oss-big-tent /public/app/plugins/datasource/grafana-postgresql-datasource/ @grafana/oss-big-tent /public/app/plugins/datasource/prometheus/ @grafana/oss-big-tent /public/app/plugins/datasource/cloud-monitoring/ @grafana/partner-datasources diff --git a/.github/workflows/pr-patch-check-event.yml b/.github/workflows/pr-patch-check-event.yml index 2b30e0fa375..86a4ad64917 100644 --- a/.github/workflows/pr-patch-check-event.yml +++ b/.github/workflows/pr-patch-check-event.yml @@ -12,6 +12,7 @@ on: permissions: id-token: write contents: read + statuses: write # Since this is run on a pull request, we want to apply the patches intended for the # target branch onto the source branch, to verify compatibility before merging. diff --git a/.github/workflows/pr-patch-check.yml b/.github/workflows/pr-patch-check.yml index 52f75a05ff2..8a1f70174d7 100644 --- a/.github/workflows/pr-patch-check.yml +++ b/.github/workflows/pr-patch-check.yml @@ -29,6 +29,10 @@ permissions: # target branch onto the source branch, to verify compatibility before merging. jobs: dispatch-job: + # If the source is not from a fork then dispatch the job to the workflow. + # This will fail on forks when trying to broker a token, so instead, forks will create the required status and mark + # it as a success + if: ${{ ! github.event.pull_request.head.repo.fork }} env: HEAD_REF: ${{ inputs.head_ref }} BASE_REF: ${{ github.base_ref }} @@ -76,3 +80,20 @@ jobs: triggering_github_handle: SENDER } }) + dispatch-job-fork: + # If the source is from a fork then use the built-in workflow token to create the same status and unconditionally + # mark it as a success. + if: ${{ github.event.pull_request.head.repo.fork }} + permissions: + statuses: write + runs-on: ubuntu-latest + steps: + - name: Create status + uses: myrotvorets/set-commit-status-action@6d6905c99cd24a4a2cbccc720b62dc6ca5587141 + with: + token: ${{ github.token }} + sha: ${{ inputs.pr_commit_sha }} + repo: ${{ inputs.repo }} + status: success + context: "Test Patches (event)" + description: "Test Patches (event) on a fork" diff --git a/.github/workflows/release-comms.yml b/.github/workflows/release-comms.yml index 58ebe84dbc0..fb65b2a3eed 100644 --- a/.github/workflows/release-comms.yml +++ b/.github/workflows/release-comms.yml @@ -111,12 +111,13 @@ jobs: ownerRepo: 'grafana/grafana-enterprise' from: ${{ needs.setup.outputs.release_branch }} to: ${{ needs.create_next_release_branch_enterprise.outputs.branch }} - post_changelog_on_forum: - needs: setup - uses: grafana/grafana/.github/workflows/community-release.yml@main - with: - version: ${{ needs.setup.outputs.version }} - dry_run: ${{ needs.setup.outputs.dry_run == 'true' }} + # Removed this for now since it doesn't work + # post_changelog_on_forum: + # needs: setup + # uses: grafana/grafana/.github/workflows/community-release.yml@main + # with: + # version: ${{ needs.setup.outputs.version }} + # dry_run: ${{ needs.setup.outputs.dry_run == 'true' }} create_github_release: # a github release requires a git tag # The github-release action retrieves the changelog using the /repos/grafana/grafana/contents/CHANGELOG.md API diff --git a/.golangci.yml b/.golangci.yml index 3b7871662e2..b52a986d435 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,7 +3,7 @@ # Others can set up the YAML LSP manually, which supports schemas: https://github.com/redhat-developer/yaml-language-server # $schema: https://golangci-lint.run/jsonschema/golangci.jsonschema.json -version: "2" +version: '2' run: timeout: 15m concurrency: 10 @@ -83,6 +83,16 @@ linters: deny: - pkg: github.com/grafana/grafana/pkg desc: apps/playlist is not allowed to import grafana core + apps-dashboard: + list-mode: lax + files: + - ./apps/dashboard/* + - ./apps/dashboard/**/* + allow: + - github.com/grafana/grafana/pkg/apimachinery + deny: + - pkg: github.com/grafana/grafana/pkg + desc: apps/dashboard is not allowed to import grafana core apps-secret: list-mode: lax files: @@ -281,16 +291,16 @@ linters: text: G306 - linters: - gosec - text: "401" + text: '401' - linters: - gosec - text: "402" + text: '402' - linters: - gosec - text: "501" + text: '501' - linters: - gosec - text: "404" + text: '404' - linters: - errorlint text: non-wrapping format verb for fmt.Errorf diff --git a/CHANGELOG.md b/CHANGELOG.md index a4dfcb3171a..6bacfafdfd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,101 @@ + + +# 12.3.1 (2025-12-16) + +### Features and enhancements + +- **Alerting:** Update alerting dependency [#114259](https://github.com/grafana/grafana/pull/114259), [@moustafab](https://github.com/moustafab) +- **Azure:** Improved column handling in logs query builder [#114841](https://github.com/grafana/grafana/pull/114841), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Include aggregate columns in logs builder [#114835](https://github.com/grafana/grafana/pull/114835), [@aangelisc](https://github.com/aangelisc) +- **Dependencies:** Bump Go to v1.25.5 [#114751](https://github.com/grafana/grafana/pull/114751), [@macabu](https://github.com/macabu) +- **Docs:** Clarify section title for repeating rows and tabs [#115346](https://github.com/grafana/grafana/pull/115346), [@imatwawana](https://github.com/imatwawana) +- **Plugins:** Add PluginContext to plugins when scenes is disabled [#115064](https://github.com/grafana/grafana/pull/115064), [@hugohaggmark](https://github.com/hugohaggmark) +- **QueryEditorRows:** Clear hideSeriesFrom override on query edit [#114628](https://github.com/grafana/grafana/pull/114628), [@Sergej-Vlasov](https://github.com/Sergej-Vlasov) + +### Bug fixes + +- **Azure:** Fix `dcount` aggregation [#114907](https://github.com/grafana/grafana/pull/114907), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Fix `percentile` syntax [#114707](https://github.com/grafana/grafana/pull/114707), [@aangelisc](https://github.com/aangelisc) +- **Dashboards:** Fix empty space under time controls when a dashboard has a lot of variables [#114730](https://github.com/grafana/grafana/pull/114730), [@oscarkilhed](https://github.com/oscarkilhed) +- **Plugins:** Datasource breadcrumb link should link to settings tab [#113910](https://github.com/grafana/grafana/pull/113910), [@wbrowne](https://github.com/wbrowne) +- **Postgresql:** Fix variable interpolation logic when the variable has multiple values [#114876](https://github.com/grafana/grafana/pull/114876), [@itsmylife](https://github.com/itsmylife) + + + + +# 12.2.3 (2025-12-16) + +### Features and enhancements + +- **Alerting:** Update alerting dependency [#114256](https://github.com/grafana/grafana/pull/114256), [@moustafab](https://github.com/moustafab) +- **Azure:** Improved column handling in logs query builder [#114840](https://github.com/grafana/grafana/pull/114840), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Include aggregate columns in logs builder [#114834](https://github.com/grafana/grafana/pull/114834), [@aangelisc](https://github.com/aangelisc) +- **Dependencies:** Bump Go to v1.25.5 [#114753](https://github.com/grafana/grafana/pull/114753), [@macabu](https://github.com/macabu) +- **Plugins:** Add PluginContext to plugins when scenes is disabled [#115063](https://github.com/grafana/grafana/pull/115063), [@hugohaggmark](https://github.com/hugohaggmark) +- **QueryEditorRows:** Clear hideSeriesFrom override on query edit [#114629](https://github.com/grafana/grafana/pull/114629), [@Sergej-Vlasov](https://github.com/Sergej-Vlasov) + +### Bug fixes + +- **Alerting:** Fix contact points issue [#115412](https://github.com/grafana/grafana/pull/115412), [@yuri-tceretian](https://github.com/yuri-tceretian) +- **Azure:** Fix `dcount` aggregation [#114906](https://github.com/grafana/grafana/pull/114906), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Fix `percentile` syntax [#114706](https://github.com/grafana/grafana/pull/114706), [@aangelisc](https://github.com/aangelisc) +- **Postgresql:** Fix variable interpolation logic when the variable has multiple values [#114875](https://github.com/grafana/grafana/pull/114875), [@itsmylife](https://github.com/itsmylife) + + + + +# 12.1.5 (2025-12-16) + +### Features and enhancements + +- **Alerting:** Update alerting dependency [#114254](https://github.com/grafana/grafana/pull/114254), [@moustafab](https://github.com/moustafab) +- **Dependencies:** Bump Go to v1.25.5 [#114755](https://github.com/grafana/grafana/pull/114755), [@macabu](https://github.com/macabu) +- **Docs:** Clarify section title for repeating rows and tabs [#115344](https://github.com/grafana/grafana/pull/115344), [@imatwawana](https://github.com/imatwawana) +- **Plugins:** Add PluginContext to plugins when scenes is disabled [#115062](https://github.com/grafana/grafana/pull/115062), [@hugohaggmark](https://github.com/hugohaggmark) + +### Bug fixes + +- **Alerting:** Fix contact points issue [#115411](https://github.com/grafana/grafana/pull/115411), [@yuri-tceretian](https://github.com/yuri-tceretian) +- **Azure:** Fix `dcount` aggregation [#114905](https://github.com/grafana/grafana/pull/114905), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Fix `percentile` syntax [#114705](https://github.com/grafana/grafana/pull/114705), [@aangelisc](https://github.com/aangelisc) +- **Postgresql:** Fix variable interpolation logic when the variable has multiple values [#114874](https://github.com/grafana/grafana/pull/114874), [@itsmylife](https://github.com/itsmylife) + + + + +# 12.0.8 (2025-12-16) + +### Features and enhancements + +- **Alerting:** Update alerting dependency [#114252](https://github.com/grafana/grafana/pull/114252), [@moustafab](https://github.com/moustafab) +- **Dependencies:** Bump Go to v1.25.5 [#114756](https://github.com/grafana/grafana/pull/114756), [@macabu](https://github.com/macabu) +- **Docs:** Clarify section title for repeating rows and tabs [#115343](https://github.com/grafana/grafana/pull/115343), [@imatwawana](https://github.com/imatwawana) +- **Plugins:** Add PluginContext to plugins when scenes is disabled [#115061](https://github.com/grafana/grafana/pull/115061), [@hugohaggmark](https://github.com/hugohaggmark) + +### Bug fixes + +- **Alerting:** Fix contact points issue [#115410](https://github.com/grafana/grafana/pull/115410), [@yuri-tceretian](https://github.com/yuri-tceretian) +- **Azure:** Fix `dcount` aggregation [#114904](https://github.com/grafana/grafana/pull/114904), [@aangelisc](https://github.com/aangelisc) +- **Azure:** Fix `percentile` syntax [#114704](https://github.com/grafana/grafana/pull/114704), [@aangelisc](https://github.com/aangelisc) +- **Postgresql:** Fix variable interpolation logic when the variable has multiple values [#114873](https://github.com/grafana/grafana/pull/114873), [@itsmylife](https://github.com/itsmylife) + + + + +# 11.6.9 (2025-12-16) + +### Features and enhancements + +- **Alerting:** Update alerting dependency [#114249](https://github.com/grafana/grafana/pull/114249), [@moustafab](https://github.com/moustafab) +- **Dependencies:** Bump Go to v1.25.5 [#114757](https://github.com/grafana/grafana/pull/114757), [@macabu](https://github.com/macabu) +- **PDFTables:** Dynamically shrink font to try and fit whole table in pdf page width (Enterprise) +- **Plugins:** Add PluginContext to plugins when scenes is disabled [#115060](https://github.com/grafana/grafana/pull/115060), [@hugohaggmark](https://github.com/hugohaggmark) + +### Bug fixes + +- **Alerting:** Fix contacts point issues [#115409](https://github.com/grafana/grafana/pull/115409), [@yuri-tceretian](https://github.com/yuri-tceretian) + + # 12.3.0 (2025-11-19) diff --git a/Dockerfile b/Dockerfile index 558672951e6..2b16926a836 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,7 +14,7 @@ ARG JS_SRC=js-builder # Dependabot cannot update dependencies listed in ARGs # By using FROM instructions we can delegate dependency updates to dependabot -FROM alpine:3.22.2 AS alpine-base +FROM alpine:3.23.0 AS alpine-base FROM ubuntu:22.04 AS ubuntu-base FROM golang:1.25.5-alpine AS go-builder-base FROM --platform=${JS_PLATFORM} node:24-alpine AS js-builder-base diff --git a/apps/advisor/go.mod b/apps/advisor/go.mod index 941d8b9bc0f..1dc4d93b4f5 100644 --- a/apps/advisor/go.mod +++ b/apps/advisor/go.mod @@ -15,6 +15,7 @@ require ( github.com/stretchr/testify v1.11.1 k8s.io/apimachinery v0.34.2 k8s.io/apiserver v0.34.2 + k8s.io/client-go v0.34.2 k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 ) @@ -43,6 +44,7 @@ replace github.com/grafana/grafana/apps/plugins => ../plugins replace github.com/prometheus/alertmanager => github.com/grafana/prometheus-alertmanager v0.25.1-0.20250911094103-5456b6e45604 require ( + cel.dev/expr v0.24.0 // indirect cloud.google.com/go/compute/metadata v0.9.0 // indirect dario.cat/mergo v1.0.2 // indirect filippo.io/edwards25519 v1.1.0 // indirect @@ -55,6 +57,7 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig/v3 v3.3.0 // indirect + github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/ProtonMail/go-crypto v1.1.6 // indirect github.com/VividCortex/mysqlerr v0.0.0-20170204212430-6c6b55f8796f // indirect github.com/alecthomas/units v0.0.0-20240927000941-0f3dac36c52b // indirect @@ -85,6 +88,7 @@ require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cheekybits/genny v1.0.0 // indirect github.com/cloudflare/circl v1.6.1 // indirect + github.com/coreos/go-semver v0.3.1 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect @@ -101,6 +105,7 @@ require ( github.com/evanphx/json-patch v5.9.11+incompatible // 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/fxamacker/cbor/v2 v2.9.0 // indirect github.com/gchaincl/sqlhooks v1.3.0 // indirect github.com/getkin/kin-openapi v0.133.0 // indirect @@ -144,12 +149,13 @@ require ( 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.26.1 // indirect github.com/google/flatbuffers v25.2.10+incompatible // indirect github.com/google/gnostic-models 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.7.0 // indirect - github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba // indirect + github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 // indirect github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f // indirect github.com/grafana/dataplane/sdata v0.0.9 // indirect github.com/grafana/dskit v0.0.0-20250908063411-6b6da59b5cc4 // indirect @@ -162,6 +168,7 @@ require ( github.com/grafana/sqlds/v4 v4.2.7 // indirect github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect + github.com/grpc-ecosystem/go-grpc-prometheus v1.2.1-0.20191002090509-6af20e3a5340 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-hclog v1.6.3 // indirect @@ -176,6 +183,7 @@ require ( github.com/hashicorp/memberlist v0.5.2 // indirect github.com/hashicorp/yamux v0.1.2 // indirect github.com/huandu/xstrings v1.5.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jaegertracing/jaeger-idl v0.5.0 // indirect github.com/jessevdk/go-flags v1.6.1 // indirect github.com/jmespath-community/go-jmespath v1.1.1 // indirect @@ -248,7 +256,9 @@ require ( github.com/shurcooL/vfsgen v0.0.0-20230704071429-0000e147ea92 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/cobra v1.10.1 // indirect github.com/spf13/pflag v1.0.10 // indirect + github.com/stoewer/go-strcase v1.3.1 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/tetratelabs/wazero v1.8.2 // indirect github.com/thomaspoignant/go-feature-flag v1.42.0 // indirect @@ -256,6 +266,9 @@ require ( github.com/woodsbury/decimal128 v1.3.0 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/zeebo/xxh3 v1.0.2 // indirect + go.etcd.io/etcd/api/v3 v3.6.4 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.6.4 // indirect + go.etcd.io/etcd/client/v3 v3.6.4 // indirect go.mongodb.org/mongo-driver v1.17.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.63.0 // indirect @@ -274,6 +287,8 @@ require ( go.opentelemetry.io/proto/otlp v1.9.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/mock v0.6.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.1 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.45.0 // indirect @@ -297,23 +312,26 @@ require ( google.golang.org/grpc v1.77.0 // indirect google.golang.org/protobuf v1.36.10 // indirect gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/evanphx/json-patch.v4 v4.12.0 // 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/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/src-d/go-errors.v1 v1.0.0 // indirect gopkg.in/telebot.v3 v3.3.8 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/api v0.34.2 // indirect k8s.io/apiextensions-apiserver v0.34.2 // indirect - k8s.io/client-go v0.34.2 // indirect k8s.io/component-base v0.34.2 // indirect k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/kms v0.34.2 // indirect k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 // indirect modernc.org/libc v1.66.10 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect modernc.org/sqlite v1.40.1 // indirect + sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 // 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/v6 v6.3.1 // indirect diff --git a/apps/advisor/go.sum b/apps/advisor/go.sum index 4695785bbd1..4c5843a2ee2 100644 --- a/apps/advisor/go.sum +++ b/apps/advisor/go.sum @@ -282,6 +282,7 @@ github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03V github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/cznic/b v0.0.0-20180115125044-35e9bbe41f07/go.mod h1:URriBxXwVq5ijiJ12C7iIZqlA69nTlI+LgI6/pwftG8= github.com/cznic/fileutil v0.0.0-20180108211300-6a051e75936f/go.mod h1:8S58EK26zhXSxzv7NQFpnliaOQsmDUxvoQO3rt154Vg= @@ -406,6 +407,8 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= +github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= github.com/go-openapi/analysis v0.24.0 h1:vE/VFFkICKyYuTWYnplQ+aVr45vlG6NcZKC7BdIXhsA= github.com/go-openapi/analysis v0.24.0/go.mod h1:GLyoJA+bvmGGaHgpfeDh8ldpGo69fAJg7eeMDMRCIrw= github.com/go-openapi/errors v0.22.3 h1:k6Hxa5Jg1TUyZnOwV2Lh81j8ayNw5VVYLvKrp4zFKFs= @@ -606,8 +609,10 @@ github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z github.com/gorilla/mux v1.7.1/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba h1:psKWNETD5nGxmFAlqnWsXoRyUwSa2GHNEMSEDKGKfQ4= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 h1:ZzG/gCclEit9w0QUfQt9GURcOycAIGcsQAhY1u0AEX0= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f h1:Cbm6OKkOcJ+7CSZsGsEJzktC/SIa5bxVeYKQLuYK86o= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f/go.mod h1:axY0cdOg3q0TZHwpHnIz5x16xZ8ZBxJHShsSHHXcHQg= github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 h1:Muoy+FMGrHj3GdFbvsMzUT7eusgii9PKf9L1ZaXDDbY= @@ -749,6 +754,8 @@ github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGw github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= +github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= +github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA= @@ -979,6 +986,7 @@ github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSg github.com/pressly/goose/v3 v3.26.0 h1:KJakav68jdH0WDvoAcj8+n61WqOIaPGgH0bJWS6jpmM= github.com/pressly/goose/v3 v3.26.0/go.mod h1:4hC1KrritdCxtuFsqgs1R4AU5bWtTAf+cnWvfhf2DNY= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.2/go.mod h1:OsXs2jCmiKlQ1lTBmv21f2mNfw4xf/QclQDMrYNZzcM= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= @@ -996,6 +1004,7 @@ github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6T github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= @@ -1010,6 +1019,7 @@ github.com/prometheus/common/sigv4 v0.1.0/go.mod h1:2Jkxxk9yYvCkE5G1sQT7GuEXm57J github.com/prometheus/exporter-toolkit v0.14.0 h1:NMlswfibpcZZ+H0sZBiTjrA3/aBFHkNZqE+iCj5EmRg= github.com/prometheus/exporter-toolkit v0.14.0/go.mod h1:Gu5LnVvt7Nr/oqTBUC23WILZepW0nffNo10XdhQcwWA= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= @@ -1036,6 +1046,7 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sagikazarmark/crypt v0.6.0/go.mod h1:U8+INwJo3nBv1m6A/8OBXAq7Jnpspk5AxSgDyEQcea8= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= @@ -1058,6 +1069,8 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= @@ -1071,6 +1084,7 @@ github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s= github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.13.0/go.mod h1:Icm2xNL3/8uyh/wFuB1jI7TiTNKp8632Nwegu+zgdYw= @@ -1096,6 +1110,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= @@ -1112,6 +1127,8 @@ github.com/thomaspoignant/go-feature-flag v1.42.0/go.mod h1:y0QiWH7chHWhGATb/+Xq github.com/tidwall/pretty v0.0.0-20180105212114-65a9db5fad51/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tjhop/slog-gokit v0.1.5 h1:ayloIUi5EK2QYB8eY4DOPO95/mRtMW42lUkp3quJohc= github.com/tjhop/slog-gokit v0.1.5/go.mod h1:yA48zAHvV+Sg4z4VRyeFyFUNNXd3JY5Zg84u3USICq0= +github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7otjonDflCTK0BCfls4SPy3NcCVb5dqqmbRknE= +github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o= github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= @@ -1129,6 +1146,8 @@ github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcY github.com/xanzy/go-gitlab v0.15.0/go.mod h1:8zdQa/ri1dfn8eS3Ir1SyfvOKlw7WBJ8DVThkpGiXrs= github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= +github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= +github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -1139,6 +1158,8 @@ github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= gitlab.com/nyarla/go-crypt v0.0.0-20160106005555-d9a5dc2b789b/go.mod h1:T3BPAOm2cqquPa0MKWeNkmOM5RQsRhkrwMWonFMN7fE= +go.etcd.io/bbolt v1.4.2 h1:IrUHp260R8c+zYx/Tm8QZr04CX+qWS5PGfPdevhdm1I= +go.etcd.io/bbolt v1.4.2/go.mod h1:Is8rSHO/b4f3XigBC0lL0+4FwAQv3HXEEIgFMuKHceM= go.etcd.io/etcd/api/v3 v3.5.4/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= go.etcd.io/etcd/api/v3 v3.6.4 h1:7F6N7toCKcV72QmoUKa23yYLiiljMrT4xCeBL9BmXdo= go.etcd.io/etcd/api/v3 v3.6.4/go.mod h1:eFhhvfR8Px1P6SEuLT600v+vrhdDTdcfMzmnxVXXSbk= @@ -1149,6 +1170,12 @@ go.etcd.io/etcd/client/v2 v2.305.4/go.mod h1:Ud+VUwIi9/uQHOMA+4ekToJ12lTxlv0zB/+ go.etcd.io/etcd/client/v3 v3.5.4/go.mod h1:ZaRkVgBZC+L+dLCjTcF1hRXpgZXQPOvnA/Ak/gq3kiY= go.etcd.io/etcd/client/v3 v3.6.4 h1:YOMrCfMhRzY8NgtzUsHl8hC2EBSnuqbR3dh84Uryl7A= go.etcd.io/etcd/client/v3 v3.6.4/go.mod h1:jaNNHCyg2FdALyKWnd7hxZXZxZANb0+KGY+YQaEMISo= +go.etcd.io/etcd/pkg/v3 v3.6.4 h1:fy8bmXIec1Q35/jRZ0KOes8vuFxbvdN0aAFqmEfJZWA= +go.etcd.io/etcd/pkg/v3 v3.6.4/go.mod h1:kKcYWP8gHuBRcteyv6MXWSN0+bVMnfgqiHueIZnKMtE= +go.etcd.io/etcd/server/v3 v3.6.4 h1:LsCA7CzjVt+8WGrdsnh6RhC0XqCsLkBly3ve5rTxMAU= +go.etcd.io/etcd/server/v3 v3.6.4/go.mod h1:aYCL/h43yiONOv0QIR82kH/2xZ7m+IWYjzRmyQfnCAg= +go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ= +go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo= go.mongodb.org/mongo-driver v1.1.0/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= go.mongodb.org/mongo-driver v1.17.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw= go.mongodb.org/mongo-driver v1.17.4/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= @@ -1301,6 +1328,7 @@ golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181108082009-03003ca0c849/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1712,6 +1740,7 @@ google.golang.org/genproto/googleapis/api v0.0.0-20251111163417-95abcf5c77ba/go. google.golang.org/genproto/googleapis/rpc v0.0.0-20251111163417-95abcf5c77ba h1:UKgtfRM7Yh93Sya0Fo8ZzhDP4qBckrrxEr2oF5UIVb8= google.golang.org/genproto/googleapis/rpc v0.0.0-20251111163417-95abcf5c77ba/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= diff --git a/apps/advisor/pkg/app/app.go b/apps/advisor/pkg/app/app.go index 9c1dd3c0f98..114b1fbabce 100644 --- a/apps/advisor/pkg/app/app.go +++ b/apps/advisor/pkg/app/app.go @@ -8,18 +8,24 @@ import ( "github.com/grafana/grafana-app-sdk/app" "github.com/grafana/grafana-app-sdk/k8s" + appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" "github.com/grafana/grafana-app-sdk/logging" "github.com/grafana/grafana-app-sdk/operator" "github.com/grafana/grafana-app-sdk/resource" "github.com/grafana/grafana-app-sdk/simple" + advisorapi "github.com/grafana/grafana/apps/advisor/pkg/apis" advisorv0alpha1 "github.com/grafana/grafana/apps/advisor/pkg/apis/advisor/v0alpha1" "github.com/grafana/grafana/apps/advisor/pkg/app/checkregistry" "github.com/grafana/grafana/apps/advisor/pkg/app/checks" "github.com/grafana/grafana/apps/advisor/pkg/app/checkscheduler" "github.com/grafana/grafana/apps/advisor/pkg/app/checktyperegisterer" "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/services/org" + "github.com/grafana/grafana/pkg/setting" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/authorization/authorizer" + "k8s.io/client-go/rest" ) func New(cfg app.Config) (app.App, error) { @@ -188,3 +194,45 @@ func GetKinds() map[schema.GroupVersion][]resource.Kind { }, } } + +func ProvideAppInstaller( + authorizer authorizer.Authorizer, + checkRegistry checkregistry.CheckService, + cfg *setting.Cfg, + orgService org.Service, +) (*AdvisorAppInstaller, error) { + provider := simple.NewAppProvider(advisorapi.LocalManifest(), nil, New) + pluginConfig := cfg.PluginSettings["grafana-advisor-app"] + specificConfig := checkregistry.AdvisorAppConfig{ + CheckRegistry: checkRegistry, + PluginConfig: pluginConfig, + StackID: cfg.StackID, + OrgService: orgService, + } + appCfg := app.Config{ + KubeConfig: rest.Config{}, + ManifestData: *advisorapi.LocalManifest().ManifestData, + SpecificConfig: specificConfig, + } + + defaultInstaller, err := appsdkapiserver.NewDefaultAppInstaller(provider, appCfg, advisorapi.NewGoTypeAssociator()) + if err != nil { + return nil, err + } + + installer := &AdvisorAppInstaller{ + AppInstaller: defaultInstaller, + authorizer: authorizer, + } + + return installer, nil +} + +type AdvisorAppInstaller struct { + appsdkapiserver.AppInstaller + authorizer authorizer.Authorizer +} + +func (a *AdvisorAppInstaller) GetAuthorizer() authorizer.Authorizer { + return a.authorizer +} diff --git a/apps/advisor/pkg/app/authorizer.go b/apps/advisor/pkg/app/authorizer.go deleted file mode 100644 index 576773330e3..00000000000 --- a/apps/advisor/pkg/app/authorizer.go +++ /dev/null @@ -1,47 +0,0 @@ -package app - -import ( - "context" - - claims "github.com/grafana/authlib/types" - "github.com/grafana/grafana/pkg/apimachinery/identity" - "k8s.io/apiserver/pkg/authorization/authorizer" -) - -func GetAuthorizer() authorizer.Authorizer { - return authorizer.AuthorizerFunc(func( - ctx context.Context, attr authorizer.Attributes, - ) (authorized authorizer.Decision, reason string, err error) { - if !attr.IsResourceRequest() { - return authorizer.DecisionNoOpinion, "", nil - } - - // Check for service identity - if identity.IsServiceIdentity(ctx) { - return authorizer.DecisionAllow, "", nil - } - - // Check for access policy identity - info, ok := claims.AuthInfoFrom(ctx) - if ok && claims.IsIdentityType(info.GetIdentityType(), claims.TypeAccessPolicy) { - // For access policy identities, we need to use ResourceAuthorizer - // This requires an AccessClient, which should be provided by the API server - // For now, we'll use the default ResourceAuthorizer from the API server - // This will be set up by the API server's authorization chain - return authorizer.DecisionNoOpinion, "", nil - } - - // For regular Grafana users, check if they are admin - u, err := identity.GetRequester(ctx) - if err != nil { - return authorizer.DecisionDeny, "valid user is required", err - } - - // check if is admin - if u.HasRole(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - - return authorizer.DecisionDeny, "forbidden", nil - }) -} diff --git a/apps/advisor/pkg/app/authorizer_test.go b/apps/advisor/pkg/app/authorizer_test.go deleted file mode 100644 index de8c0fad2db..00000000000 --- a/apps/advisor/pkg/app/authorizer_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package app - -import ( - "context" - "testing" - - claims "github.com/grafana/authlib/types" - "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/stretchr/testify/assert" - "k8s.io/apiserver/pkg/authorization/authorizer" -) - -func TestGetAuthorizer(t *testing.T) { - tests := []struct { - name string - ctx context.Context - attr authorizer.Attributes - expectedDecision authorizer.Decision - expectedReason string - expectedErr error - }{ - { - name: "non-resource request", - ctx: context.TODO(), - attr: &mockAttributes{resourceRequest: false}, - expectedDecision: authorizer.DecisionNoOpinion, - expectedReason: "", - expectedErr: nil, - }, - { - name: "user is admin", - ctx: identity.WithRequester(context.TODO(), &mockUser{isGrafanaAdmin: true}), - attr: &mockAttributes{resourceRequest: true}, - expectedDecision: authorizer.DecisionAllow, - expectedReason: "", - expectedErr: nil, - }, - { - name: "user is not admin", - ctx: identity.WithRequester(context.TODO(), &mockUser{isGrafanaAdmin: false}), - attr: &mockAttributes{resourceRequest: true}, - expectedDecision: authorizer.DecisionDeny, - expectedReason: "forbidden", - expectedErr: nil, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - auth := GetAuthorizer() - decision, reason, err := auth.Authorize(tt.ctx, tt.attr) - assert.Equal(t, tt.expectedDecision, decision) - assert.Equal(t, tt.expectedReason, reason) - assert.Equal(t, tt.expectedErr, err) - }) - } -} - -type mockAttributes struct { - authorizer.Attributes - resourceRequest bool -} - -func (m *mockAttributes) IsResourceRequest() bool { - return m.resourceRequest -} - -// Implement other methods of authorizer.Attributes as needed - -type mockUser struct { - identity.Requester - isGrafanaAdmin bool -} - -func (m *mockUser) GetIsGrafanaAdmin() bool { - return m.isGrafanaAdmin -} - -func (m *mockUser) HasRole(role identity.RoleType) bool { - return role == identity.RoleAdmin && m.isGrafanaAdmin -} - -func (m *mockUser) GetUID() string { - return "test-uid" -} - -func (m *mockUser) GetIdentityType() claims.IdentityType { - return claims.TypeUser -} - -// Implement other methods of identity.Requester as needed diff --git a/apps/alerting/historian/go.mod b/apps/alerting/historian/go.mod index 21ad42c90af..dc8b8ef80a9 100644 --- a/apps/alerting/historian/go.mod +++ b/apps/alerting/historian/go.mod @@ -4,7 +4,7 @@ go 1.25.5 require ( github.com/go-kit/log v0.2.1 - github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba + github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 github.com/grafana/dskit v0.0.0-20250908063411-6b6da59b5cc4 github.com/grafana/grafana-app-sdk v0.48.5 github.com/grafana/grafana-app-sdk/logging v0.48.3 diff --git a/apps/alerting/historian/go.sum b/apps/alerting/historian/go.sum index 9c00f19a029..e4440ed687f 100644 --- a/apps/alerting/historian/go.sum +++ b/apps/alerting/historian/go.sum @@ -216,12 +216,10 @@ github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grafana/grafana-app-sdk v0.48.5 h1:MS8l9fTZz+VbTfgApn09jw27GxhQ6fNOWGhC4ydvZmM= -github.com/grafana/grafana-app-sdk v0.48.5/go.mod h1:HJsMOSBmt/D/Ihs1SvagOwmXKi0coBMVHlfvdd+qe9Y= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba h1:psKWNETD5nGxmFAlqnWsXoRyUwSa2GHNEMSEDKGKfQ4= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 h1:ZzG/gCclEit9w0QUfQt9GURcOycAIGcsQAhY1u0AEX0= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= github.com/grafana/dskit v0.0.0-20250908063411-6b6da59b5cc4 h1:jSojuc7njleS3UOz223WDlXOinmuLAIPI0z2vtq8EgI= github.com/grafana/dskit v0.0.0-20250908063411-6b6da59b5cc4/go.mod h1:VahT+GtfQIM+o8ht2StR6J9g+Ef+C2Vokh5uuSmOD/4= github.com/grafana/grafana-app-sdk v0.48.5 h1:MS8l9fTZz+VbTfgApn09jw27GxhQ6fNOWGhC4ydvZmM= diff --git a/apps/collections/pkg/apis/collections/v1alpha1/stars.go b/apps/collections/pkg/apis/collections/v1alpha1/stars.go index e203e6b560e..79bff8a6513 100644 --- a/apps/collections/pkg/apis/collections/v1alpha1/stars.go +++ b/apps/collections/pkg/apis/collections/v1alpha1/stars.go @@ -8,9 +8,8 @@ import ( func (stars *StarsSpec) Add(group, kind, name string) { for i, r := range stars.Resource { if r.Group == group && r.Kind == kind { - r.Names = append(r.Names, name) - slices.Sort(r.Names) - stars.Resource[i].Names = slices.Compact(r.Names) + stars.Resource[i].Names = append(r.Names, name) + stars.Normalize() return } } @@ -46,8 +45,15 @@ func (stars *StarsSpec) Normalize() { resources := make([]StarsResource, 0, len(stars.Resource)) for _, r := range stars.Resource { if len(r.Names) > 0 { - slices.Sort(r.Names) - r.Names = slices.Compact(r.Names) // removes any duplicates + unique := make([]string, 0, len(r.Names)) + found := make(map[string]bool, len(r.Names)) + for _, name := range r.Names { + if !found[name] { + unique = append(unique, name) + found[name] = true + } + } + r.Names = unique resources = append(resources, r) } } diff --git a/apps/collections/pkg/apis/collections/v1alpha1/stars_test.go b/apps/collections/pkg/apis/collections/v1alpha1/stars_test.go index 5713b07a751..d4421fae614 100644 --- a/apps/collections/pkg/apis/collections/v1alpha1/stars_test.go +++ b/apps/collections/pkg/apis/collections/v1alpha1/stars_test.go @@ -39,7 +39,7 @@ func TestStarsWrite(t *testing.T) { Resource: []StarsResource{{ Group: "g", Kind: "k", - Names: []string{"a", "b", "c", "x"}, // added "b" (and sorted) + Names: []string{"a", "b", "x", "c"}, // added c to the end }}, }, }, { diff --git a/apps/dashboard/go.mod b/apps/dashboard/go.mod index 0a19120fe80..00fe99f0c9c 100644 --- a/apps/dashboard/go.mod +++ b/apps/dashboard/go.mod @@ -9,6 +9,7 @@ require ( github.com/grafana/grafana-app-sdk/logging v0.48.3 github.com/grafana/grafana-plugin-sdk-go v0.284.0 github.com/grafana/grafana/pkg/apimachinery v0.0.0-20250514132646-acbc7b54ed9e + github.com/hashicorp/golang-lru/v2 v2.0.7 github.com/prometheus/client_golang v1.23.2 github.com/stretchr/testify v1.11.1 k8s.io/apimachinery v0.34.2 diff --git a/apps/dashboard/go.sum b/apps/dashboard/go.sum index 0faeaaf78ba..a93f97a1d0e 100644 --- a/apps/dashboard/go.sum +++ b/apps/dashboard/go.sum @@ -112,6 +112,8 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-plugin v1.7.0 h1:YghfQH/0QmPNc/AZMTFE3ac8fipZyZECHdDPshfk+mA= github.com/hashicorp/go-plugin v1.7.0/go.mod h1:BExt6KEaIYx804z8k4gRzRLEvxKVb+kn0NMcihqOqb8= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/yamux v0.1.2 h1:XtB8kyFOyHXYVFnwT5C3+Bdo8gArse7j2AQ0DA0Uey8= github.com/hashicorp/yamux v0.1.2/go.mod h1:C+zze2n6e/7wshOZep2A70/aQU6QBRWJO/G6FT1wIns= github.com/jaegertracing/jaeger-idl v0.5.0 h1:zFXR5NL3Utu7MhPg8ZorxtCBjHrL3ReM1VoB65FOFGE= diff --git a/apps/dashboard/pkg/apis/dashboard/v0alpha1/dashboard_kind.cue b/apps/dashboard/pkg/apis/dashboard/v0alpha1/dashboard_kind.cue index 4a255a57ba6..8338c9e13c5 100644 --- a/apps/dashboard/pkg/apis/dashboard/v0alpha1/dashboard_kind.cue +++ b/apps/dashboard/pkg/apis/dashboard/v0alpha1/dashboard_kind.cue @@ -706,6 +706,10 @@ lineage: schemas: [{ // Field options allow you to change how the data is displayed in your visualizations. fieldConfig?: #FieldConfigSource + + // When a panel is migrated from a previous version (Angular to React), this field is set to the original panel type. + // This is used to determine the original panel type when migrating to a new version so the plugin migration can be applied. + autoMigrateFrom?: string } @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview) // The data model used in Grafana, namely the data frame, is a columnar-oriented table structure that unifies both time series and table query results. diff --git a/apps/dashboard/pkg/apis/dashboard/v1beta1/dashboard_kind.cue b/apps/dashboard/pkg/apis/dashboard/v1beta1/dashboard_kind.cue index 4a255a57ba6..8338c9e13c5 100644 --- a/apps/dashboard/pkg/apis/dashboard/v1beta1/dashboard_kind.cue +++ b/apps/dashboard/pkg/apis/dashboard/v1beta1/dashboard_kind.cue @@ -706,6 +706,10 @@ lineage: schemas: [{ // Field options allow you to change how the data is displayed in your visualizations. fieldConfig?: #FieldConfigSource + + // When a panel is migrated from a previous version (Angular to React), this field is set to the original panel type. + // This is used to determine the original panel type when migrating to a new version so the plugin migration can be applied. + autoMigrateFrom?: string } @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview) // The data model used in Grafana, namely the data frame, is a columnar-oriented table structure that unifies both time series and table query results. diff --git a/apps/dashboard/pkg/migration/README.md b/apps/dashboard/pkg/migration/README.md index ab938e31f66..6fd2069cce9 100644 --- a/apps/dashboard/pkg/migration/README.md +++ b/apps/dashboard/pkg/migration/README.md @@ -53,6 +53,7 @@ v0alpha1 (Legacy JSON) → v1beta1 (Migrated JSON) → v2alpha1/v2beta1 (Structu - Transforms JSON dashboards to structured dashboard format - v2 schema is the stable, typed schema with proper type definitions - Handles modern dashboard features and Kubernetes-native storage +- Preserves Angular panel migration data for frontend processing (see [Angular Panel Migrations](#angular-panel-migrations)) - See [V2 to V1 Layout Conversion](./conversion/v2_to_v1_layout_conversion.md) for details on how V2 layouts are converted back to V1 panel arrays #### v2 to v0/v1 Conversion: @@ -61,6 +62,76 @@ v0alpha1 (Legacy JSON) → v1beta1 (Migrated JSON) → v2alpha1/v2beta1 (Structu - v0alpha1 and v1beta1 share the same spec structure (only API version differs) - Enables backward compatibility when storing v2 dashboards in legacy format +### Angular Panel Migrations + +When converting dashboards from v0/v1 to v2, panels with Angular types require special handling. The `autoMigrateFrom` field is used in v0 and v1 to indicate the panel was migrated from a deprecated plugin type, and the target plugin contains migration logic to transform the original panel's options and field configurations. + +Panel plugins define their own migration logic via `plugin.onPanelTypeChanged()`. This migration runs in the frontend when a panel type changes, transforming old options/fieldConfig to the new format. Examples: +- `singlestat.format: "short"` → `stat.fieldConfig.defaults.unit: "short"` +- `graph.legend.show: true` → `timeseries.options.legend.showLegend: true` + +The v2 schema doesn't include `autoMigrateFrom` as a typed field, so we need a mechanism to preserve the original panel data for the frontend to run these plugin migrations. + +#### `__angularMigration` Temporary Data + +The backend v1 → v2 conversion preserves the original panel data in a temporary field within `vizConfig.spec.options`. This works for **any** Angular panel, not just specific panel types: + +```json +{ + "vizConfig": { + "kind": "stat", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalPanel": { + "type": "singlestat", + "format": "short", + "colorBackground": true, + "sparkline": { "show": true }, + "fieldConfig": { ... }, + "options": { ... } + } + } + } + } + } +} +``` + +#### How It Works + +1. **Backend (v1 → v2):** The conversion detects panels that need Angular migration in two ways: + - If `autoMigrateFrom` is already set on the panel (from v0 → v1 migration) - panel type already converted + - If the panel type is a known Angular panel type (fallback for dashboards stored directly as v1 without v0 → v1 migration) + + In the second case, the conversion also transforms the panel type (e.g., `singlestat` → `stat`) and sets `autoMigrateFrom`. This replicates the same logic as the v0 → v1 migration. + + The entire original panel is stored under `options.__angularMigration` for the frontend to run plugin-specific migrations. + +2. **Frontend (v2 load):** When building a `VizPanel` from v2 data: + - Extracts `__angularMigration` from options + - Removes it from the options object (not persisted) + - Attaches a custom migration handler via `_UNSAFE_customMigrationHandler` + +3. **Plugin load (VizPanel activation):** When the plugin loads, the migration handler calls `plugin.onPanelTypeChanged()` with the original panel data, allowing the plugin's own migration code to run + +#### Key Points + +- Works for **any** panel with `autoMigrateFrom`, not limited to specific panel types +- Each plugin defines its own migration logic - the backend just preserves the data +- The `originalPanel` contains the complete panel data to ensure no information is lost +- Migration data is removed from options after loaded in frontend +- The 0v → v1 and v1 → v2 conversions automatically detects these Angular panel types if `autoMigrateFrom` is not set. + +#### Implementation Files + +| File | Purpose | +|------|---------| +| `apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1.go` | Injects `__angularMigration` during v1 → v2 | +| `public/app/features/dashboard-scene/serialization/layoutSerializers/utils.ts` | Extracts and consumes `__angularMigration` | +| `public/app/features/dashboard-scene/serialization/angularMigration.ts` | Creates migration handler for v2 path | + ## Conversion Matrix The system supports conversions between all dashboard API versions: diff --git a/apps/dashboard/pkg/migration/conversion/conversion_cache_test.go b/apps/dashboard/pkg/migration/conversion/conversion_cache_test.go new file mode 100644 index 00000000000..3e54d9682fd --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/conversion_cache_test.go @@ -0,0 +1,454 @@ +package conversion + +import ( + "context" + "sync/atomic" + "testing" + "time" + + dashv0 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v0alpha1" + dashv1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v1beta1" + dashv2alpha1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v2alpha1" + dashv2beta1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v2beta1" + "github.com/grafana/grafana/apps/dashboard/pkg/migration" + "github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion" + common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// countingDataSourceProvider tracks how many times Index() is called +type countingDataSourceProvider struct { + datasources []schemaversion.DataSourceInfo + callCount atomic.Int64 +} + +func newCountingDataSourceProvider(datasources []schemaversion.DataSourceInfo) *countingDataSourceProvider { + return &countingDataSourceProvider{ + datasources: datasources, + } +} + +func (p *countingDataSourceProvider) Index(_ context.Context) *schemaversion.DatasourceIndex { + p.callCount.Add(1) + return schemaversion.NewDatasourceIndex(p.datasources) +} + +func (p *countingDataSourceProvider) getCallCount() int64 { + return p.callCount.Load() +} + +// countingLibraryElementProvider tracks how many times GetLibraryElementInfo() is called +type countingLibraryElementProvider struct { + elements []schemaversion.LibraryElementInfo + callCount atomic.Int64 +} + +func newCountingLibraryElementProvider(elements []schemaversion.LibraryElementInfo) *countingLibraryElementProvider { + return &countingLibraryElementProvider{ + elements: elements, + } +} + +func (p *countingLibraryElementProvider) GetLibraryElementInfo(_ context.Context) []schemaversion.LibraryElementInfo { + p.callCount.Add(1) + return p.elements +} + +func (p *countingLibraryElementProvider) getCallCount() int64 { + return p.callCount.Load() +} + +// createTestV0Dashboard creates a minimal v0 dashboard for testing +// The dashboard has a datasource with UID only (no type) to force provider lookup +// and includes library panels to test library element provider caching +func createTestV0Dashboard(namespace, title string) *dashv0.Dashboard { + return &dashv0.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-dashboard", + Namespace: namespace, + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": title, + "schemaVersion": schemaversion.LATEST_VERSION, + // Variables with datasource reference that requires lookup + "templating": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{ + "name": "query_var", + "type": "query", + "query": "label_values(up, job)", + // Datasource with UID only - type needs to be looked up + "datasource": map[string]interface{}{ + "uid": "ds1", + // type is intentionally omitted to trigger provider lookup + }, + }, + }, + }, + "panels": []interface{}{ + map[string]interface{}{ + "id": 1, + "title": "Test Panel", + "type": "timeseries", + "targets": []interface{}{ + map[string]interface{}{ + // Datasource with UID only - type needs to be looked up + "datasource": map[string]interface{}{ + "uid": "ds1", + }, + }, + }, + }, + // Library panel reference - triggers library element provider lookup + map[string]interface{}{ + "id": 2, + "title": "Library Panel with Horizontal Repeat", + "type": "library-panel-ref", + "gridPos": map[string]interface{}{ + "h": 8, + "w": 12, + "x": 0, + "y": 8, + }, + "libraryPanel": map[string]interface{}{ + "uid": "lib-panel-repeat-h", + "name": "Library Panel with Horizontal Repeat", + }, + }, + // Another library panel reference + map[string]interface{}{ + "id": 3, + "title": "Library Panel without Repeat", + "type": "library-panel-ref", + "gridPos": map[string]interface{}{ + "h": 3, + "w": 6, + "x": 0, + "y": 16, + }, + "libraryPanel": map[string]interface{}{ + "uid": "lib-panel-no-repeat", + "name": "Library Panel without Repeat", + }, + }, + }, + }, + }, + } +} + +// createTestV1Dashboard creates a minimal v1beta1 dashboard for testing +// The dashboard has a datasource with UID only (no type) to force provider lookup +// and includes library panels to test library element provider caching +func createTestV1Dashboard(namespace, title string) *dashv1.Dashboard { + return &dashv1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-dashboard", + Namespace: namespace, + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": title, + "schemaVersion": schemaversion.LATEST_VERSION, + // Variables with datasource reference that requires lookup + "templating": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{ + "name": "query_var", + "type": "query", + "query": "label_values(up, job)", + // Datasource with UID only - type needs to be looked up + "datasource": map[string]interface{}{ + "uid": "ds1", + // type is intentionally omitted to trigger provider lookup + }, + }, + }, + }, + "panels": []interface{}{ + map[string]interface{}{ + "id": 1, + "title": "Test Panel", + "type": "timeseries", + "targets": []interface{}{ + map[string]interface{}{ + // Datasource with UID only - type needs to be looked up + "datasource": map[string]interface{}{ + "uid": "ds1", + }, + }, + }, + }, + // Library panel reference - triggers library element provider lookup + map[string]interface{}{ + "id": 2, + "title": "Library Panel with Vertical Repeat", + "type": "library-panel-ref", + "gridPos": map[string]interface{}{ + "h": 4, + "w": 6, + "x": 0, + "y": 8, + }, + "libraryPanel": map[string]interface{}{ + "uid": "lib-panel-repeat-v", + "name": "Library Panel with Vertical Repeat", + }, + }, + // Another library panel reference + map[string]interface{}{ + "id": 3, + "title": "Library Panel without Repeat", + "type": "library-panel-ref", + "gridPos": map[string]interface{}{ + "h": 3, + "w": 6, + "x": 6, + "y": 8, + }, + "libraryPanel": map[string]interface{}{ + "uid": "lib-panel-no-repeat", + "name": "Library Panel without Repeat", + }, + }, + }, + }, + }, + } +} + +// TestConversionCaching_V0_to_V2alpha1 verifies caching works when converting V0 to V2alpha1 +func TestConversionCaching_V0_to_V2alpha1(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-h", Name: "Library Panel with Horizontal Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, time.Minute) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, time.Minute) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + // Convert multiple dashboards in the same namespace + numDashboards := 5 + namespace := "default" + + for i := 0; i < numDashboards; i++ { + source := createTestV0Dashboard(namespace, "Dashboard "+string(rune('A'+i))) + target := &dashv2alpha1.Dashboard{} + + err := Convert_V0_to_V2alpha1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion %d should succeed", i) + require.NotNil(t, target.Spec) + } + + // With caching, the underlying datasource provider should only be called once per namespace + // The test dashboard has datasources without type that require lookup + assert.Equal(t, int64(1), underlyingDS.getCallCount(), + "datasource provider should be called only once for %d conversions in same namespace", numDashboards) + // Library element provider should also be called only once per namespace due to caching + assert.Equal(t, int64(1), underlyingLE.getCallCount(), + "library element provider should be called only once for %d conversions in same namespace", numDashboards) +} + +// TestConversionCaching_V0_to_V2beta1 verifies caching works when converting V0 to V2beta1 +func TestConversionCaching_V0_to_V2beta1(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-h", Name: "Library Panel with Horizontal Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, time.Minute) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, time.Minute) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + numDashboards := 5 + namespace := "default" + + for i := 0; i < numDashboards; i++ { + source := createTestV0Dashboard(namespace, "Dashboard "+string(rune('A'+i))) + target := &dashv2beta1.Dashboard{} + + err := Convert_V0_to_V2beta1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion %d should succeed", i) + require.NotNil(t, target.Spec) + } + + assert.Equal(t, int64(1), underlyingDS.getCallCount(), + "datasource provider should be called only once for %d conversions in same namespace", numDashboards) + assert.Equal(t, int64(1), underlyingLE.getCallCount(), + "library element provider should be called only once for %d conversions in same namespace", numDashboards) +} + +// TestConversionCaching_V1beta1_to_V2alpha1 verifies caching works when converting V1beta1 to V2alpha1 +func TestConversionCaching_V1beta1_to_V2alpha1(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-v", Name: "Library Panel with Vertical Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, time.Minute) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, time.Minute) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + numDashboards := 5 + namespace := "default" + + for i := 0; i < numDashboards; i++ { + source := createTestV1Dashboard(namespace, "Dashboard "+string(rune('A'+i))) + target := &dashv2alpha1.Dashboard{} + + err := Convert_V1beta1_to_V2alpha1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion %d should succeed", i) + require.NotNil(t, target.Spec) + } + + assert.Equal(t, int64(1), underlyingDS.getCallCount(), + "datasource provider should be called only once for %d conversions in same namespace", numDashboards) + assert.Equal(t, int64(1), underlyingLE.getCallCount(), + "library element provider should be called only once for %d conversions in same namespace", numDashboards) +} + +// TestConversionCaching_V1beta1_to_V2beta1 verifies caching works when converting V1beta1 to V2beta1 +func TestConversionCaching_V1beta1_to_V2beta1(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-v", Name: "Library Panel with Vertical Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, time.Minute) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, time.Minute) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + numDashboards := 5 + namespace := "default" + + for i := 0; i < numDashboards; i++ { + source := createTestV1Dashboard(namespace, "Dashboard "+string(rune('A'+i))) + target := &dashv2beta1.Dashboard{} + + err := Convert_V1beta1_to_V2beta1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion %d should succeed", i) + require.NotNil(t, target.Spec) + } + + assert.Equal(t, int64(1), underlyingDS.getCallCount(), + "datasource provider should be called only once for %d conversions in same namespace", numDashboards) + assert.Equal(t, int64(1), underlyingLE.getCallCount(), + "library element provider should be called only once for %d conversions in same namespace", numDashboards) +} + +// TestConversionCaching_MultipleNamespaces verifies that different namespaces get separate cache entries +func TestConversionCaching_MultipleNamespaces(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-h", Name: "Library Panel with Horizontal Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, time.Minute) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, time.Minute) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + namespaces := []string{"default", "org-2", "org-3"} + numDashboardsPerNs := 3 + + for _, ns := range namespaces { + for i := 0; i < numDashboardsPerNs; i++ { + source := createTestV0Dashboard(ns, "Dashboard "+string(rune('A'+i))) + target := &dashv2alpha1.Dashboard{} + + err := Convert_V0_to_V2alpha1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion for namespace %s should succeed", ns) + } + } + + // With caching, each namespace should result in one call to the underlying provider + expectedCalls := int64(len(namespaces)) + assert.Equal(t, expectedCalls, underlyingDS.getCallCount(), + "datasource provider should be called once per namespace (%d namespaces)", len(namespaces)) + assert.Equal(t, expectedCalls, underlyingLE.getCallCount(), + "library element provider should be called once per namespace (%d namespaces)", len(namespaces)) +} + +// TestConversionCaching_CacheDisabled verifies that TTL=0 disables caching +func TestConversionCaching_CacheDisabled(t *testing.T) { + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + elements := []schemaversion.LibraryElementInfo{ + {UID: "lib-panel-repeat-h", Name: "Library Panel with Horizontal Repeat", Type: "timeseries"}, + {UID: "lib-panel-no-repeat", Name: "Library Panel without Repeat", Type: "graph"}, + } + + underlyingDS := newCountingDataSourceProvider(datasources) + underlyingLE := newCountingLibraryElementProvider(elements) + + // TTL of 0 should disable caching - the wrapper returns the underlying provider directly + cachedDS := schemaversion.WrapIndexProviderWithCache(underlyingDS, 0) + cachedLE := schemaversion.WrapLibraryElementProviderWithCache(underlyingLE, 0) + + migration.ResetForTesting() + migration.Initialize(cachedDS, cachedLE, migration.DefaultCacheTTL) + + numDashboards := 3 + namespace := "default" + + for i := 0; i < numDashboards; i++ { + source := createTestV0Dashboard(namespace, "Dashboard "+string(rune('A'+i))) + target := &dashv2alpha1.Dashboard{} + + err := Convert_V0_to_V2alpha1(source, target, nil, cachedDS, cachedLE) + require.NoError(t, err, "conversion %d should succeed", i) + } + + // Without caching, each conversion calls the underlying provider multiple times + // (once for each datasource lookup needed - variables and panels) + // The key check is that the count is GREATER than 1 per conversion (no caching benefit) + assert.Greater(t, underlyingDS.getCallCount(), int64(numDashboards), + "with cache disabled, conversions should call datasource provider multiple times") + // Library element provider is also called for each conversion without caching + assert.GreaterOrEqual(t, underlyingLE.getCallCount(), int64(numDashboards), + "with cache disabled, conversions should call library element provider multiple times") +} diff --git a/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection.go b/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection.go index 296a95ac054..db3353b66a1 100644 --- a/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection.go +++ b/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection.go @@ -4,8 +4,6 @@ import ( "errors" "fmt" - "k8s.io/apimachinery/pkg/conversion" - dashv0 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v0alpha1" dashv1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v1beta1" dashv2alpha1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v2alpha1" @@ -121,6 +119,14 @@ func countPanelsV0V1(spec map[string]interface{}) int { return count } +// countTargetsFromPanel counts the number of targets/queries in a panel. +func countTargetsFromPanel(panelMap map[string]interface{}) int { + if targets, ok := panelMap["targets"].([]interface{}); ok { + return len(targets) + } + return 0 +} + // countQueriesV0V1 counts data queries in v0alpha1 or v1beta1 dashboard spec // Note: Row panels are layout containers and should not have queries. // We ignore any queries on row panels themselves, but count queries in their collapsed panels. @@ -145,9 +151,7 @@ func countQueriesV0V1(spec map[string]interface{}) int { // Count queries in regular panels (NOT row panels) if panelType != "row" { - if targets, ok := panelMap["targets"].([]interface{}); ok { - count += len(targets) - } + count += countTargetsFromPanel(panelMap) } // Count queries in collapsed panels inside row panels @@ -155,9 +159,7 @@ func countQueriesV0V1(spec map[string]interface{}) int { if collapsedPanels, ok := panelMap["panels"].([]interface{}); ok { for _, cp := range collapsedPanels { if cpMap, ok := cp.(map[string]interface{}); ok { - if targets, ok := cpMap["targets"].([]interface{}); ok { - count += len(targets) - } + count += countTargetsFromPanel(cpMap) } } } @@ -442,77 +444,3 @@ func collectDashboardStats(dashboard interface{}) dashboardStats { } return dashboardStats{} } - -// withConversionDataLossDetection wraps a conversion function to detect data loss -func withConversionDataLossDetection(sourceFuncName, targetFuncName string, conversionFunc func(a, b interface{}, scope conversion.Scope) error) func(a, b interface{}, scope conversion.Scope) error { - return func(a, b interface{}, scope conversion.Scope) error { - // Collect source statistics - var sourceStats dashboardStats - switch source := a.(type) { - case *dashv0.Dashboard: - if source.Spec.Object != nil { - sourceStats = collectStatsV0V1(source.Spec.Object) - } - case *dashv1.Dashboard: - if source.Spec.Object != nil { - sourceStats = collectStatsV0V1(source.Spec.Object) - } - case *dashv2alpha1.Dashboard: - sourceStats = collectStatsV2alpha1(source.Spec) - case *dashv2beta1.Dashboard: - sourceStats = collectStatsV2beta1(source.Spec) - } - - // Execute the conversion - err := conversionFunc(a, b, scope) - if err != nil { - return err - } - - // Collect target statistics - var targetStats dashboardStats - switch target := b.(type) { - case *dashv0.Dashboard: - if target.Spec.Object != nil { - targetStats = collectStatsV0V1(target.Spec.Object) - } - case *dashv1.Dashboard: - if target.Spec.Object != nil { - targetStats = collectStatsV0V1(target.Spec.Object) - } - case *dashv2alpha1.Dashboard: - targetStats = collectStatsV2alpha1(target.Spec) - case *dashv2beta1.Dashboard: - targetStats = collectStatsV2beta1(target.Spec) - } - - // Detect if data was lost - if dataLossErr := detectConversionDataLoss(sourceStats, targetStats, sourceFuncName, targetFuncName); dataLossErr != nil { - logger.Error("Dashboard conversion data loss detected", - "sourceFunc", sourceFuncName, - "targetFunc", targetFuncName, - "sourcePanels", sourceStats.panelCount, - "targetPanels", targetStats.panelCount, - "sourceQueries", sourceStats.queryCount, - "targetQueries", targetStats.queryCount, - "sourceAnnotations", sourceStats.annotationCount, - "targetAnnotations", targetStats.annotationCount, - "sourceLinks", sourceStats.linkCount, - "targetLinks", targetStats.linkCount, - "error", dataLossErr, - ) - return dataLossErr - } - - logger.Debug("Dashboard conversion completed without data loss", - "sourceFunc", sourceFuncName, - "targetFunc", targetFuncName, - "panels", targetStats.panelCount, - "queries", targetStats.queryCount, - "annotations", targetStats.annotationCount, - "links", targetStats.linkCount, - ) - - return nil - } -} diff --git a/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection_test.go b/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection_test.go index f49305996f9..5c28c98b861 100644 --- a/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection_test.go +++ b/apps/dashboard/pkg/migration/conversion/conversion_data_loss_detection_test.go @@ -410,158 +410,167 @@ func TestCountPanelsV2(t *testing.T) { } func TestDetectConversionDataLoss(t *testing.T) { - tests := []struct { - name string - sourceStats dashboardStats - targetStats dashboardStats - expectError bool - errorMsg string - }{ - { - name: "perfect match - no data loss", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - variableCount: 2, + // Tests that expect NO error (no data loss) + t.Run("success cases", func(t *testing.T) { + successTests := []struct { + name string + sourceStats dashboardStats + targetStats dashboardStats + }{ + { + name: "perfect match - no data loss", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + variableCount: 2, + }, + targetStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + variableCount: 2, + }, }, - targetStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - variableCount: 2, + { + name: "panel count increased (allowed)", + sourceStats: dashboardStats{ + panelCount: 2, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, + targetStats: dashboardStats{ + panelCount: 3, // Added a panel (OK) + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, }, - expectError: false, - }, - { - name: "panel count decreased (data loss)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, + { + name: "annotation count increased (allowed - default annotations)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 0, + linkCount: 1, + }, + targetStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 1, // Added default annotation (OK) + linkCount: 1, + }, }, - targetStats: dashboardStats{ - panelCount: 2, // Lost a panel! - queryCount: 5, - annotationCount: 2, - linkCount: 1, - }, - expectError: true, - errorMsg: "panel count decreased", - }, - { - name: "panel count increased (allowed)", - sourceStats: dashboardStats{ - panelCount: 2, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - }, - targetStats: dashboardStats{ - panelCount: 3, // Added a panel (OK) - queryCount: 5, - annotationCount: 2, - linkCount: 1, - }, - expectError: false, - }, - { - name: "query count decreased (data loss)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - }, - targetStats: dashboardStats{ - panelCount: 3, - queryCount: 3, // Lost queries! - annotationCount: 2, - linkCount: 1, - }, - expectError: true, - errorMsg: "query count decreased", - }, - { - name: "annotation count decreased (data loss)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - }, - targetStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 1, // Lost annotation! - linkCount: 1, - }, - expectError: true, - errorMsg: "annotation count decreased", - }, - { - name: "annotation count increased (allowed - default annotations)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 0, - linkCount: 1, - }, - targetStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 1, // Added default annotation (OK) - linkCount: 1, - }, - expectError: false, - }, - { - name: "variable count decreased (data loss)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - variableCount: 3, - }, - targetStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - variableCount: 1, // Lost variables! - }, - expectError: true, - errorMsg: "variable count decreased", - }, - { - name: "multiple decreases (data loss)", - sourceStats: dashboardStats{ - panelCount: 3, - queryCount: 5, - annotationCount: 2, - linkCount: 1, - variableCount: 2, - }, - targetStats: dashboardStats{ - panelCount: 2, // Lost panel - queryCount: 3, // Lost queries - annotationCount: 2, - linkCount: 0, // Lost link - variableCount: 2, - }, - expectError: true, - errorMsg: "panel count decreased", - }, - } + } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := detectConversionDataLoss(tt.sourceStats, tt.targetStats, "TestSource", "TestTarget") - if tt.expectError { + for _, tt := range successTests { + t.Run(tt.name, func(t *testing.T) { + err := detectConversionDataLoss(tt.sourceStats, tt.targetStats, "TestSource", "TestTarget") + assert.NoError(t, err) + }) + } + }) + + // Tests that expect an error (data loss detected) + t.Run("data loss cases", func(t *testing.T) { + errorTests := []struct { + name string + sourceStats dashboardStats + targetStats dashboardStats + errorMsg string + }{ + { + name: "panel count decreased (data loss)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, + targetStats: dashboardStats{ + panelCount: 2, // Lost a panel! + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, + errorMsg: "panel count decreased", + }, + { + name: "query count decreased (data loss)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, + targetStats: dashboardStats{ + panelCount: 3, + queryCount: 3, // Lost queries! + annotationCount: 2, + linkCount: 1, + }, + errorMsg: "query count decreased", + }, + { + name: "annotation count decreased (data loss)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + }, + targetStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 1, // Lost annotation! + linkCount: 1, + }, + errorMsg: "annotation count decreased", + }, + { + name: "variable count decreased (data loss)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + variableCount: 3, + }, + targetStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + variableCount: 1, // Lost variables! + }, + errorMsg: "variable count decreased", + }, + { + name: "multiple decreases (data loss)", + sourceStats: dashboardStats{ + panelCount: 3, + queryCount: 5, + annotationCount: 2, + linkCount: 1, + variableCount: 2, + }, + targetStats: dashboardStats{ + panelCount: 2, // Lost panel + queryCount: 3, // Lost queries + annotationCount: 2, + linkCount: 0, // Lost link + variableCount: 2, + }, + errorMsg: "panel count decreased", + }, + } + + for _, tt := range errorTests { + t.Run(tt.name, func(t *testing.T) { + err := detectConversionDataLoss(tt.sourceStats, tt.targetStats, "TestSource", "TestTarget") require.Error(t, err) assert.Contains(t, err.Error(), tt.errorMsg) @@ -569,11 +578,9 @@ func TestDetectConversionDataLoss(t *testing.T) { var detectConversionDataLossErr *ConversionDataLossError require.ErrorAs(t, err, &detectConversionDataLossErr) assert.Equal(t, "TestSource_to_TestTarget", detectConversionDataLossErr.GetFunctionName()) - } else { - assert.NoError(t, err) - } - }) - } + }) + } + }) } func TestCollectStatsV0V1(t *testing.T) { @@ -687,140 +694,692 @@ func TestConversionDataLossError(t *testing.T) { assert.Equal(t, "data loss detected in TestFunc (v0alpha1 → v1beta1): test error message", err.Error()) } -// Integration test showing how validation works with actual dashboard types -func TestWithConversionValidation_Integration(t *testing.T) { - // Create a source dashboard (v0) with specific counts - sourceV0 := &dashv0.Dashboard{ - Spec: dashv0.DashboardSpec{ - Object: map[string]interface{}{ - "panels": []interface{}{ - map[string]interface{}{ - "id": float64(1), - "type": "graph", - "targets": []interface{}{ - map[string]interface{}{"refId": "A"}, - }, - }, - map[string]interface{}{ - "id": float64(2), - "type": "table", - "targets": []interface{}{ - map[string]interface{}{"refId": "A"}, - map[string]interface{}{"refId": "B"}, - }, - }, - }, - "annotations": map[string]interface{}{ - "list": []interface{}{ - map[string]interface{}{"name": "Annotation 1"}, - }, - }, - "links": []interface{}{ - map[string]interface{}{"title": "Link 1"}, - }, - }, - }, - } +// TestWithConversionMetrics_DataLossOnlyCheckedOnSuccess verifies that the +// withConversionMetrics wrapper only runs data loss detection when conversion succeeds. +func TestWithConversionMetrics_DataLossOnlyCheckedOnSuccess(t *testing.T) { + conversionError := errors.New("conversion failed") - // Create a target dashboard (v1) with matching counts - targetV1 := &dashv1.Dashboard{ - Spec: dashv1.DashboardSpec{ - Object: map[string]interface{}{ - "panels": []interface{}{ - map[string]interface{}{ - "id": float64(1), - "type": "graph", - "targets": []interface{}{ - map[string]interface{}{"refId": "A"}, - }, - }, - map[string]interface{}{ - "id": float64(2), - "type": "table", - "targets": []interface{}{ - map[string]interface{}{"refId": "A"}, - map[string]interface{}{"refId": "B"}, - }, - }, - }, - "annotations": map[string]interface{}{ - "list": []interface{}{ - map[string]interface{}{"name": "Annotation 1"}, - }, - }, - "links": []interface{}{ - map[string]interface{}{"title": "Link 1"}, - }, - }, - }, - } + // Test 1: Conversion fails - data loss should NOT be checked + t.Run("data loss not checked when conversion fails", func(t *testing.T) { + mockFailingConversion := func(a, b interface{}, scope conversion.Scope) error { + return conversionError + } - // Mock conversion function that just copies the spec - mockConversion := func(a, b interface{}, scope conversion.Scope) error { - source := a.(*dashv0.Dashboard) - target := b.(*dashv1.Dashboard) - target.Spec = dashv1.DashboardSpec{Object: source.Spec.Object} - return nil - } + wrappedFunc := withConversionMetrics(dashv0.APIVERSION, dashv1.APIVERSION, mockFailingConversion) - // Wrap with validation - validatedFunc := withConversionDataLossDetection("V0", "V1beta1", mockConversion) - - // This should pass validation - err := validatedFunc(sourceV0, targetV1, nil) - assert.NoError(t, err) -} - -func TestWithConversionValidation_DataLoss(t *testing.T) { - // Create a source dashboard (v0) with 2 panels - sourceV0 := &dashv0.Dashboard{ - Spec: dashv0.DashboardSpec{ - Object: map[string]interface{}{ - "panels": []interface{}{ - map[string]interface{}{ - "id": float64(1), - "type": "graph", + sourceV0 := &dashv0.Dashboard{ + Spec: dashv0.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{"id": float64(1), "type": "graph"}, + map[string]interface{}{"id": float64(2), "type": "table"}, }, - map[string]interface{}{ - "id": float64(2), - "type": "table", - }, - }, - }, - }, - } - - targetV1 := &dashv1.Dashboard{} - - // Mock conversion function that loses a panel - mockBadConversion := func(a, b interface{}, scope conversion.Scope) error { - target := b.(*dashv1.Dashboard) - // Only copy 1 panel instead of 2 - target.Spec = dashv1.DashboardSpec{ - Object: map[string]interface{}{ - "panels": []interface{}{ - map[string]interface{}{ - "id": float64(1), - "type": "graph", - }, - // Missing panel 2! }, }, } - return nil + targetV1 := &dashv1.Dashboard{} // Empty - would trigger data loss if checked + + // Execute - withConversionMetrics always returns nil to avoid 500s + err := wrappedFunc(sourceV0, targetV1, nil) + require.NoError(t, err, "withConversionMetrics should return nil even on conversion failure") + }) + + // Test 2: Conversion succeeds but data loss occurs - should detect data loss + t.Run("data loss detected when conversion succeeds but loses data", func(t *testing.T) { + mockDataLosingConversion := func(a, b interface{}, scope conversion.Scope) error { + // Conversion "succeeds" but loses a panel + target := b.(*dashv1.Dashboard) + target.Spec = dashv1.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + // Only 1 panel instead of 2 + map[string]interface{}{"id": float64(1), "type": "graph"}, + }, + }, + } + return nil + } + + wrappedFunc := withConversionMetrics(dashv0.APIVERSION, dashv1.APIVERSION, mockDataLosingConversion) + + sourceV0 := &dashv0.Dashboard{ + Spec: dashv0.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{"id": float64(1), "type": "graph"}, + map[string]interface{}{"id": float64(2), "type": "table"}, + }, + }, + }, + } + targetV1 := &dashv1.Dashboard{} + + // Execute - withConversionMetrics always returns nil + err := wrappedFunc(sourceV0, targetV1, nil) + require.NoError(t, err, "withConversionMetrics should return nil even on data loss") + + // The data loss is logged and recorded in metrics, but no error is returned to API server + }) +} + +// TestDataLossDetectionReturnsCorrectError verifies that when data loss is detected, +// a ConversionDataLossError is returned with proper function name and details. +func TestDataLossDetectionReturnsCorrectError(t *testing.T) { + t.Run("panel loss returns ConversionDataLossError", func(t *testing.T) { + sourceV0 := &dashv0.Dashboard{ + Spec: dashv0.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{"id": float64(1), "type": "graph"}, + map[string]interface{}{"id": float64(2), "type": "table"}, + }, + }, + }, + } + + targetV1 := &dashv1.Dashboard{ + Spec: dashv1.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + // Missing panel 2 + map[string]interface{}{"id": float64(1), "type": "graph"}, + }, + }, + }, + } + + err := checkConversionDataLoss(dashv0.APIVERSION, dashv1.APIVERSION, sourceV0, targetV1) + + require.Error(t, err) + var dataLossErr *ConversionDataLossError + require.ErrorAs(t, err, &dataLossErr) + assert.Equal(t, "V0_to_V1", dataLossErr.GetFunctionName()) + assert.Contains(t, err.Error(), "panel count decreased") + }) + + t.Run("query loss returns ConversionDataLossError", func(t *testing.T) { + sourceV0 := &dashv0.Dashboard{ + Spec: dashv0.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + map[string]interface{}{"refId": "B"}, + }, + }, + }, + }, + }, + } + + targetV1 := &dashv1.Dashboard{ + Spec: dashv1.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + // Missing query B + map[string]interface{}{"refId": "A"}, + }, + }, + }, + }, + }, + } + + err := checkConversionDataLoss(dashv0.APIVERSION, dashv1.APIVERSION, sourceV0, targetV1) + + require.Error(t, err) + var dataLossErr *ConversionDataLossError + require.ErrorAs(t, err, &dataLossErr) + assert.Contains(t, err.Error(), "query count decreased") + }) + + t.Run("no data loss returns nil", func(t *testing.T) { + sourceV0 := &dashv0.Dashboard{ + Spec: dashv0.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + }, + }, + }, + } + + targetV1 := &dashv1.Dashboard{ + Spec: dashv1.DashboardSpec{ + Object: map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + }, + }, + }, + } + + err := checkConversionDataLoss(dashv0.APIVERSION, dashv1.APIVERSION, sourceV0, targetV1) + + require.NoError(t, err) + }) +} + +// TestDataLossDetection_AllTypesAllVersions verifies that data loss is detected for +// all types of loss (panels, queries, annotations, links, variables) across all +// version permutations (v0alpha1, v1beta1, v2alpha1, v2beta1). +func TestDataLossDetection_AllTypesAllVersions(t *testing.T) { + // Helper to create v0/v1 unstructured spec with data + createV0V1SpecWithData := func() map[string]interface{} { + return map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + map[string]interface{}{"refId": "B"}, + }, + }, + map[string]interface{}{ + "id": float64(2), + "type": "table", + "targets": []interface{}{ + map[string]interface{}{"refId": "C"}, + }, + }, + }, + "annotations": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "Annotation 1"}, + map[string]interface{}{"name": "Annotation 2"}, + }, + }, + "links": []interface{}{ + map[string]interface{}{"title": "Link 1"}, + map[string]interface{}{"title": "Link 2"}, + }, + "templating": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "var1", "type": "query"}, + map[string]interface{}{"name": "var2", "type": "custom"}, + }, + }, + } } - // Wrap with data loss detection - validatedFunc := withConversionDataLossDetection("V0", "V1beta1", mockBadConversion) + // Helper to create v0/v1 unstructured spec with data loss (missing items) + createV0V1SpecWithLoss := func(lossType string) map[string]interface{} { + spec := createV0V1SpecWithData() + switch lossType { + case "panel": + spec["panels"] = []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + map[string]interface{}{"refId": "B"}, + }, + }, + // Missing panel 2 + } + case "query": + spec["panels"] = []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + // Missing query B + }, + }, + map[string]interface{}{ + "id": float64(2), + "type": "table", + "targets": []interface{}{ + map[string]interface{}{"refId": "C"}, + }, + }, + } + case "annotation": + spec["annotations"] = map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "Annotation 1"}, + // Missing annotation 2 + }, + } + case "link": + spec["links"] = []interface{}{ + map[string]interface{}{"title": "Link 1"}, + // Missing link 2 + } + case "variable": + spec["templating"] = map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "var1", "type": "query"}, + // Missing var2 + }, + } + } + return spec + } - // This should fail due to data loss - err := validatedFunc(sourceV0, targetV1, nil) - require.Error(t, err) - assert.Contains(t, err.Error(), "panel count decreased") + // Helper to create v2alpha1 dashboard with data + createV2alpha1WithData := func() *dashv2alpha1.Dashboard { + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: map[string]dashv2alpha1.DashboardElement{ + "panel1": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 1, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "B"}}, + }, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 2, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "C"}}, + }, + }, + }, + }, + }, + }, + }, + Annotations: []dashv2alpha1.DashboardAnnotationQueryKind{{}, {}}, + Links: []dashv2alpha1.DashboardDashboardLink{{}, {}}, + Variables: []dashv2alpha1.DashboardVariableKind{{}, {}}, + }, + } + } - var detectConversionDataLossErr *ConversionDataLossError - require.ErrorAs(t, err, &detectConversionDataLossErr) - assert.Equal(t, "V0_to_V1beta1", detectConversionDataLossErr.GetFunctionName()) + // Helper to create v2alpha1 dashboard with data loss + createV2alpha1WithLoss := func(lossType string) *dashv2alpha1.Dashboard { + dash := createV2alpha1WithData() + switch lossType { + case "panel": + delete(dash.Spec.Elements, "panel2") + case "query": + dash.Spec.Elements["panel1"].PanelKind.Spec.Data.Spec.Queries = []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + // Missing query B + } + case "annotation": + dash.Spec.Annotations = []dashv2alpha1.DashboardAnnotationQueryKind{{}} + case "link": + dash.Spec.Links = []dashv2alpha1.DashboardDashboardLink{{}} + case "variable": + dash.Spec.Variables = []dashv2alpha1.DashboardVariableKind{{}} + } + return dash + } + + // Helper to create v2beta1 dashboard with data + createV2beta1WithData := func() *dashv2beta1.Dashboard { + return &dashv2beta1.Dashboard{ + Spec: dashv2beta1.DashboardSpec{ + Elements: map[string]dashv2beta1.DashboardElement{ + "panel1": { + PanelKind: &dashv2beta1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2beta1.DashboardPanelSpec{ + Id: 1, + Data: dashv2beta1.DashboardQueryGroupKind{ + Spec: dashv2beta1.DashboardQueryGroupSpec{ + Queries: []dashv2beta1.DashboardPanelQueryKind{ + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "A"}}, + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "B"}}, + }, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2beta1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2beta1.DashboardPanelSpec{ + Id: 2, + Data: dashv2beta1.DashboardQueryGroupKind{ + Spec: dashv2beta1.DashboardQueryGroupSpec{ + Queries: []dashv2beta1.DashboardPanelQueryKind{ + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "C"}}, + }, + }, + }, + }, + }, + }, + }, + Annotations: []dashv2beta1.DashboardAnnotationQueryKind{{}, {}}, + Links: []dashv2beta1.DashboardDashboardLink{{}, {}}, + Variables: []dashv2beta1.DashboardVariableKind{{}, {}}, + }, + } + } + + // Helper to create v2beta1 dashboard with data loss + createV2beta1WithLoss := func(lossType string) *dashv2beta1.Dashboard { + dash := createV2beta1WithData() + switch lossType { + case "panel": + delete(dash.Spec.Elements, "panel2") + case "query": + dash.Spec.Elements["panel1"].PanelKind.Spec.Data.Spec.Queries = []dashv2beta1.DashboardPanelQueryKind{ + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "A"}}, + // Missing query B + } + case "annotation": + dash.Spec.Annotations = []dashv2beta1.DashboardAnnotationQueryKind{{}} + case "link": + dash.Spec.Links = []dashv2beta1.DashboardDashboardLink{{}} + case "variable": + dash.Spec.Variables = []dashv2beta1.DashboardVariableKind{{}} + } + return dash + } + + // All loss types to test + lossTypes := []struct { + name string + expectedErrMsg string + }{ + {"panel", "panel count decreased"}, + {"query", "query count decreased"}, + {"annotation", "annotation count decreased"}, + {"link", "link count decreased"}, + {"variable", "variable count decreased"}, + } + + // All version permutations (12 total: 4 versions × 3 targets each) + versionPairs := []struct { + sourceVersion string + targetVersion string + sourceAPI string + targetAPI string + }{ + // From v0alpha1 + {"v0alpha1", "v1beta1", dashv0.APIVERSION, dashv1.APIVERSION}, + {"v0alpha1", "v2alpha1", dashv0.APIVERSION, dashv2alpha1.APIVERSION}, + {"v0alpha1", "v2beta1", dashv0.APIVERSION, dashv2beta1.APIVERSION}, + // From v1beta1 + {"v1beta1", "v0alpha1", dashv1.APIVERSION, dashv0.APIVERSION}, + {"v1beta1", "v2alpha1", dashv1.APIVERSION, dashv2alpha1.APIVERSION}, + {"v1beta1", "v2beta1", dashv1.APIVERSION, dashv2beta1.APIVERSION}, + // From v2alpha1 + {"v2alpha1", "v0alpha1", dashv2alpha1.APIVERSION, dashv0.APIVERSION}, + {"v2alpha1", "v1beta1", dashv2alpha1.APIVERSION, dashv1.APIVERSION}, + {"v2alpha1", "v2beta1", dashv2alpha1.APIVERSION, dashv2beta1.APIVERSION}, + // From v2beta1 + {"v2beta1", "v0alpha1", dashv2beta1.APIVERSION, dashv0.APIVERSION}, + {"v2beta1", "v1beta1", dashv2beta1.APIVERSION, dashv1.APIVERSION}, + {"v2beta1", "v2alpha1", dashv2beta1.APIVERSION, dashv2alpha1.APIVERSION}, + } + + for _, vp := range versionPairs { + for _, lt := range lossTypes { + testName := fmt.Sprintf("%s_to_%s_%s_loss", vp.sourceVersion, vp.targetVersion, lt.name) + t.Run(testName, func(t *testing.T) { + var source, target interface{} + + // Create source dashboard with full data + switch vp.sourceVersion { + case "v0alpha1": + source = &dashv0.Dashboard{Spec: dashv0.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v1beta1": + source = &dashv1.Dashboard{Spec: dashv1.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v2alpha1": + source = createV2alpha1WithData() + case "v2beta1": + source = createV2beta1WithData() + } + + // Create target dashboard with data loss + switch vp.targetVersion { + case "v0alpha1": + target = &dashv0.Dashboard{Spec: dashv0.DashboardSpec{Object: createV0V1SpecWithLoss(lt.name)}} + case "v1beta1": + target = &dashv1.Dashboard{Spec: dashv1.DashboardSpec{Object: createV0V1SpecWithLoss(lt.name)}} + case "v2alpha1": + target = createV2alpha1WithLoss(lt.name) + case "v2beta1": + target = createV2beta1WithLoss(lt.name) + } + + // Check for data loss + err := checkConversionDataLoss(vp.sourceAPI, vp.targetAPI, source, target) + + // Verify data loss was detected + require.Error(t, err, "Expected %s loss to be detected for %s -> %s", lt.name, vp.sourceVersion, vp.targetVersion) + assert.Contains(t, err.Error(), lt.expectedErrMsg) + + // Verify it's a ConversionDataLossError + var dataLossErr *ConversionDataLossError + require.ErrorAs(t, err, &dataLossErr) + }) + } + } +} + +// TestDataLossDetection_NoFalsePositives_AllVersionPermutations verifies that no false positives +// are triggered for any attribute type when counts are equal or increased, across ALL version permutations. +func TestDataLossDetection_NoFalsePositives_AllVersionPermutations(t *testing.T) { + // Helper to create v0/v1 spec with data + createV0V1SpecWithData := func() map[string]interface{} { + return map[string]interface{}{ + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(1), + "type": "graph", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + map[string]interface{}{"refId": "B"}, + }, + }, + map[string]interface{}{ + "id": float64(2), + "type": "table", + "targets": []interface{}{ + map[string]interface{}{"refId": "C"}, + }, + }, + }, + "annotations": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "Annotation 1"}, + map[string]interface{}{"name": "Annotation 2"}, + }, + }, + "links": []interface{}{ + map[string]interface{}{"title": "Link 1"}, + map[string]interface{}{"title": "Link 2"}, + }, + "templating": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{"name": "var1", "type": "query"}, + map[string]interface{}{"name": "var2", "type": "custom"}, + }, + }, + } + } + + // Helper to create v2alpha1 dashboard with data + createV2alpha1WithData := func() *dashv2alpha1.Dashboard { + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: map[string]dashv2alpha1.DashboardElement{ + "panel1": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 1, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "B"}}, + }, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 2, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "C"}}, + }, + }, + }, + }, + }, + }, + }, + Annotations: []dashv2alpha1.DashboardAnnotationQueryKind{{}, {}}, + Links: []dashv2alpha1.DashboardDashboardLink{{}, {}}, + Variables: []dashv2alpha1.DashboardVariableKind{{}, {}}, + }, + } + } + + // Helper to create v2beta1 dashboard with data + createV2beta1WithData := func() *dashv2beta1.Dashboard { + return &dashv2beta1.Dashboard{ + Spec: dashv2beta1.DashboardSpec{ + Elements: map[string]dashv2beta1.DashboardElement{ + "panel1": { + PanelKind: &dashv2beta1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2beta1.DashboardPanelSpec{ + Id: 1, + Data: dashv2beta1.DashboardQueryGroupKind{ + Spec: dashv2beta1.DashboardQueryGroupSpec{ + Queries: []dashv2beta1.DashboardPanelQueryKind{ + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "A"}}, + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "B"}}, + }, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2beta1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2beta1.DashboardPanelSpec{ + Id: 2, + Data: dashv2beta1.DashboardQueryGroupKind{ + Spec: dashv2beta1.DashboardQueryGroupSpec{ + Queries: []dashv2beta1.DashboardPanelQueryKind{ + {Spec: dashv2beta1.DashboardPanelQuerySpec{RefId: "C"}}, + }, + }, + }, + }, + }, + }, + }, + Annotations: []dashv2beta1.DashboardAnnotationQueryKind{{}, {}}, + Links: []dashv2beta1.DashboardDashboardLink{{}, {}}, + Variables: []dashv2beta1.DashboardVariableKind{{}, {}}, + }, + } + } + + // All 12 version permutations + versionPairs := []struct { + sourceVersion string + targetVersion string + sourceAPI string + targetAPI string + }{ + // From v0alpha1 + {"v0alpha1", "v1beta1", dashv0.APIVERSION, dashv1.APIVERSION}, + {"v0alpha1", "v2alpha1", dashv0.APIVERSION, dashv2alpha1.APIVERSION}, + {"v0alpha1", "v2beta1", dashv0.APIVERSION, dashv2beta1.APIVERSION}, + // From v1beta1 + {"v1beta1", "v0alpha1", dashv1.APIVERSION, dashv0.APIVERSION}, + {"v1beta1", "v2alpha1", dashv1.APIVERSION, dashv2alpha1.APIVERSION}, + {"v1beta1", "v2beta1", dashv1.APIVERSION, dashv2beta1.APIVERSION}, + // From v2alpha1 + {"v2alpha1", "v0alpha1", dashv2alpha1.APIVERSION, dashv0.APIVERSION}, + {"v2alpha1", "v1beta1", dashv2alpha1.APIVERSION, dashv1.APIVERSION}, + {"v2alpha1", "v2beta1", dashv2alpha1.APIVERSION, dashv2beta1.APIVERSION}, + // From v2beta1 + {"v2beta1", "v0alpha1", dashv2beta1.APIVERSION, dashv0.APIVERSION}, + {"v2beta1", "v1beta1", dashv2beta1.APIVERSION, dashv1.APIVERSION}, + {"v2beta1", "v2alpha1", dashv2beta1.APIVERSION, dashv2alpha1.APIVERSION}, + } + + for _, vp := range versionPairs { + testName := fmt.Sprintf("%s_to_%s_no_loss", vp.sourceVersion, vp.targetVersion) + t.Run(testName, func(t *testing.T) { + var source, target interface{} + + // Create source dashboard with full data + switch vp.sourceVersion { + case "v0alpha1": + source = &dashv0.Dashboard{Spec: dashv0.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v1beta1": + source = &dashv1.Dashboard{Spec: dashv1.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v2alpha1": + source = createV2alpha1WithData() + case "v2beta1": + source = createV2beta1WithData() + } + + // Create target dashboard with same data (no loss) + switch vp.targetVersion { + case "v0alpha1": + target = &dashv0.Dashboard{Spec: dashv0.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v1beta1": + target = &dashv1.Dashboard{Spec: dashv1.DashboardSpec{Object: createV0V1SpecWithData()}} + case "v2alpha1": + target = createV2alpha1WithData() + case "v2beta1": + target = createV2beta1WithData() + } + + // Check for data loss - should be none + err := checkConversionDataLoss(vp.sourceAPI, vp.targetAPI, source, target) + require.NoError(t, err, "Expected no data loss when data is preserved for %s -> %s", vp.sourceVersion, vp.targetVersion) + }) + } } // TestDataLossDetectionOnAllInputFiles tests all conversions from testdata/input @@ -829,7 +1388,7 @@ func TestDataLossDetectionOnAllInputFiles(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := testutil.NewDataSourceProvider(testutil.StandardTestConfig) leProvider := testutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -1359,3 +1918,1148 @@ func extractQueryInfoV2beta1(spec dashv2beta1.DashboardSpec) []queryInfo { return queries } + +// TestDataLossDetection_IntegrationWithRealConversions performs actual conversions +// using the scheme and verifies that data loss detection works correctly. +func TestDataLossDetection_IntegrationWithRealConversions(t *testing.T) { + // Initialize the migrator with a test data source provider + dsProvider := testutil.NewDataSourceProvider(testutil.StandardTestConfig) + leProvider := testutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Set up conversion scheme + scheme := runtime.NewScheme() + err := RegisterConversions(scheme, dsProvider, leProvider) + require.NoError(t, err) + + // + // ========== V0/V1 -> V2 CONVERSIONS (These should all pass) ========== + // + + // Test 1: V0 Collapsed Rows -> V2alpha1 + t.Run("Integration_V0CollapsedRows_To_V2alpha1", func(t *testing.T) { + source := &dashv0.Dashboard{ + TypeMeta: metav1.TypeMeta{ + APIVersion: dashv0.APIVERSION, + Kind: "Dashboard", + }, + Spec: dashv0.DashboardSpec{ + Object: createV0V1WithCollapsedRows(2, 2, 1), + }, + } + sourceStats := collectStatsV0V1(source.Spec.Object) + + target := &dashv2alpha1.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV2alpha1(target.Spec) + + t.Logf("V0 Collapsed Rows -> V2alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 2: V0 Expanded Rows -> V2alpha1 + t.Run("Integration_V0ExpandedRows_To_V2alpha1", func(t *testing.T) { + source := &dashv0.Dashboard{ + TypeMeta: metav1.TypeMeta{ + APIVersion: dashv0.APIVERSION, + Kind: "Dashboard", + }, + Spec: dashv0.DashboardSpec{ + Object: createV0V1WithExpandedRows(2, 2, 1), + }, + } + sourceStats := collectStatsV0V1(source.Spec.Object) + + target := &dashv2alpha1.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV2alpha1(target.Spec) + + t.Logf("V0 Expanded Rows -> V2alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 3: V0 Flat Panels -> V2alpha1 + t.Run("Integration_V0FlatPanels_To_V2alpha1", func(t *testing.T) { + source := &dashv0.Dashboard{ + TypeMeta: metav1.TypeMeta{ + APIVersion: dashv0.APIVERSION, + Kind: "Dashboard", + }, + Spec: dashv0.DashboardSpec{ + Object: createV0V1FlatPanels(4, 1), + }, + } + sourceStats := collectStatsV0V1(source.Spec.Object) + + target := &dashv2alpha1.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV2alpha1(target.Spec) + + t.Logf("V0 Flat Panels -> V2alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 4: V0 Mixed Layout -> V2alpha1 + t.Run("Integration_V0MixedLayout_To_V2alpha1", func(t *testing.T) { + source := &dashv0.Dashboard{ + TypeMeta: metav1.TypeMeta{ + APIVersion: dashv0.APIVERSION, + Kind: "Dashboard", + }, + Spec: dashv0.DashboardSpec{ + Object: createV0V1MixedAllTypes(), + }, + } + sourceStats := collectStatsV0V1(source.Spec.Object) + + target := &dashv2alpha1.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV2alpha1(target.Spec) + + t.Logf("V0 Mixed Layout -> V2alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // + // ========== V2 -> V0/V1 CONVERSIONS ========== + // These tests document the current state of V2 -> V0 conversions. + // + + // Test 5: V2 Simple Tabs -> V0alpha1 + t.Run("Integration_V2SimpleTabs_To_V0alpha1", func(t *testing.T) { + source := createV2DashboardWithSimpleTabs() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Simple Tabs -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 6: V2 Rows Collapsed -> V0alpha1 + t.Run("Integration_V2RowsCollapsed_To_V0alpha1", func(t *testing.T) { + source := createV2DashboardWithRowsCollapsed() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Rows Collapsed -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 7: V2 Rows Expanded -> V0alpha1 + t.Run("Integration_V2RowsExpanded_To_V0alpha1", func(t *testing.T) { + source := createV2DashboardWithRowsExpanded() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Rows Expanded -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 8: V2 Tabs with Nested Rows -> V0alpha1 + t.Run("Integration_V2TabsWithNestedRows_To_V0alpha1", func(t *testing.T) { + source := createV2DashboardWithTabsAndNestedRows() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Tabs with Nested Rows -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 9: V2 Rows with Nested Tabs -> V0alpha1 + t.Run("Integration_V2RowsWithNestedTabs_To_V0alpha1", func(t *testing.T) { + source := createV2DashboardWithRowsAndNestedTabs() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Rows with Nested Tabs -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // Test 10: V2 Complex Nesting -> V0alpha1 + t.Run("Integration_V2ComplexNesting_To_V0alpha1", func(t *testing.T) { + source := createV2ComplexNestedDashboard() + source.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + sourceStats := collectStatsV2alpha1(source.Spec) + + target := &dashv0.Dashboard{} + err := scheme.Convert(source, target, nil) + require.NoError(t, err, "Conversion should succeed") + + targetStats := collectStatsV0V1(target.Spec.Object) + + t.Logf("V2 Complex Nesting -> V0alpha1:") + t.Logf(" Source: panels=%d, queries=%d", sourceStats.panelCount, sourceStats.queryCount) + t.Logf(" Target: panels=%d, queries=%d", targetStats.panelCount, targetStats.queryCount) + + assert.Equal(t, sourceStats.panelCount, targetStats.panelCount, "Panel count should match") + assert.Equal(t, sourceStats.queryCount, targetStats.queryCount, "Query count should match") + }) + + // + // ========== ROUND-TRIP CONVERSIONS ========== + // + + // Test 11: V2 -> V0 -> V2 round-trip (panel count should be preserved) + t.Run("Integration_RoundTrip_V2_V0_V2", func(t *testing.T) { + original := createV2DashboardWithSimpleTabs() + original.TypeMeta = metav1.TypeMeta{ + APIVersion: dashv2alpha1.APIVERSION, + Kind: "Dashboard", + } + originalStats := collectStatsV2alpha1(original.Spec) + + // V2 -> V0 + intermediate := &dashv0.Dashboard{} + err := scheme.Convert(original, intermediate, nil) + require.NoError(t, err, "V2 -> V0 conversion should succeed") + intermediateStats := collectStatsV0V1(intermediate.Spec.Object) + + // V0 -> V2 + final := &dashv2alpha1.Dashboard{} + err = scheme.Convert(intermediate, final, nil) + require.NoError(t, err, "V0 -> V2 conversion should succeed") + finalStats := collectStatsV2alpha1(final.Spec) + + t.Logf("Round-trip V2 -> V0 -> V2:") + t.Logf(" Original (V2): panels=%d, queries=%d", originalStats.panelCount, originalStats.queryCount) + t.Logf(" Intermediate (V0): panels=%d, queries=%d", intermediateStats.panelCount, intermediateStats.queryCount) + t.Logf(" Final (V2): panels=%d, queries=%d", finalStats.panelCount, finalStats.queryCount) + + // Panel count should be preserved through round-trip + assert.Equal(t, originalStats.panelCount, finalStats.panelCount, "Panel count should match after round-trip") + + // Document query behavior + if intermediateStats.queryCount < originalStats.queryCount { + t.Logf(" ⚠️ Queries lost in V2->V0: %d -> %d", originalStats.queryCount, intermediateStats.queryCount) + } + if finalStats.queryCount != originalStats.queryCount { + t.Logf(" ⚠️ Final query count differs: original=%d, final=%d", originalStats.queryCount, finalStats.queryCount) + } + }) + + // Test 12: V0 -> V2 -> V0 round-trip + t.Run("Integration_RoundTrip_V0_V2_V0", func(t *testing.T) { + original := &dashv0.Dashboard{ + TypeMeta: metav1.TypeMeta{ + APIVersion: dashv0.APIVERSION, + Kind: "Dashboard", + }, + Spec: dashv0.DashboardSpec{ + Object: createV0V1MixedAllTypes(), + }, + } + originalStats := collectStatsV0V1(original.Spec.Object) + + // V0 -> V2 + intermediate := &dashv2alpha1.Dashboard{} + err := scheme.Convert(original, intermediate, nil) + require.NoError(t, err, "V0 -> V2 conversion should succeed") + intermediateStats := collectStatsV2alpha1(intermediate.Spec) + + // V2 -> V0 + final := &dashv0.Dashboard{} + err = scheme.Convert(intermediate, final, nil) + require.NoError(t, err, "V2 -> V0 conversion should succeed") + finalStats := collectStatsV0V1(final.Spec.Object) + + t.Logf("Round-trip V0 -> V2 -> V0:") + t.Logf(" Original (V0): panels=%d, queries=%d", originalStats.panelCount, originalStats.queryCount) + t.Logf(" Intermediate (V2): panels=%d, queries=%d", intermediateStats.panelCount, intermediateStats.queryCount) + t.Logf(" Final (V0): panels=%d, queries=%d", finalStats.panelCount, finalStats.queryCount) + + // V0 -> V2 should preserve everything + assert.Equal(t, originalStats.panelCount, intermediateStats.panelCount, "V0->V2 should preserve panels") + assert.Equal(t, originalStats.queryCount, intermediateStats.queryCount, "V0->V2 should preserve queries") + + // Document what happens in V2 -> V0 + assert.Equal(t, originalStats.panelCount, finalStats.panelCount, "Panel count should match after round-trip") + + if finalStats.queryCount < originalStats.queryCount { + t.Logf(" ⚠️ Queries lost in V2->V0 leg: %d -> %d", intermediateStats.queryCount, finalStats.queryCount) + } + }) +} + +// Helper functions to create test dashboards + +// ========== V2 Dashboard Fixtures ========== + +// createV2DashboardWithSimpleTabs creates a V2 dashboard with simple TabsLayout +// Structure: TabsLayout > Tab1[panel1, panel2] + Tab2[panel3, panel4] +func createV2DashboardWithSimpleTabs() *dashv2alpha1.Dashboard { + elements := map[string]dashv2alpha1.DashboardElement{} + for i := 1; i <= 4; i++ { + tabNum := (i-1)/2 + 1 + elements[fmt.Sprintf("panel%d", i)] = dashv2alpha1.DashboardElement{ + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: float64(i), + Title: fmt.Sprintf("Panel %d - Tab %d", i, tabNum), + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + }, + }, + }, + }, + }, + } + } + + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + TabsLayoutKind: &dashv2alpha1.DashboardTabsLayoutKind{ + Kind: "TabsLayout", + Spec: dashv2alpha1.DashboardTabsLayoutSpec{ + Tabs: []dashv2alpha1.DashboardTabsLayoutTabKind{ + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 2"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +// createV2DashboardWithRowsCollapsed creates a V2 dashboard with RowsLayout (collapsed rows) +// Structure: RowsLayout > Row1(collapsed)[panel1, panel2] + Row2(collapsed)[panel3, panel4] +func createV2DashboardWithRowsCollapsed() *dashv2alpha1.Dashboard { + elements := map[string]dashv2alpha1.DashboardElement{} + for i := 1; i <= 4; i++ { + rowNum := (i-1)/2 + 1 + elements[fmt.Sprintf("panel%d", i)] = dashv2alpha1.DashboardElement{ + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: float64(i), + Title: fmt.Sprintf("Panel %d - Row %d (collapsed)", i, rowNum), + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + }, + }, + }, + }, + }, + } + } + + collapsed := true + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1 (collapsed)"), + Collapse: &collapsed, + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 2 (collapsed)"), + Collapse: &collapsed, + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +// createV2DashboardWithRowsExpanded creates a V2 dashboard with RowsLayout (expanded rows) +// Structure: RowsLayout > Row1(expanded)[panel1, panel2] + Row2(expanded)[panel3, panel4] +func createV2DashboardWithRowsExpanded() *dashv2alpha1.Dashboard { + elements := map[string]dashv2alpha1.DashboardElement{} + for i := 1; i <= 4; i++ { + rowNum := (i-1)/2 + 1 + elements[fmt.Sprintf("panel%d", i)] = dashv2alpha1.DashboardElement{ + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: float64(i), + Title: fmt.Sprintf("Panel %d - Row %d (expanded)", i, rowNum), + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{ + {Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}, + }, + }, + }, + }, + }, + } + } + + expanded := false // collapse=false means expanded + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1 (expanded)"), + Collapse: &expanded, + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 2 (expanded)"), + Collapse: &expanded, + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func createV0V1FlatPanels(numPanels, queriesPerPanel int) map[string]interface{} { + panels := make([]interface{}, numPanels) + for i := 0; i < numPanels; i++ { + targets := make([]interface{}, queriesPerPanel) + for q := 0; q < queriesPerPanel; q++ { + targets[q] = map[string]interface{}{"refId": fmt.Sprintf("%c", 'A'+q)} + } + panels[i] = map[string]interface{}{ + "id": float64(i + 1), + "title": fmt.Sprintf("Panel %d", i+1), + "type": "timeseries", + "targets": targets, + } + } + return map[string]interface{}{"panels": panels} +} + +func createV0V1WithCollapsedRows(numRows, panelsPerRow, queriesPerPanel int) map[string]interface{} { + panels := make([]interface{}, 0) + panelID := 1 + + for r := 0; r < numRows; r++ { + // Create collapsed panels for this row + collapsedPanels := make([]interface{}, panelsPerRow) + for p := 0; p < panelsPerRow; p++ { + targets := make([]interface{}, queriesPerPanel) + for q := 0; q < queriesPerPanel; q++ { + targets[q] = map[string]interface{}{"refId": fmt.Sprintf("%c", 'A'+q)} + } + collapsedPanels[p] = map[string]interface{}{ + "id": float64(panelID), + "title": fmt.Sprintf("Panel %d (in Row %d)", panelID, r+1), + "type": "timeseries", + "targets": targets, + } + panelID++ + } + + // Add row with collapsed panels + panels = append(panels, map[string]interface{}{ + "id": float64(100 + r), + "title": fmt.Sprintf("Row %d (collapsed)", r+1), + "type": "row", + "collapsed": true, + "panels": collapsedPanels, + }) + } + return map[string]interface{}{"panels": panels} +} + +func createV0V1WithExpandedRows(numRows, panelsPerRow, queriesPerPanel int) map[string]interface{} { + panels := make([]interface{}, 0) + panelID := 1 + + for r := 0; r < numRows; r++ { + // Add expanded row (no nested panels) + panels = append(panels, map[string]interface{}{ + "id": float64(100 + r), + "title": fmt.Sprintf("Row %d (expanded)", r+1), + "type": "row", + // No "panels" field when row is expanded + }) + + // Add panels after the row + for p := 0; p < panelsPerRow; p++ { + targets := make([]interface{}, queriesPerPanel) + for q := 0; q < queriesPerPanel; q++ { + targets[q] = map[string]interface{}{"refId": fmt.Sprintf("%c", 'A'+q)} + } + panels = append(panels, map[string]interface{}{ + "id": float64(panelID), + "title": fmt.Sprintf("Panel %d (after Row %d)", panelID, r+1), + "type": "timeseries", + "targets": targets, + }) + panelID++ + } + } + return map[string]interface{}{"panels": panels} +} + +func createV2DashboardWithTabsAndNestedRows() *dashv2alpha1.Dashboard { + // 2 tabs, each with 1 row containing 2 panels = 4 panels total + // Structure: TabsLayout > Tab1[RowsLayout > Row[panel1, panel2]] + Tab2[RowsLayout > Row[panel3, panel4]] + elements := map[string]dashv2alpha1.DashboardElement{ + "panel1": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 1, Title: "Panel 1 - Tab1/Row1", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 2, Title: "Panel 2 - Tab1/Row1", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "stat"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel3": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 3, Title: "Panel 3 - Tab2/Row1", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "gauge"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel4": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 4, Title: "Panel 4 - Tab2/Row1", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "table"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + } + + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + TabsLayoutKind: &dashv2alpha1.DashboardTabsLayoutKind{ + Kind: "TabsLayout", + Spec: dashv2alpha1.DashboardTabsLayoutSpec{ + Tabs: []dashv2alpha1.DashboardTabsLayoutTabKind{ + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 2"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func createV2DashboardWithRowsAndNestedTabs() *dashv2alpha1.Dashboard { + // 2 rows, each containing a tab layout with 2 panels = 4 panels total + // Structure: RowsLayout > Row1[TabsLayout > Tab[panel1, panel2]] + Row2[TabsLayout > Tab[panel3, panel4]] + elements := map[string]dashv2alpha1.DashboardElement{ + "panel1": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 1, Title: "Panel 1 - Row1/TabA", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel2": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 2, Title: "Panel 2 - Row1/TabB", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "stat"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel3": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 3, Title: "Panel 3 - Row2/TabA", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "gauge"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + "panel4": { + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: 4, Title: "Panel 4 - Row2/TabB", + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "table"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + }, + } + + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + TabsLayoutKind: &dashv2alpha1.DashboardTabsLayoutKind{ + Kind: "TabsLayout", + Spec: dashv2alpha1.DashboardTabsLayoutSpec{ + Tabs: []dashv2alpha1.DashboardTabsLayoutTabKind{ + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab A"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 2"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + TabsLayoutKind: &dashv2alpha1.DashboardTabsLayoutKind{ + Kind: "TabsLayout", + Spec: dashv2alpha1.DashboardTabsLayoutSpec{ + Tabs: []dashv2alpha1.DashboardTabsLayoutTabKind{ + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab A"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +func createV2ComplexNestedDashboard() *dashv2alpha1.Dashboard { + // Complex: 2 tabs, Tab1 has 2 rows (each with 2 panels), Tab2 has 2 panels directly + // Total: 6 panels + // Structure: TabsLayout > Tab1[RowsLayout > Row1[p1,p2] + Row2[p3,p4]] + Tab2[GridLayout > p5,p6] + elements := map[string]dashv2alpha1.DashboardElement{} + for i := 1; i <= 6; i++ { + elements[fmt.Sprintf("panel%d", i)] = dashv2alpha1.DashboardElement{ + PanelKind: &dashv2alpha1.DashboardPanelKind{ + Kind: "Panel", + Spec: dashv2alpha1.DashboardPanelSpec{ + Id: float64(i), + Title: fmt.Sprintf("Panel %d", i), + VizConfig: dashv2alpha1.DashboardVizConfigKind{Kind: "timeseries"}, + Data: dashv2alpha1.DashboardQueryGroupKind{ + Spec: dashv2alpha1.DashboardQueryGroupSpec{ + Queries: []dashv2alpha1.DashboardPanelQueryKind{{Spec: dashv2alpha1.DashboardPanelQuerySpec{RefId: "A"}}}, + }, + }, + }, + }, + } + } + + return &dashv2alpha1.Dashboard{ + Spec: dashv2alpha1.DashboardSpec{ + Elements: elements, + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + TabsLayoutKind: &dashv2alpha1.DashboardTabsLayoutKind{ + Kind: "TabsLayout", + Spec: dashv2alpha1.DashboardTabsLayoutSpec{ + Tabs: []dashv2alpha1.DashboardTabsLayoutTabKind{ + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + RowsLayoutKind: &dashv2alpha1.DashboardRowsLayoutKind{ + Kind: "RowsLayout", + Spec: dashv2alpha1.DashboardRowsLayoutSpec{ + Rows: []dashv2alpha1.DashboardRowsLayoutRowKind{ + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 1"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel1"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel2"}}}, + }, + }, + }, + }, + }, + }, + { + Kind: "RowsLayoutRow", + Spec: dashv2alpha1.DashboardRowsLayoutRowSpec{ + Title: ptrString("Row 2"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrAutoGridLayoutKindOrTabsLayoutKindOrRowsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel3"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel4"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + Kind: "TabsLayoutTab", + Spec: dashv2alpha1.DashboardTabsLayoutTabSpec{ + Title: ptrString("Tab 2"), + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{ + Items: []dashv2alpha1.DashboardGridLayoutItemKind{ + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel5"}}}, + {Spec: dashv2alpha1.DashboardGridLayoutItemSpec{Element: dashv2alpha1.DashboardElementReference{Name: "panel6"}}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } +} + +// createV0V1MixedAllTypes creates a V0/V1 dashboard with ALL layout types: +// - Panels out of rows (flat, top-level) +// - Collapsed row with nested panels +// - Expanded row followed by panels +// Structure: [p1, p2, Row1(collapsed){p3,p4}, Row2(expanded), p5, p6] +// Total: 6 panels +func createV0V1MixedAllTypes() map[string]interface{} { + panels := []interface{}{ + // Flat panels out of rows (at the beginning) + map[string]interface{}{ + "id": float64(1), + "title": "Panel 1 (flat, no row)", + "type": "timeseries", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + map[string]interface{}{ + "id": float64(2), + "title": "Panel 2 (flat, no row)", + "type": "stat", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + + // Collapsed row with nested panels + map[string]interface{}{ + "id": float64(100), + "title": "Row 1 (collapsed)", + "type": "row", + "collapsed": true, + "panels": []interface{}{ + map[string]interface{}{ + "id": float64(3), + "title": "Panel 3 (in collapsed row)", + "type": "gauge", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + map[string]interface{}{ + "id": float64(4), + "title": "Panel 4 (in collapsed row)", + "type": "table", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + }, + }, + + // Expanded row (empty, panels follow after) + map[string]interface{}{ + "id": float64(101), + "title": "Row 2 (expanded)", + "type": "row", + // No "panels" field when row is expanded + }, + + // Panels after expanded row + map[string]interface{}{ + "id": float64(5), + "title": "Panel 5 (after expanded row)", + "type": "bargauge", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + map[string]interface{}{ + "id": float64(6), + "title": "Panel 6 (after expanded row)", + "type": "piechart", + "targets": []interface{}{ + map[string]interface{}{"refId": "A"}, + }, + }, + } + + return map[string]interface{}{"panels": panels} +} + +// ptrString is a helper to create a pointer to a string +func ptrString(s string) *string { + return &s +} diff --git a/apps/dashboard/pkg/migration/conversion/conversion_test.go b/apps/dashboard/pkg/migration/conversion/conversion_test.go index 88dfb683225..63338e7ea70 100644 --- a/apps/dashboard/pkg/migration/conversion/conversion_test.go +++ b/apps/dashboard/pkg/migration/conversion/conversion_test.go @@ -35,7 +35,7 @@ func TestConversionMatrixExist(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) versions := []metav1.Object{ &dashv0.Dashboard{Spec: common.Unstructured{Object: map[string]any{"title": "dashboardV0"}}}, @@ -89,7 +89,7 @@ func TestDashboardConversionToAllVersions(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -309,7 +309,7 @@ func TestMigratedDashboardsConversion(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -428,7 +428,7 @@ func setupTestConversionScheme(t *testing.T) *runtime.Scheme { t.Helper() dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) scheme := runtime.NewScheme() err := RegisterConversions(scheme, dsProvider, leProvider) @@ -527,7 +527,7 @@ func TestConversionMetrics(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Create a test registry for metrics registry := prometheus.NewRegistry() @@ -694,7 +694,7 @@ func TestConversionMetricsWrapper(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Create a test registry for metrics registry := prometheus.NewRegistry() @@ -864,7 +864,7 @@ func TestSchemaVersionExtraction(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Create a test registry for metrics registry := prometheus.NewRegistry() @@ -910,7 +910,7 @@ func TestConversionLogging(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Create a test registry for metrics registry := prometheus.NewRegistry() @@ -1003,7 +1003,7 @@ func TestConversionLogLevels(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("log levels and structured fields verification", func(t *testing.T) { // Create test wrapper to verify logging behavior @@ -1076,7 +1076,7 @@ func TestConversionLoggingFields(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) // Use TestLibraryElementProvider for tests that need library panel models with repeat options leProvider := migrationtestutil.NewTestLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("verify all log fields are present", func(t *testing.T) { // Test that the conversion wrapper includes all expected structured fields diff --git a/apps/dashboard/pkg/migration/conversion/metrics.go b/apps/dashboard/pkg/migration/conversion/metrics.go index 5b2700bce60..5a60aa848de 100644 --- a/apps/dashboard/pkg/migration/conversion/metrics.go +++ b/apps/dashboard/pkg/migration/conversion/metrics.go @@ -17,7 +17,9 @@ import ( "github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion" ) -var logger = logging.DefaultLogger.With("logger", "dashboard.conversion") +func getLogger() logging.Logger { + return logging.DefaultLogger.With("logger", "dashboard.conversion") +} // getErroredSchemaVersionFunc determines the schema version function that errored func getErroredSchemaVersionFunc(err error) string { @@ -197,9 +199,9 @@ func withConversionMetrics(sourceVersionAPI, targetVersionAPI string, conversion ) if errorType == "schema_minimum_version_error" { - logger.Warn("Dashboard conversion failed", logFields...) + getLogger().Warn("Dashboard conversion failed", logFields...) } else { - logger.Error("Dashboard conversion failed", logFields...) + getLogger().Error("Dashboard conversion failed", logFields...) } } else { // Record success metrics @@ -235,7 +237,7 @@ func withConversionMetrics(sourceVersionAPI, targetVersionAPI string, conversion ) } - logger.Debug("Dashboard conversion succeeded", successLogFields...) + getLogger().Debug("Dashboard conversion succeeded", successLogFields...) } return nil diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json index 863d7b2a102..7c7c479199d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.json @@ -76,9 +76,9 @@ "barGlow": false, "centerGlow": false, "rounded": true, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -155,9 +155,9 @@ "barGlow": false, "centerGlow": true, "rounded": true, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -234,9 +234,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -313,9 +313,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -392,9 +392,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -471,9 +471,9 @@ "barGlow": true, "centerGlow": true, "rounded": false, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -550,9 +550,9 @@ "barGlow": true, "centerGlow": true, "rounded": false, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -642,9 +642,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -721,9 +721,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -800,9 +800,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -879,9 +879,9 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -975,9 +975,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1054,9 +1054,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1133,9 +1133,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": true }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1212,9 +1212,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1291,9 +1291,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1387,9 +1387,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": true }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1470,9 +1470,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": true }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1553,9 +1553,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": true }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1645,10 +1645,10 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1731,10 +1731,10 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1831,10 +1831,10 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1919,10 +1919,10 @@ "centerGlow": true, "rounded": true, "sparkline": false, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2005,10 +2005,10 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2091,10 +2091,10 @@ "barGlow": true, "centerGlow": true, "rounded": true, - "spotlight": true + "spotlight": true, + "gradient": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2147,4 +2147,4 @@ "title": "Panel tests - Gauge (new)", "uid": "panel-tests-gauge-new", "weekStart": "" -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json index d4dd7980100..a3de6df336a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.json @@ -956,9 +956,9 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1162,4 +1162,4 @@ "title": "Panel tests - Old gauge to new", "uid": "panel-tests-old-gauge-to-new", "weekStart": "" -} \ No newline at end of file +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.angular-migrations.json b/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.angular-migrations.json new file mode 100644 index 00000000000..3d496f51731 --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.angular-migrations.json @@ -0,0 +1,1310 @@ +{ + "kind": "Dashboard", + "apiVersion": "dashboard.grafana.app/v1beta1", + "metadata": { + "name": "angular-migrations-test" + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "links": [ + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate graph panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate graph panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate table (old) panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate table (old) panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate piechart panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate piechart panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate worldmap panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate worldmap panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate stat panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate stat panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate (TRUE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate (FALSE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Disable angular (TRUE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.disableAngular=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Disable angular (FALSE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.disableAngular=false" + } + ], + "liveNow": false, + "panels": [ + { + "aliasColors": {}, + "type": "graph", + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 0 + }, + "hiddenSeries": false, + "id": 4, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 3 + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 0 + }, + "id": 6, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Timeseries panel\n\nKnown issues:\n* hiding null/empty series\n* time regions", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 11 + }, + "hiddenSeries": false, + "id": 28, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "rawFrameContent": "[\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.260951647569786,\n 1.887442338051216,\n 2.1526144400893514,\n 1.7287721375237766,\n 1.7262902137793208\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod1\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 1.589539045095202,\n 1.5914283506847613,\n 1.8976990616650726,\n 1.758223085999124,\n 2.2294649594813816\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod2\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.0914263380328766,\n 1.8164545521094575,\n 1.621111084665713,\n 1.3902653996444705,\n 1.482803315949775\n ]\n ]\n }\n }\n]", + "refId": "A", + "scenarioId": "raw_frame" + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis series mode", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "barchart", + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 11 + }, + "id": 29, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar chart panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "default": false, + "type": "datasource", + "uid": "-- Dashboard --" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 22 + }, + "hiddenSeries": false, + "id": 32, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.3.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "datasource", + "uid": "-- Dashboard --" + }, + "panelId": 28, + "refId": "A" + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis series mode (with legend calcs)", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "bargauge", + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 22 + }, + "hiddenSeries": false, + "id": 30, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 3 + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis histogram mode", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "histogram", + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 22 + }, + "id": 33, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar gauge panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.3.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 22 + }, + "id": 31, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Histogram panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "table-old", + "columns": [], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fontSize": "100%", + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 33 + }, + "id": 2, + "options": { + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "showRowNums": false + }, + "pluginVersion": "9.5.0-pre", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk_table" + } + ], + "title": "Table (old)", + "transform": "table", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + } + ], + "type": "table" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 33 + }, + "id": 7, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Table (old) \u003e\u003e Table\n\nKnown issues:\n* wrapping text\n* style changes", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-singlestat-panel", + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 43 + }, + "id": 9, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "thresholds": "", + "title": "grafana-singlestat-panel", + "type": "stat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "match": "null", + "result": { + "text": "N/A" + } + }, + "type": "special" + } + ], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "ms" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 43 + }, + "id": 23, + "maxDataPoints": 100, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "horizontal", + "reduceOptions": { + "calcs": [ + "mean" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "textMode": "auto", + "wideLayout": true + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "singlestat (old, internal. Migrated if schema \u003c 28)", + "type": "stat" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 43 + }, + "id": 10, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Singlestat \u003e\u003e Stat\n\nKnown issues:\n* limited options", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-piechart-panel", + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 51 + }, + "id": 24, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "9.5.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk_table" + } + ], + "title": "grafana-piechart-panel", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + } + ], + "type": "piechart" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 51 + }, + "id": 25, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-piechart-panel \u003e\u003e piechart\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-worldmap-panel", + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "decimals": 0, + "esMetric": "Count", + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 61 + }, + "hideEmpty": false, + "hideZero": false, + "id": 26, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "maxDataPoints": 1, + "mouseWheelZoom": false, + "options": { + "basemap": { + "name": "Basemap", + "type": "default" + }, + "controls": { + "mouseWheelZoom": false, + "showAttribution": true, + "showDebug": false, + "showMeasure": false, + "showScale": false, + "showZoom": true + }, + "layers": [ + { + "config": { + "showLegend": true, + "style": { + "color": { + "fixed": "dark-green" + }, + "opacity": 0.4, + "rotation": { + "fixed": 0, + "max": 360, + "min": -360, + "mode": "mod" + }, + "size": { + "fixed": 5, + "max": 30, + "min": 2 + }, + "symbol": { + "fixed": "img/icons/marker/circle.svg", + "mode": "fixed" + }, + "symbolAlign": { + "horizontal": "center", + "vertical": "center" + }, + "textConfig": { + "fontSize": 12, + "offsetX": 0, + "offsetY": 0, + "textAlign": "center", + "textBaseline": "middle" + } + } + }, + "location": { + "gazetteer": "public/gazetteer/countries.json", + "mode": "lookup" + }, + "name": "Layer 0", + "tooltip": true, + "type": "markers" + } + ], + "tooltip": { + "mode": "details" + }, + "view": { + "allLayers": true, + "id": "zero", + "lat": 0, + "lon": 0, + "zoom": 1 + } + }, + "pluginVersion": "10.4.0-pre", + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "targets": [ + { + "csvFileName": "flight_info_by_state.csv", + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "csv_file" + } + ], + "thresholds": "0,10", + "title": "grafana-worldmap-panel", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + }, + { + "id": "reduce", + "options": { + "reducers": [ + "sum" + ] + } + } + ], + "type": "geomap", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 61 + }, + "id": 27, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-worldmap-panel \u003e\u003e geomap\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + } + ], + "refresh": "", + "schemaVersion": 42, + "tags": [ + "gdev", + "migrations", + "angular" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "", + "title": "Devenv - Panel migrations", + "uid": "cdd412c4", + "weekStart": "" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.value-mapping-and-overrides.json b/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.value-mapping-and-overrides.json new file mode 100644 index 00000000000..c0a82877ecc --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/v1beta1.value-mapping-and-overrides.json @@ -0,0 +1,603 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v1beta1", + "metadata": { + "name": "value-mapping-test", + "namespace": "default", + "uid": "value-mapping-test", + "resourceVersion": "1765384157199094", + "generation": 2, + "creationTimestamp": "2025-11-19T20:09:28Z", + "labels": { + "grafana.app/deprecatedInternalID": "646372978987008" + }, + "annotations": {}, + "managedFields": [] + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "description": "Test dashboard for all value mapping types and override matcher types", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "links": [], + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with ValueMap mapping type - maps specific text values to colors and display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "critical": { + "color": "red", + "index": 0, + "text": "Critical!" + }, + "warning": { + "color": "orange", + "index": 1, + "text": "Warning" + }, + "ok": { + "color": "green", + "index": 2, + "text": "OK" + } + }, + "type": "value" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 100 + }, + { + "id": "custom.align", + "value": "center" + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 1, + "targets": [ + { + "expr": "up", + "refId": "A" + } + ], + "title": "ValueMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with RangeMap mapping type - maps numerical ranges to colors and display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "from": 0, + "to": 50, + "result": { + "color": "green", + "index": 0, + "text": "Low" + } + }, + "type": "range" + }, + { + "options": { + "from": 50, + "to": 80, + "result": { + "color": "orange", + "index": 1, + "text": "Medium" + } + }, + "type": "range" + }, + { + "options": { + "from": 80, + "to": 100, + "result": { + "color": "red", + "index": 2, + "text": "High" + } + }, + "type": "range" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byRegexp", + "options": "/^cpu_/" + }, + "properties": [ + { + "id": "unit", + "value": "percent" + }, + { + "id": "decimals", + "value": 2 + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + }, + "id": 2, + "targets": [ + { + "expr": "cpu_usage_percent", + "refId": "A" + } + ], + "title": "RangeMap Example", + "type": "gauge" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with RegexMap mapping type - maps values matching regex patterns to colors", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "pattern": "/^error.*/", + "result": { + "color": "red", + "index": 0, + "text": "Error" + } + }, + "type": "regex" + }, + { + "options": { + "pattern": "/^warn.*/", + "result": { + "color": "orange", + "index": 1, + "text": "Warning" + } + }, + "type": "regex" + }, + { + "options": { + "pattern": "/^info.*/", + "result": { + "color": "blue", + "index": 2, + "text": "Info" + } + }, + "type": "regex" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byType", + "options": "string" + }, + "properties": [ + { + "id": "custom.cellOptions", + "value": { + "type": "color-text" + } + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 8 + }, + "id": 3, + "targets": [ + { + "expr": "log_level", + "refId": "A" + } + ], + "title": "RegexMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with SpecialValueMap mapping type - maps special values like null, NaN, true, false to display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "match": "null", + "result": { + "color": "gray", + "index": 0, + "text": "No Data" + } + }, + "type": "special" + }, + { + "options": { + "match": "nan", + "result": { + "color": "gray", + "index": 1, + "text": "Not a Number" + } + }, + "type": "special" + }, + { + "options": { + "match": "null+nan", + "result": { + "color": "gray", + "index": 2, + "text": "N/A" + } + }, + "type": "special" + }, + { + "options": { + "match": "true", + "result": { + "color": "green", + "index": 3, + "text": "Yes" + } + }, + "type": "special" + }, + { + "options": { + "match": "false", + "result": { + "color": "red", + "index": 4, + "text": "No" + } + }, + "type": "special" + }, + { + "options": { + "match": "empty", + "result": { + "color": "gray", + "index": 5, + "text": "Empty" + } + }, + "type": "special" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "A" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "blue" + } + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 8 + }, + "id": 4, + "targets": [ + { + "expr": "some_metric", + "refId": "A" + } + ], + "title": "SpecialValueMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with all mapping types combined - demonstrates mixing different mapping types and multiple override matchers", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "success": { + "color": "green", + "index": 0, + "text": "Success" + }, + "failure": { + "color": "red", + "index": 1, + "text": "Failure" + } + }, + "type": "value" + }, + { + "options": { + "from": 0, + "to": 100, + "result": { + "color": "blue", + "index": 2, + "text": "In Range" + } + }, + "type": "range" + }, + { + "options": { + "pattern": "/^[A-Z]{3}-\\d+$/", + "result": { + "color": "purple", + "index": 3, + "text": "ID Format" + } + }, + "type": "regex" + }, + { + "options": { + "match": "null", + "result": { + "color": "gray", + "index": 4, + "text": "Missing" + } + }, + "type": "special" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 120 + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + } + ] + }, + { + "matcher": { + "id": "byRegexp", + "options": "/^value_/" + }, + "properties": [ + { + "id": "unit", + "value": "short" + }, + { + "id": "min", + "value": 0 + }, + { + "id": "max", + "value": 100 + } + ] + }, + { + "matcher": { + "id": "byType", + "options": "number" + }, + "properties": [ + { + "id": "decimals", + "value": 2 + }, + { + "id": "thresholds", + "value": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "yellow", + "value": 50 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + ] + }, + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "displayName", + "value": "Secondary Query" + } + ] + }, + { + "matcher": { + "id": "byValue", + "options": { + "reducer": "allIsNull", + "op": "gte", + "value": 0 + } + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 16 + }, + "id": 5, + "targets": [ + { + "expr": "combined_metric", + "refId": "A" + }, + { + "expr": "secondary_metric", + "refId": "B" + } + ], + "title": "Combined Mappings and Overrides Example", + "type": "table" + } + ], + "schemaVersion": 42, + "tags": [ + "value-mapping", + "overrides", + "test" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "Value Mapping and Overrides Test", + "weekStart": "" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + }, + "access": { + "slug": "value-mapping-test", + "url": "/d/value-mapping-test/value-mapping-and-overrides-test", + "canSave": true, + "canEdit": true, + "canAdmin": true, + "canStar": true, + "canDelete": true, + "annotationsPermissions": { + "dashboard": { + "canAdd": true, + "canEdit": true, + "canDelete": true + }, + "organization": { + "canAdd": true, + "canEdit": true, + "canDelete": true + } + } + } +} diff --git a/apps/dashboard/pkg/migration/conversion/testdata/input/v2beta1.tab-with-multiple-panels.json b/apps/dashboard/pkg/migration/conversion/testdata/input/v2beta1.tab-with-multiple-panels.json new file mode 100644 index 00000000000..c2bb49cc5cb --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/input/v2beta1.tab-with-multiple-panels.json @@ -0,0 +1,715 @@ +{ +"kind": "DashboardWithAccessInfo", +"apiVersion": "dashboard.grafana.app/v2beta1", +"metadata": { + "name": "adt885j", + "namespace": "default", + "uid": "yTWet6JgBjlRIWnqRE9ZOmUycfT0tEkr2mljaln1GWIX", + "resourceVersion": "2", + "generation": 2, + "creationTimestamp": "2025-12-16T10:44:31Z", + "labels": { + "grafana.app/deprecatedInternalID": "2409" + }, + "annotations": { + "grafana.app/createdBy": "user:u000000001", + "grafana.app/updatedBy": "user:u000000001", + "grafana.app/updatedTimestamp": "2025-12-16T10:51:14Z" + } +}, +"spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana", + "version": "v0", + "datasource": { + "name": "-- Grafana --" + }, + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true + } + } + ], + "cursorSync": "Off", + "description": "", + "editable": true, + "elements": { + "panel-1": { + "kind": "Panel", + "spec": { + "id": 1, + "title": "Panel1", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "datasource": { + "name": "PD8C576611E62080A" + }, + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "12.4.0-pre", + "spec": { + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "Panel2", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "12.4.0-pre", + "spec": { + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-3": { + "kind": "Panel", + "spec": { + "id": 3, + "title": "Panel3", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "12.4.0-pre", + "spec": { + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "Panel4", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "12.4.0-pre", + "spec": { + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-5": { + "kind": "Panel", + "spec": { + "id": 5, + "title": "Panel5", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "12.4.0-pre", + "spec": { + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + } + }, + "layout": { + "kind": "TabsLayout", + "spec": { + "tabs": [ + { + "kind": "TabsLayoutTab", + "spec": { + "title": "Tab1", + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 7, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-1" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 7, + "y": 0, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 15, + "y": 0, + "width": 9, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-3" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-5" + } + } + } + ] + } + } + } + } + ] + } + }, + "links": [], + "liveNow": false, + "preload": false, + "tags": [], + "timeSettings": { + "timezone": "browser", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Dashboard with tabs", + "variables": [] +}, +"status": {}, +"access": { + "slug": "dashboard-with-tabs", + "url": "/d/adt885j/dashboard-with-tabs", + "isPublic": false, + "canSave": true, + "canEdit": true, + "canAdmin": true, + "canStar": true, + "canDelete": true, + "annotationsPermissions": { + "dashboard": { + "canAdd": true, + "canEdit": true, + "canDelete": true + }, + "organization": { + "canAdd": true, + "canEdit": true, + "canDelete": true + } + } +} +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2alpha1.json index 7a4a4d2c4b7..669e2e742a6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2alpha1.json @@ -66,7 +66,29 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "thresholds": [ + "20", + "30" + ] + }, + { + "align": "auto", + "thresholds": [ + "200", + "300" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +132,22 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "thresholds": [ + "50", + "75" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +191,22 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "styles": [ + { + "thresholds": [ + "5", + "10", + "15" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -237,5 +289,10 @@ "title": "V10 Table Thresholds Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2beta1.json index 69d75b09dcf..22a36b375a0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v10.table_thresholds.v42.v2beta1.json @@ -69,7 +69,29 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "thresholds": [ + "20", + "30" + ] + }, + { + "align": "auto", + "thresholds": [ + "200", + "300" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +137,22 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "thresholds": [ + "50", + "75" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +198,22 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "styles": [ + { + "thresholds": [ + "5", + "10", + "15" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -244,5 +296,10 @@ "title": "V10 Table Thresholds Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2alpha1.json index f427b5dbcb7..b9007aeab43 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2alpha1.json @@ -66,7 +66,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +121,20 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -206,5 +230,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2beta1.json index 8e59bbd21ca..75255794c5c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v11.no-op-migration.v42.v2beta1.json @@ -69,7 +69,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +126,20 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -213,5 +237,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2alpha1.json index f55769f82b2..5e69664e182 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2alpha1.json @@ -203,5 +203,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2beta1.json index febee713d97..e3d0bff265d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v12.template-variables.v42.v2beta1.json @@ -216,5 +216,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2alpha1.json index a1ef92d3d50..091b4103636 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2alpha1.json @@ -66,7 +66,20 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 200, + "threshold1Color": "yellow", + "threshold2": 400, + "threshold2Color": "red", + "thresholdLine": true + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +123,20 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 100, + "threshold1Color": "green", + "threshold2": 300, + "threshold2Color": "blue", + "thresholdLine": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +180,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 150, + "threshold1Color": "orange", + "thresholdLine": true + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -198,7 +235,25 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 200, + "threshold1Color": "yellow", + "thresholdLine": false + }, + "thresholds": [ + { + "color": "purple", + "colorMode": "custom", + "value": 50 + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -242,7 +297,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -351,5 +411,10 @@ "title": "V13 Graph Thresholds Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2beta1.json index a41d04804b7..0fdbbd1990b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.graph_thresholds.v42.v2beta1.json @@ -69,7 +69,20 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 200, + "threshold1Color": "yellow", + "threshold2": 400, + "threshold2Color": "red", + "thresholdLine": true + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +128,20 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 100, + "threshold1Color": "green", + "threshold2": 300, + "threshold2Color": "blue", + "thresholdLine": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +187,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 150, + "threshold1Color": "orange", + "thresholdLine": true + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -207,7 +244,25 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "threshold1": 200, + "threshold1Color": "yellow", + "thresholdLine": false + }, + "thresholds": [ + { + "color": "purple", + "colorMode": "custom", + "value": 50 + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -253,7 +308,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -362,5 +422,10 @@ "title": "V13 Graph Thresholds Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2alpha1.json index 3edc16edae6..b2673944cb7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2alpha1.json @@ -72,7 +72,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -129,5 +134,10 @@ "title": "Dashboard with minimal graph panel settings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2beta1.json index 8e18ac60c4d..1b8e98bafc0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v13.minimal_graph_config.v42.v2beta1.json @@ -75,7 +75,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -132,5 +137,10 @@ "title": "Dashboard with minimal graph panel settings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2alpha1.json index e4a62f00bc7..5a00a12baa3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2alpha1.json @@ -68,7 +68,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -114,7 +125,20 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "max": 100, + "min": 0, + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -210,5 +234,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2beta1.json index 975fc24c969..9251f743242 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v14.shared_crosshair_to_graph_tooltip.v42.v2beta1.json @@ -71,7 +71,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -119,7 +130,20 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "max": 100, + "min": 0, + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -217,5 +241,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2alpha1.json index decdff12902..8d340c0f65e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2alpha1.json @@ -1004,5 +1004,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2beta1.json index 9db5193d5af..8070895766a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.mimir_rollout_debugging.v42.v2beta1.json @@ -1023,5 +1023,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2alpha1.json index 347556eb45d..551348d7852 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2alpha1.json @@ -83,7 +83,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -127,7 +138,20 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -223,5 +247,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2beta1.json index 756f4a76074..c6ab962de2f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v15.no-op-migration.v42.v2beta1.json @@ -87,7 +87,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -133,7 +144,20 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -231,5 +255,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2alpha1.json index 1bf45848829..4c21c63a66a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2alpha1.json @@ -1455,5 +1455,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2beta1.json index d7f5fd82659..684b7b0f564 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.empty-rows-and-panels-array.v42.v2beta1.json @@ -1481,5 +1481,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2alpha1.json index 6cf8402f377..7229c6df268 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +159,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -198,7 +208,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -254,7 +269,14 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "height": 200 + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -282,7 +304,14 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "height": 200 + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -719,5 +748,10 @@ "title": "V16 Grid Layout Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2beta1.json index 2a6622f27a4..efdbb91f745 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.grid_layout_upgrade.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +166,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -207,7 +217,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -265,7 +280,14 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "height": 200 + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -294,7 +316,14 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "height": 200 + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -739,5 +768,10 @@ "title": "V16 Grid Layout Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2alpha1.json index 221b01ffec5..52c19734101 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2alpha1.json @@ -1655,5 +1655,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2beta1.json index 7c05e2ab74c..49e7fb1d9e7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v16.span_zero_demo.v42.v2beta1.json @@ -1707,5 +1707,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2alpha1.json index aa9017f0720..ecc7830b8fa 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +115,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +164,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -242,7 +257,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -374,7 +394,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -462,7 +487,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -636,5 +666,10 @@ "title": "V17 MinSpan to MaxPerRow Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2beta1.json index 697c0dadaac..ce68572f0d2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v17.minspan_to_maxperrow.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +120,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +171,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -253,7 +268,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -391,7 +411,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -483,7 +508,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -657,5 +687,10 @@ "title": "V17 MinSpan to MaxPerRow Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2alpha1.json index f154e2e2679..55f7729fc1a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2alpha1.json @@ -288,6 +288,10 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "show": true, "showLegend": true @@ -401,5 +405,10 @@ "title": "V18 Gauge Options Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2beta1.json index 6d1528a868a..758bdfad09e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v18.gauge_options.v42.v2beta1.json @@ -299,6 +299,10 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "show": true, "showLegend": true @@ -412,5 +416,10 @@ "title": "V18 Gauge Options Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2alpha1.json index e51fc93636a..596bd229b79 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2alpha1.json @@ -71,7 +71,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -312,7 +317,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -434,5 +444,10 @@ "title": "V19 Panel Links Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2beta1.json index 0dbf12ef898..1302e17c7f3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v19.panel_links.v42.v2beta1.json @@ -74,7 +74,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -325,7 +330,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -447,5 +457,10 @@ "title": "V19 Panel Links Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2alpha1.json index 129ba30c694..57b7b24ed56 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2alpha1.json @@ -68,7 +68,20 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graphite", + "originalOptions": { + "grid": { + "max": 100, + "min": 0 + }, + "legend": true, + "y2_format": "short", + "y_format": "percent" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -114,7 +127,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "min": 0 + }, + "legend": false, + "y_format": "bytes" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -204,7 +228,15 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graphite", + "originalOptions": { + "legend": true, + "y2_format": "Bps" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -354,5 +386,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2beta1.json index 0c80ae34850..0143563e75b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v2.panels-and-services.v42.v2beta1.json @@ -71,7 +71,20 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graphite", + "originalOptions": { + "grid": { + "max": 100, + "min": 0 + }, + "legend": true, + "y2_format": "short", + "y_format": "percent" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -119,7 +132,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "grid": { + "min": 0 + }, + "legend": false, + "y_format": "bytes" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -213,7 +237,15 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graphite", + "originalOptions": { + "legend": true, + "y2_format": "Bps" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -365,5 +397,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2alpha1.json index 95d3f1d8834..1e077553a81 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2alpha1.json @@ -426,5 +426,10 @@ "title": "V20 Variable Syntax Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2beta1.json index f5c9e157c75..13327bcd9f6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v20.variable_syntax_links.v42.v2beta1.json @@ -437,5 +437,10 @@ "title": "V20 Variable Syntax Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2alpha1.json index 0b2251f0dca..a93d077fef3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2alpha1.json @@ -181,6 +181,10 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "dataLinks": [ { "title": "Graph Data Link", @@ -401,5 +405,10 @@ "title": "V21 Data Links Series to Field Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2beta1.json index 8c9808adf32..6244177502b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v21.data_links_series_to_field.v42.v2beta1.json @@ -188,6 +188,10 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "dataLinks": [ { "title": "Graph Data Link", @@ -412,5 +416,10 @@ "title": "V21 Data Links Series to Field Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2alpha1.json index dd03601b0ac..10c570651e5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2alpha1.json @@ -66,7 +66,25 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "pattern": "Time", + "type": "number" + }, + { + "align": "auto", + "pattern": "Value", + "type": "string" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -123,5 +141,10 @@ "title": "V22 Table Panel Styles Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2beta1.json index fd3dc0b587b..8c7d86f1d86 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v22.table_panel_align.v42.v2beta1.json @@ -69,7 +69,25 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "pattern": "Time", + "type": "number" + }, + { + "align": "auto", + "pattern": "Value", + "type": "string" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -126,5 +144,10 @@ "title": "V22 Table Panel Styles Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2alpha1.json index a40797444f4..3e93dbc7a66 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2alpha1.json @@ -374,5 +374,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2beta1.json index a97d9a51e2f..7286db67bf2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v23.multi_variable_alignment.v42.v2beta1.json @@ -391,5 +391,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2alpha1.json index c9dd5bffa51..4734298869d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2alpha1.json @@ -81,7 +81,29 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "legend": true, + "styles": [ + { + "colors": [ + "red", + "yellow", + "green" + ], + "pattern": "/.*/", + "thresholds": [ + "10", + "20", + "30" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -125,7 +147,31 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "center", + "pattern": "/.*/" + }, + { + "align": "left", + "pattern": "LeftColumn" + }, + { + "align": "right", + "pattern": "RightColumn" + }, + { + "align": "auto", + "pattern": "AutoColumn" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -169,7 +215,35 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "alias": "Exact Match", + "pattern": "ExactColumnName" + }, + { + "alias": "Regex Match", + "pattern": "/Regex.*Pattern/" + }, + { + "alias": "Start Pattern", + "pattern": "/^Start/" + }, + { + "alias": "End Pattern", + "pattern": "/End$/" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -213,7 +287,37 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "link": true, + "linkTargetBlank": true, + "linkTooltip": "Click to view details", + "linkUrl": "http://example.com/with-tooltip", + "pattern": "LinkWithTooltip" + }, + { + "link": true, + "linkTargetBlank": false, + "linkUrl": "http://example.com/no-tooltip", + "pattern": "LinkWithoutTooltip" + }, + { + "link": true, + "linkUrl": "http://example.com/minimal", + "pattern": "LinkMinimal" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -257,7 +361,37 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "alias": "ISO Date", + "dateFormat": "YYYY-MM-DD", + "pattern": "DateISO", + "type": "date" + }, + { + "alias": "Full DateTime", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "DateTime", + "type": "date" + }, + { + "alias": "Time Only", + "dateFormat": "HH:mm:ss", + "pattern": "TimeOnly", + "type": "date" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -389,7 +523,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -433,7 +572,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -477,7 +621,57 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "center", + "colorMode": "cell", + "colors": [ + "green", + "yellow", + "red" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [ + "100", + "500" + ], + "unit": "bytes" + }, + { + "alias": "Current Status", + "align": "left", + "colorMode": "value", + "decimals": 0, + "pattern": "Status", + "unit": "short" + }, + { + "colorMode": "row", + "link": true, + "linkTargetBlank": true, + "linkTooltip": "View error details", + "linkUrl": "http://example.com/errors", + "pattern": "/Error.*/" + }, + { + "alias": "Timestamp", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "pattern": "Hidden", + "type": "hidden" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -521,7 +715,47 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [ + { + "text": "Average", + "value": "avg" + }, + { + "text": "Maximum", + "value": "max" + }, + { + "text": "Minimum", + "value": "min" + }, + { + "text": "Total", + "value": "total" + }, + { + "text": "Current", + "value": "current" + }, + { + "text": "Count", + "value": "count" + } + ], + "styles": [ + { + "decimals": 1, + "pattern": "/.*/", + "unit": "percent" + } + ], + "transform": "timeseries_aggregations" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -565,7 +799,20 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -609,7 +856,20 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "bytes" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -653,7 +913,20 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "pattern": "/.*/" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -712,7 +985,20 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -756,7 +1042,29 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "colors": [ + "green", + "yellow", + "orange", + "red" + ], + "pattern": "/.*/", + "thresholds": [ + 10, + "20", + 30.5 + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -800,7 +1108,31 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "colorMode": "cell", + "pattern": "/.*/" + }, + { + "colorMode": "cell", + "pattern": "CellColumn" + }, + { + "colorMode": "row", + "pattern": "RowColumn" + }, + { + "colorMode": "value", + "pattern": "ValueColumn" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1065,5 +1397,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2beta1.json index 3d74b493b8e..57979e9f551 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v24.table-angular.v42.v2beta1.json @@ -85,7 +85,29 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "legend": true, + "styles": [ + { + "colors": [ + "red", + "yellow", + "green" + ], + "pattern": "/.*/", + "thresholds": [ + "10", + "20", + "30" + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -131,7 +153,31 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "center", + "pattern": "/.*/" + }, + { + "align": "left", + "pattern": "LeftColumn" + }, + { + "align": "right", + "pattern": "RightColumn" + }, + { + "align": "auto", + "pattern": "AutoColumn" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -177,7 +223,35 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "alias": "Exact Match", + "pattern": "ExactColumnName" + }, + { + "alias": "Regex Match", + "pattern": "/Regex.*Pattern/" + }, + { + "alias": "Start Pattern", + "pattern": "/^Start/" + }, + { + "alias": "End Pattern", + "pattern": "/End$/" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -223,7 +297,37 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "link": true, + "linkTargetBlank": true, + "linkTooltip": "Click to view details", + "linkUrl": "http://example.com/with-tooltip", + "pattern": "LinkWithTooltip" + }, + { + "link": true, + "linkTargetBlank": false, + "linkUrl": "http://example.com/no-tooltip", + "pattern": "LinkWithoutTooltip" + }, + { + "link": true, + "linkUrl": "http://example.com/minimal", + "pattern": "LinkMinimal" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -269,7 +373,37 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + }, + { + "alias": "ISO Date", + "dateFormat": "YYYY-MM-DD", + "pattern": "DateISO", + "type": "date" + }, + { + "alias": "Full DateTime", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "DateTime", + "type": "date" + }, + { + "alias": "Time Only", + "dateFormat": "HH:mm:ss", + "pattern": "TimeOnly", + "type": "date" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -407,7 +541,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -453,7 +592,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -499,7 +643,57 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "center", + "colorMode": "cell", + "colors": [ + "green", + "yellow", + "red" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [ + "100", + "500" + ], + "unit": "bytes" + }, + { + "alias": "Current Status", + "align": "left", + "colorMode": "value", + "decimals": 0, + "pattern": "Status", + "unit": "short" + }, + { + "colorMode": "row", + "link": true, + "linkTargetBlank": true, + "linkTooltip": "View error details", + "linkUrl": "http://example.com/errors", + "pattern": "/Error.*/" + }, + { + "alias": "Timestamp", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "pattern": "Hidden", + "type": "hidden" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -545,7 +739,47 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [ + { + "text": "Average", + "value": "avg" + }, + { + "text": "Maximum", + "value": "max" + }, + { + "text": "Minimum", + "value": "min" + }, + { + "text": "Total", + "value": "total" + }, + { + "text": "Current", + "value": "current" + }, + { + "text": "Count", + "value": "count" + } + ], + "styles": [ + { + "decimals": 1, + "pattern": "/.*/", + "unit": "percent" + } + ], + "transform": "timeseries_aggregations" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -591,7 +825,20 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -637,7 +884,20 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "bytes" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -683,7 +943,20 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "align": "auto", + "pattern": "/.*/" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -744,7 +1017,20 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "pattern": "/.*/", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -790,7 +1076,29 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "colors": [ + "green", + "yellow", + "orange", + "red" + ], + "pattern": "/.*/", + "thresholds": [ + 10, + "20", + 30.5 + ] + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -836,7 +1144,31 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "styles": [ + { + "colorMode": "cell", + "pattern": "/.*/" + }, + { + "colorMode": "cell", + "pattern": "CellColumn" + }, + { + "colorMode": "row", + "pattern": "RowColumn" + }, + { + "colorMode": "value", + "pattern": "ValueColumn" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1101,5 +1433,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2alpha1.json index 3375a6bffe4..618d1193a1c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2alpha1.json @@ -123,7 +123,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -217,5 +228,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2beta1.json index b873fdea3a3..7fd6cdec538 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v25.no-op-migration.v42.v2beta1.json @@ -130,7 +130,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -226,5 +237,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2alpha1.json index a135614baba..d15f179ac31 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2alpha1.json @@ -240,5 +240,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2beta1.json index 378ae69f16a..59aad2fdb0b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v26.text2_to_text.v42.v2beta1.json @@ -247,5 +247,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2alpha1.json index 51cdcba85c1..bab8c53ac6a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -94,7 +99,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -207,5 +217,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2beta1.json index 3fdcd01a27c..79dab4989d1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v27.repeated_panels_and_constant_variable.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -98,7 +103,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -211,5 +221,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2alpha1.json index 54384f8dc06..75831381989 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2alpha1.json @@ -131,5 +131,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2beta1.json index 6626b919137..e79b7d1f7d7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.remove_variable_properties.v42.v2beta1.json @@ -134,5 +134,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2alpha1.json index 82fc46be585..14e59bfc9bc 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2alpha1.json @@ -81,7 +81,24 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -125,7 +142,28 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "gauge": { + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "grid": { + "max": 10, + "min": 1 + }, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -184,7 +222,47 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + } + ], + "thresholds": "10,20,30", + "valueMaps": [ + { + "op": "=", + "text": "test", + "value": "20" + }, + { + "op": "=", + "text": "test1", + "value": "30" + }, + { + "op": "=", + "text": "50", + "value": "40" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -393,5 +471,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2beta1.json index 4eff500bef6..4f376187bba 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_and_variable_properties.v42.v2beta1.json @@ -85,7 +85,24 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -131,7 +148,28 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "gauge": { + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "grid": { + "max": 10, + "min": 1 + }, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -193,7 +231,47 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + } + ], + "thresholds": "10,20,30", + "valueMaps": [ + { + "op": "=", + "text": "test", + "value": "20" + }, + { + "op": "=", + "text": "test1", + "value": "30" + }, + { + "op": "=", + "text": "50", + "value": "40" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -406,5 +484,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2alpha1.json index 0873ad2190c..195ceebb6cc 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2alpha1.json @@ -81,7 +81,24 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -140,7 +157,24 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -184,7 +218,28 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "gauge": { + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "grid": { + "max": 10, + "min": 1 + }, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -243,7 +298,47 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + } + ], + "thresholds": "10,20,30", + "valueMaps": [ + { + "op": "=", + "text": "test", + "value": "20" + }, + { + "op": "=", + "text": "test1", + "value": "30" + }, + { + "op": "=", + "text": "50", + "value": "40" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -289,7 +384,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -622,5 +778,10 @@ "title": "V28 Singlestat and Variable Properties Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2beta1.json index 2b7d27024c6..fb221254e90 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v28.singlestat_migration.v42.v2beta1.json @@ -85,7 +85,24 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -147,7 +164,24 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "thresholds": "" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -193,7 +227,28 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "gauge": { + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "grid": { + "max": 10, + "min": 1 + }, + "thresholds": "10,20,30" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -255,7 +310,47 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colors": [ + "#FF0000", + "green", + "orange" + ], + "grid": { + "max": 10, + "min": 1 + }, + "legend": true, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + } + ], + "thresholds": "10,20,30", + "valueMaps": [ + { + "op": "=", + "text": "test", + "value": "20" + }, + { + "op": "=", + "text": "test1", + "value": "30" + }, + { + "op": "=", + "text": "50", + "value": "40" + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -303,7 +398,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -642,5 +798,10 @@ "title": "V28 Singlestat and Variable Properties Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2alpha1.json index 2688367b33b..5a096f20011 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2alpha1.json @@ -435,5 +435,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2beta1.json index 8e57483ceb4..270c6912485 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v29.query_variables_refresh_and_options.v42.v2beta1.json @@ -458,5 +458,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2alpha1.json index db33eea5445..112dae69255 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2alpha1.json @@ -294,5 +294,10 @@ "title": "V3 No-Op Migration - but tests ensuring panel IDs are unique", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2beta1.json index 4a38725abc3..0a3a97926b8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v3.no-op.v42.v2beta1.json @@ -303,5 +303,10 @@ "title": "V3 No-Op Migration - but tests ensuring panel IDs are unique", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2alpha1.json index 60334f9ffb1..40e4072138c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2alpha1.json @@ -280,6 +280,10 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "tooltip": { "mode": "single" } @@ -530,7 +534,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -689,5 +693,10 @@ "title": "V30 Value Mappings and Tooltip Options Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2beta1.json index 6848d2d1714..9f5630252bf 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v30.value_mappings_and_tooltip_options.v42.v2beta1.json @@ -289,6 +289,10 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "tooltip": { "mode": "single" } @@ -546,7 +550,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -705,5 +709,10 @@ "title": "V30 Value Mappings and Tooltip Options Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2alpha1.json index ac34174bfcb..6fe0fcc67c8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2alpha1.json @@ -669,5 +669,10 @@ "title": "V31 LabelsToFields Merge Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2beta1.json index d7f0684597c..5ca1fbff96c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v31.labels_to_fields_merge.v42.v2beta1.json @@ -684,5 +684,10 @@ "title": "V31 LabelsToFields Merge Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2alpha1.json index 3c58166f6c4..369db4327b7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2alpha1.json @@ -144,7 +144,18 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -310,5 +321,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2beta1.json index 1611cea2464..1fd5d1638ec 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v32.no_op_migration.v42.v2beta1.json @@ -151,7 +151,18 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "yAxes": [ + { + "show": true + } + ] + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -320,5 +331,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2alpha1.json index d41d2d7bda3..b21c071f750 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2alpha1.json @@ -345,7 +345,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -548,7 +553,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -720,5 +725,10 @@ "title": "V33 Panel Datasource Name to Ref Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2beta1.json index fbb8d83b728..c541c51dc42 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v33.panel_ds_name_to_ref.v42.v2beta1.json @@ -361,7 +361,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -574,7 +579,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -746,5 +751,10 @@ "title": "V33 Panel Datasource Name to Ref Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2alpha1.json index ad69702a739..bc705379491 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2alpha1.json @@ -1663,7 +1663,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -1900,5 +1900,10 @@ "title": "CloudWatch Multiple Statistics Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2beta1.json index 79ee3db369e..329e10bcd42 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v34.multiple_stats_cloudwatch.v42.v2beta1.json @@ -1727,7 +1727,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -1964,5 +1964,10 @@ "title": "CloudWatch Multiple Statistics Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2alpha1.json index c06dd85bb25..cbb59009f10 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2alpha1.json @@ -595,5 +595,10 @@ "title": "X-Axis Visibility Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2beta1.json index f9be2a6cee1..fde3ba9c006 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v35.ensure_x_axis_visibility.v42.v2beta1.json @@ -612,5 +612,10 @@ "title": "X-Axis Visibility Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2alpha1.json index 474b22d4ffb..97a0dd7d19c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2alpha1.json @@ -1029,5 +1029,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2beta1.json index 6465fae7ed0..24c49f553ae 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v36.ds_name_to_ref.v42.v2beta1.json @@ -1065,5 +1065,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2alpha1.json index eb254828d3e..7dc1d5c7069 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2alpha1.json @@ -111,6 +111,10 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "displayMode": "list", "showLegend": false @@ -207,6 +211,10 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "displayMode": "list", "showLegend": false @@ -629,5 +637,10 @@ "title": "V37 Legend Normalization Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2beta1.json index 2803cc68947..ba78f73005d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v37.legend_normalization.v42.v2beta1.json @@ -115,6 +115,10 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "displayMode": "list", "showLegend": false @@ -214,6 +218,10 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + }, "legend": { "displayMode": "list", "showLegend": false @@ -642,5 +650,10 @@ "title": "V37 Legend Normalization Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2alpha1.json index 92f6ec2ef8e..89dd54e3bf6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2alpha1.json @@ -443,7 +443,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -659,5 +664,10 @@ "title": "V38 Table Migration Comprehensive Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2beta1.json index 493b6147404..546c73663d6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.table_displaymode_comprehensive.v42.v2beta1.json @@ -455,7 +455,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -671,5 +676,10 @@ "title": "V38 Table Migration Comprehensive Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2alpha1.json index a1fb5ca81af..92dce415c0d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2alpha1.json @@ -443,7 +443,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -659,5 +664,10 @@ "title": "V38 Table Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2beta1.json index 81cc875df07..7d89cc8bbdd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v38.timeseries_table_display_mode.v42.v2beta1.json @@ -455,7 +455,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -671,5 +676,10 @@ "title": "V38 Table Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2alpha1.json index 37eb51fbdff..8d382676f16 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2alpha1.json @@ -217,7 +217,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -396,7 +401,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -586,5 +596,10 @@ "title": "V39 TimeSeriesTable Transformation Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2beta1.json index 3b56960e026..fe92c7f9537 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v39.transform_timeseries_table.v42.v2beta1.json @@ -222,7 +222,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -406,7 +411,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -596,5 +606,10 @@ "title": "V39 TimeSeriesTable Transformation Migration Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2alpha1.json index e6701e601c7..45615b7ae44 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +115,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +164,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -237,5 +252,10 @@ "title": "V4 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2beta1.json index b6d1aa7d200..3a7e5420f11 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v4.no-op.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +120,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +171,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -244,5 +259,10 @@ "title": "V4 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2alpha1.json index 10f6bbf20f4..40df255245e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Empty String Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2beta1.json index a6cabe62d43..44136818b17 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_empty_string.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Empty String Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2alpha1.json index 13a901e94af..e149f9f6a45 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Boolean False Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2beta1.json index 7b5f900ef36..0499fbc7328 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_false.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Boolean False Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2alpha1.json index 04b94fc3919..95b61ef4e22 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Refresh Not Set Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2beta1.json index 1f09949f995..93ce85b17e1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_not_set.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Refresh Not Set Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2alpha1.json index 103fe15fdf3..fd250ce03c6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Numeric Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2beta1.json index 6904267e72b..f81e1b004e9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_numeric.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Numeric Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2alpha1.json index 9fe42b778dd..94fa361257d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "String Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2beta1.json index b1bd81269c1..f8818a9dbf3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_string.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "String Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2alpha1.json index 3524796f0aa..bd9f897d313 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Boolean Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2beta1.json index 76eea7dbbdc..eecd119a617 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v40.refresh_true.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Boolean Refresh Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2alpha1.json index 9036e54f22d..ed1ea8dc001 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "No Time Picker Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2beta1.json index 54e2cfeef43..6b3b49c11e5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.no_time_picker.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "No Time Picker Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2alpha1.json index 78e27ac4411..2806b7c6d8d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Time Picker No Time Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2beta1.json index 52de1909de4..5b9595d8f74 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_no_time_options.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Time Picker No Time Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2alpha1.json index 8115f687203..a48695c53ec 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2alpha1.json @@ -64,5 +64,10 @@ "title": "Time Picker Time Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2beta1.json index 9dffb1fc27e..3f31b897bf0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v41.time_picker_time_options.v42.v2beta1.json @@ -65,5 +65,10 @@ "title": "Time Picker Time Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2alpha1.json index ee97abbd7e2..6aa423b4431 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2alpha1.json @@ -123,5 +123,10 @@ "title": "v42 Migration Test - Harky Must", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2beta1.json index 3d267c3135b..79648901fc2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.harky_must.v42.v2beta1.json @@ -125,5 +125,10 @@ "title": "v42 Migration Test - Harky Must", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2alpha1.json index d231c6561ad..e019782a68b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2alpha1.json @@ -94,7 +94,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [ @@ -328,7 +333,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -461,5 +466,10 @@ "title": "v42 Migration Test - HideFrom Tooltip", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2beta1.json index a1e187676a5..f97c257c251 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v42.hidefrom_tooltip.v42.v2beta1.json @@ -97,7 +97,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [ @@ -335,7 +340,7 @@ "kind": "RowsLayoutRow", "spec": { "title": "", - "collapse": true, + "collapse": false, "hideHeader": true, "layout": { "kind": "GridLayout", @@ -468,5 +473,10 @@ "title": "v42 Migration Test - HideFrom Tooltip", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2alpha1.json index 3c5f977cf19..a1fc7ad4752 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +115,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +164,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -237,5 +252,10 @@ "title": "V5 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2beta1.json index 10544c3c0fe..860ab47b3ea 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v5.no-op.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +120,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +171,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -244,5 +259,10 @@ "title": "V5 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2alpha1.json index 5c98e01c0f0..6ca93a6768a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2alpha1.json @@ -108,7 +108,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +159,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -332,5 +342,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2beta1.json index 19fbf9be88f..0fa353e9a30 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v6.pulldowns_and_templating.v42.v2beta1.json @@ -113,7 +113,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +166,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -344,5 +354,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2alpha1.json index 425516baea9..10b57eb4b69 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2alpha1.json @@ -142,5 +142,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2beta1.json index 72cb9aadb9b..252a510f233 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v7.timepicker.v42.v2beta1.json @@ -146,5 +146,10 @@ "title": "No Title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2alpha1.json index 0bf433b534a..1bdd08aecf5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2alpha1.json @@ -119,7 +119,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -177,7 +182,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -247,5 +257,10 @@ "title": "V8 InfluxDB Query Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2beta1.json index d8ee1076605..ed5b9515a9f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v8.influxdb_query.v42.v2beta1.json @@ -122,7 +122,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -182,7 +187,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -252,5 +262,10 @@ "title": "V8 InfluxDB Query Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2alpha1.json index 0e4ea43800d..b69579db16b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2alpha1.json @@ -66,7 +66,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -110,7 +115,12 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +164,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -237,5 +252,10 @@ "title": "V9 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2beta1.json index 45487aaebb9..2f8f9c79a0b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/migrated_dashboards_output/v1beta1-mig-v9.no-op.v42.v2beta1.json @@ -69,7 +69,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -115,7 +120,12 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +171,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -244,5 +259,10 @@ "title": "V9 No-Op Migration Test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2alpha1.json index 59ed9c457a1..c7f21881b4c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2alpha1.json @@ -558,5 +558,10 @@ "title": "Annotation filtering", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2beta1.json index 26e6d792f59..b7a613fc48b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.annotation-filtering.v42.v2beta1.json @@ -570,5 +570,10 @@ "title": "Annotation filtering", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2alpha1.json index 5449d222a2c..b6addcc81ed 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2alpha1.json @@ -1368,5 +1368,10 @@ "title": "Multi-lane annotations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2beta1.json index e23c11c69ef..f806e27a98f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/annotations/v0alpha1.multi-lane-annotations.v42.v2beta1.json @@ -1393,5 +1393,10 @@ "title": "Multi-lane annotations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2alpha1.json index 253b6471087..5fb32832089 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2alpha1.json @@ -7244,5 +7244,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2beta1.json index 54edeecb540..3ab6bb18228 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_complex.v42.v2beta1.json @@ -7345,5 +7345,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2alpha1.json index 5b384c10afc..f2cd5feadf1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2alpha1.json @@ -13081,5 +13081,10 @@ "title": "Datasource tests - Elasticsearch migration", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2beta1.json index 898dc2b2489..5ba04ac7b23 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_migration.v42.v2beta1.json @@ -13289,5 +13289,10 @@ "title": "Datasource tests - Elasticsearch migration", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2alpha1.json index 9eab3b48079..7cf034e5479 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2alpha1.json @@ -1450,5 +1450,10 @@ "title": "Datasource tests - Elasticsearch simple", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2beta1.json index 35e24952e8a..e358643fc42 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-elasticsearch/v0alpha1.elasticsearch_simple.v42.v2beta1.json @@ -1472,5 +1472,10 @@ "title": "Datasource tests - Elasticsearch simple", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2alpha1.json index 462481754b0..d30cf519eb9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2alpha1.json @@ -164,6 +164,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -239,5 +298,10 @@ "title": "Datasource tests - InfluxDB Logs", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2beta1.json index 7cfd839bf00..def63fe73f1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-logs.v42.v2beta1.json @@ -170,6 +170,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -245,5 +304,10 @@ "title": "Datasource tests - InfluxDB Logs", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2alpha1.json index 3b776907f83..7bd7146240e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2alpha1.json @@ -113,7 +113,78 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "annotate": { + "enable": false + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 2, + "grid": {}, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "resolution": 100, + "scale": 1, + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "query_as_alias": true, + "shared": false, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + }, + "zerofill": true + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -317,5 +388,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2beta1.json index a6ebf10b8f0..943bd4c0a7b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-influxdb/v0alpha1.influxdb-templated.v42.v2beta1.json @@ -117,7 +117,78 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "annotate": { + "enable": false + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 2, + "grid": {}, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "resolution": 100, + "scale": 1, + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "query_as_alias": true, + "shared": false, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + }, + "zerofill": true + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -327,5 +398,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2alpha1.json index d8a362c5029..f6e20264866 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2alpha1.json @@ -615,5 +615,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2beta1.json index 029c2bcf218..01d2f669fe1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_fakedata.v42.v2beta1.json @@ -627,5 +627,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2alpha1.json index e5078c03a19..c3feede3aca 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2alpha1.json @@ -1552,5 +1552,10 @@ "title": "Datasource tests - Loki query splitting", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2beta1.json index c2651fc75a2..6ac4f48fde4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-loki/v0alpha1.loki_query_splitting.v42.v2beta1.json @@ -1577,5 +1577,10 @@ "title": "Datasource tests - Loki query splitting", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2alpha1.json index 3faa6bf6d7b..0f908ced2aa 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2alpha1.json @@ -129,6 +129,74 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -178,7 +246,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -227,6 +333,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -296,6 +461,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -546,5 +770,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2beta1.json index b9acf971b1d..a346f009588 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_fakedata.v42.v2beta1.json @@ -138,6 +138,74 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -189,7 +257,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -240,6 +346,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -312,6 +477,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -566,5 +790,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2alpha1.json index 915a7a7f790..747942f6dc3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2alpha1.json @@ -147,7 +147,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -195,7 +253,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -243,7 +358,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -291,7 +463,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -339,7 +573,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -387,7 +683,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -435,7 +788,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -483,7 +898,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -531,7 +1006,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -579,7 +1116,38 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -627,7 +1195,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -675,7 +1303,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -723,7 +1414,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -771,7 +1525,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -819,7 +1636,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -867,7 +1747,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -915,7 +1858,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -963,7 +1969,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1011,7 +2079,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1059,7 +2187,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1107,7 +2297,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1156,7 +2408,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1205,7 +2495,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1254,7 +2582,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1303,7 +2669,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1351,7 +2755,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1399,7 +2861,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1447,7 +2966,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1514,7 +3095,79 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1562,7 +3215,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1629,7 +3344,79 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1677,7 +3464,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1725,7 +3570,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2280,5 +4183,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2beta1.json index f28e28bdded..fa5c52ae871 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mssql/v0alpha1.mssql_unittest.v42.v2beta1.json @@ -159,7 +159,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -209,7 +267,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -259,7 +374,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -309,7 +481,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -359,7 +593,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -409,7 +705,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -459,7 +812,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -509,7 +924,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -559,7 +1034,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -609,7 +1146,38 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -659,7 +1227,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -709,7 +1337,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -759,7 +1450,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -809,7 +1563,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -859,7 +1676,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -909,7 +1789,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -959,7 +1902,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1009,7 +2015,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1059,7 +2127,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1109,7 +2237,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1159,7 +2349,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1210,7 +2462,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1261,7 +2551,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1312,7 +2640,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1363,7 +2729,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1413,7 +2817,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1463,7 +2925,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1513,7 +3032,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1583,7 +3164,79 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1633,7 +3286,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1703,7 +3418,79 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1753,7 +3540,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1803,7 +3648,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2360,5 +4263,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2alpha1.json index bd3a41d6f40..59f1c712177 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2alpha1.json @@ -128,6 +128,74 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -179,6 +247,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -249,6 +376,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -299,7 +485,46 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "link": false, + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -548,5 +773,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2beta1.json index fbb9f11c316..3f782078e85 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_fakedata.v42.v2beta1.json @@ -137,6 +137,74 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -190,6 +258,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -263,6 +390,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -315,7 +501,46 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "link": false, + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -568,5 +793,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2alpha1.json index 007f6f3f04c..ccfd35d981e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2alpha1.json @@ -147,7 +147,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -195,7 +253,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -243,7 +358,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -291,7 +463,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -339,7 +573,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -387,7 +683,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -435,7 +788,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -483,7 +898,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -531,7 +1006,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -579,7 +1116,38 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -627,7 +1195,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -675,7 +1303,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -723,7 +1414,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -771,7 +1525,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -819,7 +1636,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -867,7 +1747,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -915,7 +1858,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -963,7 +1969,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1011,7 +2079,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1060,7 +2188,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1109,7 +2275,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1158,7 +2362,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1207,7 +2449,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1255,7 +2535,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1303,7 +2641,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1351,7 +2746,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1399,7 +2856,79 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1447,7 +2976,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1495,7 +3086,79 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1543,7 +3206,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1591,7 +3312,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2123,5 +3902,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2beta1.json index 35767416230..643298fb85c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-mysql/v0alpha1.mysql_unittest.v42.v2beta1.json @@ -159,7 +159,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -209,7 +267,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -259,7 +374,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -309,7 +481,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -359,7 +593,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -409,7 +705,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -459,7 +812,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -509,7 +924,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -559,7 +1034,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -609,7 +1146,38 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -659,7 +1227,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -709,7 +1337,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -759,7 +1450,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -809,7 +1563,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -859,7 +1676,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -909,7 +1789,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -959,7 +1902,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1009,7 +2015,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1059,7 +2127,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1110,7 +2238,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1161,7 +2327,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1212,7 +2416,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time_sec", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1263,7 +2505,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1313,7 +2593,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1363,7 +2701,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1413,7 +2808,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1463,7 +2920,79 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1513,7 +3042,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1563,7 +3154,79 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "MovingAverageValueOne", + "dashes": true, + "lines": false + }, + { + "alias": "MovingAverageValueTwo", + "dashes": true, + "lines": false, + "yaxis": 1 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1613,7 +3276,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1663,7 +3384,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2197,5 +3976,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2alpha1.json index 71e90cc1bac..893d135c144 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2alpha1.json @@ -68,6 +68,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -119,6 +178,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -194,5 +312,10 @@ "title": "Datasource tests - OpenTSDB", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2beta1.json index 9566977e001..5086e9f987d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb.v42.v2beta1.json @@ -72,6 +72,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -125,6 +184,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -200,5 +318,10 @@ "title": "Datasource tests - OpenTSDB", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2alpha1.json index ccd7b7cac51..deb7d353db8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2alpha1.json @@ -84,6 +84,65 @@ "spec": { "pluginVersion": "8.1.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -148,6 +207,65 @@ "spec": { "pluginVersion": "8.1.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -219,5 +337,10 @@ "title": "Datasource tests - OpenTSDB v2.3", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2beta1.json index dd46ba3407a..342f5a0a94c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-opentsdb/v0alpha1.opentsdb_v23.v42.v2beta1.json @@ -88,6 +88,65 @@ "version": "8.1.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -154,6 +213,65 @@ "version": "8.1.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -225,5 +343,10 @@ "title": "Datasource tests - OpenTSDB v2.3", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2alpha1.json index dd5972aef39..0e222d96742 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2alpha1.json @@ -170,6 +170,74 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -221,6 +289,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -291,6 +418,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -341,7 +527,46 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "link": false, + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -590,5 +815,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2beta1.json index 707c89428e3..9ece61d256d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_fakedata.v42.v2beta1.json @@ -179,6 +179,74 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "total avg": "#6ed0e0" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "total avg", + "fill": 0, + "pointradius": 3, + "points": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -232,6 +300,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -305,6 +432,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -357,7 +543,46 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "link": false, + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -610,5 +835,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2alpha1.json index 1b70b5d07eb..a7bec316030 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2alpha1.json @@ -147,7 +147,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -195,7 +253,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -243,7 +358,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -291,7 +463,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -339,7 +573,69 @@ "kind": "bargauge", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -387,7 +683,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -435,7 +788,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -483,7 +898,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -531,7 +1006,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -579,7 +1116,38 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 1, + "desc": false + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -627,7 +1195,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -675,7 +1303,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -723,7 +1414,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -771,7 +1525,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -819,7 +1636,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -867,7 +1747,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -915,7 +1858,70 @@ "kind": "histogram", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -963,7 +1969,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1011,7 +2079,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1060,7 +2188,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1109,7 +2275,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1158,7 +2362,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1207,7 +2449,45 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1255,7 +2535,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1303,7 +2641,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1351,7 +2746,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1399,7 +2856,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1447,7 +2964,69 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1495,7 +3074,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1543,7 +3182,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1591,7 +3288,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2121,5 +3876,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2beta1.json index 7878e91dac5..ce0dd08d44d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-postgres/v0alpha1.postgres_unittest.v42.v2beta1.json @@ -159,7 +159,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -209,7 +267,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -259,7 +374,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -309,7 +481,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -359,7 +593,69 @@ "group": "bargauge", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -409,7 +705,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -459,7 +812,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -509,7 +924,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -559,7 +1034,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -609,7 +1146,38 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 1, + "desc": false + }, + "styles": [ + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "string", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -659,7 +1227,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": true, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -709,7 +1337,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -759,7 +1450,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 100, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -809,7 +1563,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -859,7 +1676,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": true, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -909,7 +1789,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 50, + "mode": "histogram", + "show": true, + "values": [ + "current" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -959,7 +1902,70 @@ "group": "histogram", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": false, + "total": true, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "buckets": 20, + "mode": "histogram", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1009,7 +2015,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1059,7 +2127,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1110,7 +2238,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1161,7 +2327,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1212,7 +2416,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1263,7 +2505,45 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1313,7 +2593,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1363,7 +2701,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1413,7 +2808,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1463,7 +2920,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1513,7 +3030,69 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "hideEmpty": false, + "hideZero": false, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1563,7 +3142,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1613,7 +3252,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1663,7 +3360,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 3, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": true, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -2195,5 +3950,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2alpha1.json index 58f0b2cf4df..d7dded5b99f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2alpha1.json @@ -1371,5 +1371,10 @@ "title": "Bar Gauge Demo Unfilled", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2beta1.json index b1046fe5ca3..f1d552852e8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.bar-gauge-demo2.v42.v2beta1.json @@ -1434,5 +1434,10 @@ "title": "Bar Gauge Demo Unfilled", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2alpha1.json index 9f0da1593eb..d31a3f25ea2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2alpha1.json @@ -1698,5 +1698,10 @@ "title": "TestData - Demo Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2beta1.json index 3e11006d1de..74943a89cf9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.demo1.v42.v2beta1.json @@ -1745,5 +1745,10 @@ "title": "TestData - Demo Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2alpha1.json index ca657342364..e557b4f80a6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2alpha1.json @@ -2880,5 +2880,10 @@ "title": "New Features in v7.4", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2beta1.json index 0c8b7143a91..0ad4e83973b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v74.v42.v2beta1.json @@ -2955,5 +2955,10 @@ "title": "New Features in v7.4", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2alpha1.json index dcfd34332f4..ad6e731fd8d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2alpha1.json @@ -3951,5 +3951,10 @@ "title": "New Features in v8.0", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2beta1.json index 93b501b2222..4f087f02750 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/datasource-testdata/v0alpha1.new_features_in_v8.v42.v2beta1.json @@ -4072,5 +4072,10 @@ "title": "New Features in v8.0", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2alpha1.json index 28ea4680f2e..160c0cdf458 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2alpha1.json @@ -673,5 +673,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2beta1.json index af64f4a2f02..8d1436def13 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-Kitchen-Sink.v42.v2beta1.json @@ -687,5 +687,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2alpha1.json index 5f7f66dd3cc..1629c425da7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2alpha1.json @@ -261,5 +261,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2beta1.json index a4681683ba5..fd375b98fed 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-horizontally.v42.v2beta1.json @@ -263,5 +263,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2alpha1.json index f8f9922016b..dde9ab81f9c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2alpha1.json @@ -269,5 +269,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2beta1.json index 96c5247c4f4..04266fae41b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-panel-vertically.v42.v2beta1.json @@ -274,5 +274,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2alpha1.json index e7e365773f1..f1ef5ec1c11 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2alpha1.json @@ -326,5 +326,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2beta1.json index 8cb12e2e45f..8344ab2fd3e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-horizontal-panel.v42.v2beta1.json @@ -331,5 +331,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2alpha1.json index 62c2ef1f9bc..b3c25fda752 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2alpha1.json @@ -326,5 +326,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2beta1.json index 4e7764ff205..facb775e9f1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-a-row-with-a-repeating-vertical-panel.v42.v2beta1.json @@ -331,5 +331,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2alpha1.json index cc3254f517b..f4a9ccc966a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2alpha1.json @@ -210,5 +210,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2beta1.json index df7016f1969..79c21a744ec 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/e2e-repeats/v0alpha1.Repeating-an-empty-row.v42.v2beta1.json @@ -212,5 +212,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2alpha1.json index 3d8e275556b..d3e309f9d05 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2alpha1.json @@ -469,5 +469,10 @@ "title": "Link Extensions (onClick)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2beta1.json index a783ef609f2..2d1d0f2e529 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-onclick-extensions.v42.v2beta1.json @@ -482,5 +482,10 @@ "title": "Link Extensions (onClick)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2alpha1.json index 98e0b3fd047..fc48dd77960 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2alpha1.json @@ -327,5 +327,10 @@ "title": "Link Extensions (path)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2beta1.json index 5376f4e3832..8c998ee4b2c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/extensions/v0alpha1.link-path-extensions.v42.v2beta1.json @@ -333,5 +333,10 @@ "title": "Link Extensions (path)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2alpha1.json index 2f913de363f..1ed897f3cc8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2alpha1.json @@ -1167,5 +1167,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2beta1.json index 614ac4cabec..40cc11e8cb9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.datadata-macros.v42.v2beta1.json @@ -1201,5 +1201,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2alpha1.json index 6b40487f1d0..2b16e9ce76b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2alpha1.json @@ -168,5 +168,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2beta1.json index 0bd988b9902..59e7b0a96bc 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.global-variables-and-interpolation.v42.v2beta1.json @@ -172,5 +172,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2alpha1.json index abab61bd552..7480afb75db 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2alpha1.json @@ -205,5 +205,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2beta1.json index 4fc9cedb62a..cd93214ebc3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-dashboard-links-and-variables.v42.v2beta1.json @@ -209,5 +209,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2alpha1.json index 2d423c83c3d..f8f7fbc5350 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2alpha1.json @@ -565,5 +565,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2beta1.json index 2be4b39a06f..897abd7a0c7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-panels.v42.v2beta1.json @@ -574,5 +574,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2alpha1.json index 17ee9515ded..85cb38c13ff 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2alpha1.json @@ -485,5 +485,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2beta1.json index fbe90caa7bd..a1ec03cd26a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-repeating-rows.v42.v2beta1.json @@ -491,5 +491,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2alpha1.json index 05b4c6ed70c..123f410cac0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2alpha1.json @@ -136,5 +136,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2beta1.json index c9ba98c312b..0f3f2ab00a2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.templating-textbox-e2e-scenarios.v42.v2beta1.json @@ -140,5 +140,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2alpha1.json index 16148c1ab23..6eb2f2493aa 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2alpha1.json @@ -86,6 +86,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [ { "targetBlank": false, @@ -354,6 +412,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [ { "targetBlank": false, @@ -579,5 +695,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2beta1.json index 1f8d4d5eee6..22814d61a1e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-datalinks.v42.v2beta1.json @@ -91,6 +91,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [ { "targetBlank": false, @@ -367,6 +425,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [ { "targetBlank": false, @@ -592,5 +708,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2alpha1.json index 171b505001e..a469d4020e5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2alpha1.json @@ -62,6 +62,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -163,7 +221,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -334,5 +453,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2beta1.json index 4b2a7a98790..0a46a76d48e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables-drilldown.v42.v2beta1.json @@ -67,6 +67,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -172,7 +230,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -349,5 +468,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2alpha1.json index 837c5cbfa5a..ecc156114f4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2alpha1.json @@ -167,6 +167,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -264,7 +323,59 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -639,5 +750,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2beta1.json index 2b61b379a04..54d6e9efa1c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-nested-variables.v42.v2beta1.json @@ -174,6 +174,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -276,7 +335,59 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -661,5 +772,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2alpha1.json index efa298e1ec2..9eaf955bb68 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2alpha1.json @@ -247,5 +247,10 @@ "title": "Test variable output", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2beta1.json index 17fa40a073b..395867814e0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-test-variable-output.v42.v2beta1.json @@ -255,5 +255,10 @@ "title": "Test variable output", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2alpha1.json index 8ae6fb9f2cd..81d61c2509b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2alpha1.json @@ -171,6 +171,65 @@ "spec": { "pluginVersion": "7.2.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -259,5 +318,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2beta1.json index b07bdc72f60..01936dded6b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-textbox.v42.v2beta1.json @@ -177,6 +177,65 @@ "version": "7.2.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -265,5 +324,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2alpha1.json index 08f14e2614f..7eb15579259 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2alpha1.json @@ -84,6 +84,67 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": true, + "rightSide": true, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -198,5 +259,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2beta1.json index a1ff094b67b..c89000daee7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/feature-templating/v0alpha1.testdata-variables-that-update-on-time-change.v42.v2beta1.json @@ -89,6 +89,67 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": true, + "rightSide": true, + "show": true, + "total": false, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -207,5 +268,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2alpha1.json index f71a17e660d..83c4dd25a5c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2alpha1.json @@ -536,5 +536,10 @@ "title": "Live flakey stream (w/ liveNow)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2beta1.json index 892812351b8..89bea6fc4d4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey-refresh.v42.v2beta1.json @@ -545,5 +545,10 @@ "title": "Live flakey stream (w/ liveNow)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2alpha1.json index abf4e4cdcef..017171df8ef 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2alpha1.json @@ -536,5 +536,10 @@ "title": "Live flakey stream", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2beta1.json index 68c0083c4ab..32cec1120c6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-flakey.v42.v2beta1.json @@ -545,5 +545,10 @@ "title": "Live flakey stream", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2alpha1.json index f3777d0eedd..ca4649e18a8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2alpha1.json @@ -707,5 +707,10 @@ "title": "Live publish test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2beta1.json index 66e94e73744..e87b98713e2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-publish.v42.v2beta1.json @@ -720,5 +720,10 @@ "title": "Live publish test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2alpha1.json index efe66b835b3..ebe0f2098d8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2alpha1.json @@ -1034,5 +1034,10 @@ "title": "Live streaming examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2beta1.json index 5ad3b53ea98..051a06f0f94 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/live/v0alpha1.live-streams.v42.v2beta1.json @@ -1054,5 +1054,10 @@ "title": "Live streaming examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2alpha1.json index f8826a3a699..3c2a1a4f9d7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2alpha1.json @@ -123,6 +123,42 @@ "spec": { "pluginVersion": "9.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + }, "cellHeight": "sm", "footer": { "countRows": false, @@ -270,6 +306,10 @@ "spec": { "pluginVersion": "9.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-piechart-panel", + "originalOptions": {} + }, "legend": { "displayMode": "list", "placement": "bottom", @@ -402,6 +442,41 @@ "spec": { "pluginVersion": "10.4.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-worldmap-panel", + "originalOptions": { + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 0, + "esMetric": "Count", + "hideEmpty": false, + "hideZero": false, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "mouseWheelZoom": false, + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "thresholds": "0,10", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + } + }, "basemap": { "name": "Basemap", "type": "default" @@ -562,6 +637,69 @@ "spec": { "pluginVersion": "11.0.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -667,6 +805,67 @@ "spec": { "pluginVersion": "11.0.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -775,6 +974,70 @@ "spec": { "pluginVersion": "11.3.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -880,6 +1143,65 @@ "spec": { "pluginVersion": "11.0.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -1031,7 +1353,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1469,5 +1852,10 @@ "title": "Devenv - Panel migrations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2beta1.json index 8eea5775903..c6a9186b9e0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/migrations/v0alpha1.migrations.v42.v2beta1.json @@ -130,6 +130,42 @@ "version": "9.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + }, "cellHeight": "sm", "footer": { "countRows": false, @@ -283,6 +319,10 @@ "version": "9.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-piechart-panel", + "originalOptions": {} + }, "legend": { "displayMode": "list", "placement": "bottom", @@ -421,6 +461,41 @@ "version": "10.4.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-worldmap-panel", + "originalOptions": { + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 0, + "esMetric": "Count", + "hideEmpty": false, + "hideZero": false, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "mouseWheelZoom": false, + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "thresholds": "0,10", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + } + }, "basemap": { "name": "Basemap", "type": "default" @@ -587,6 +662,69 @@ "version": "11.0.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -698,6 +836,67 @@ "version": "11.0.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -811,6 +1010,70 @@ "version": "11.3.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -922,6 +1185,65 @@ "version": "11.0.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true, "legend": { "calcs": [], @@ -1082,7 +1404,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1520,5 +1903,10 @@ "title": "Devenv - Panel migrations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2alpha1.json index 78f2a2b6030..058a8806a5e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2alpha1.json @@ -859,5 +859,10 @@ "title": "BarChart - Panel Tests - Value sizing", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2beta1.json index c60ab8343a6..6c3fa8ae1a9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-autosizing.v42.v2beta1.json @@ -880,5 +880,10 @@ "title": "BarChart - Panel Tests - Value sizing", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2alpha1.json index 8f969cbef36..0f77a66f203 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2alpha1.json @@ -428,5 +428,10 @@ "title": "BarChart - Label Rotation \u0026 Skipping", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2beta1.json index 9290dd4ff14..3ad88c72861 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-label-rotation-skipping.v42.v2beta1.json @@ -437,5 +437,10 @@ "title": "BarChart - Label Rotation \u0026 Skipping", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2alpha1.json index 522857ab19a..8bc7997b3d4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2alpha1.json @@ -535,5 +535,10 @@ "title": "BarChart - Panel Tests - Series toggle / bar widths", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2beta1.json index 9459814d20b..7a04ed00d31 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-series-toggle.v42.v2beta1.json @@ -548,5 +548,10 @@ "title": "BarChart - Panel Tests - Series toggle / bar widths", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2alpha1.json index f25d5355ccc..e5369a162f7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2alpha1.json @@ -1682,5 +1682,10 @@ "title": "BarChart - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2beta1.json index 0d8c2dbf2a1..208c4c112c0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-thresholds-mappings.v42.v2beta1.json @@ -1721,5 +1721,10 @@ "title": "BarChart - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2alpha1.json index db478ad7e3d..bd95597bf13 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2alpha1.json @@ -1127,5 +1127,10 @@ "title": "Panel Tests - Bar Chart Tooltips \u0026 Legends", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2beta1.json index 4ea638cf0eb..3109835cd91 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-barchart/v0alpha1.barchart-tooltips-legends.v42.v2beta1.json @@ -1155,5 +1155,10 @@ "title": "Panel Tests - Bar Chart Tooltips \u0026 Legends", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2alpha1.json index 0e540c7e66e..290ee546192 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2alpha1.json @@ -1412,5 +1412,10 @@ "title": "Bar Gauge Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2beta1.json index cc190aaa2e0..ebfa6d31425 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.bar_gauge_demo.v42.v2beta1.json @@ -1548,5 +1548,10 @@ "title": "Bar Gauge Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2alpha1.json index c88ce3b28e1..bd408ee62ee 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2alpha1.json @@ -1922,5 +1922,10 @@ "title": "Panel Tests - Bar Gauge", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2beta1.json index 1aa4b0e1a85..cc604bc2045 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge.v42.v2beta1.json @@ -2052,5 +2052,10 @@ "title": "Panel Tests - Bar Gauge", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2alpha1.json index 4f782695385..2aa2d935923 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2alpha1.json @@ -1214,5 +1214,10 @@ "title": "Panel Tests - Bar Gauge 2", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2beta1.json index 777a64366ba..92be6f0c11c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-bargauge/v0alpha1.panel_tests_bar_gauge2.v42.v2beta1.json @@ -1262,5 +1262,10 @@ "title": "Panel Tests - Bar Gauge 2", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2alpha1.json index 97283f755fb..6d92fbd46bb 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2alpha1.json @@ -640,5 +640,10 @@ "title": "Candlestick", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2beta1.json index 83ab2dd5571..0ce4c776fb5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-candlestick/v0alpha1.candlestick.v42.v2beta1.json @@ -653,5 +653,10 @@ "title": "Candlestick", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2alpha1.json index f5cb9c3c909..2976d37dc0f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2alpha1.json @@ -4064,5 +4064,10 @@ "title": "Panel Tests - Canvas Connection Examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2beta1.json index 49910daa683..47fb71205e2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-connection-examples.v42.v2beta1.json @@ -4074,5 +4074,10 @@ "title": "Panel Tests - Canvas Connection Examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2alpha1.json index e5648af2325..c9e5b0662df 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2alpha1.json @@ -3503,5 +3503,10 @@ "title": "Panel Tests - Canvas Datalinks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2beta1.json index 8f705b659b6..d63bb93d321 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-datalinks.v42.v2beta1.json @@ -3506,5 +3506,10 @@ "title": "Panel Tests - Canvas Datalinks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2alpha1.json index b32f594a99e..8d2bdc0d36c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2alpha1.json @@ -4096,5 +4096,10 @@ "title": "Panel Tests - Canvas Examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2beta1.json index aa7b95b6dca..0c650fd4f87 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-canvas/v0alpha1.canvas-examples.v42.v2beta1.json @@ -4113,5 +4113,10 @@ "title": "Panel Tests - Canvas Examples", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2alpha1.json index 7d0174aecaa..42c2a374b1c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2alpha1.json @@ -66,6 +66,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "label": "", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -115,6 +175,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -164,6 +284,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "none", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -213,6 +393,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -262,6 +502,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "µs", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -311,6 +609,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -360,6 +718,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -409,6 +825,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "none", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -458,6 +934,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -507,6 +1043,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -556,6 +1150,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -605,6 +1259,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -654,6 +1366,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -871,5 +1642,10 @@ "title": "Panel Tests - Auto Decimals", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2beta1.json index c2083797bdf..c1013a5bdcd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.auto_decimals.v42.v2beta1.json @@ -70,6 +70,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "label": "", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -121,6 +181,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -172,6 +292,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "none", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -223,6 +403,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -274,6 +514,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "µs", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -325,6 +623,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -376,6 +734,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -427,6 +843,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "none", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -478,6 +954,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -529,6 +1065,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -580,6 +1174,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -631,6 +1285,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -682,6 +1394,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -899,5 +1670,10 @@ "title": "Panel Tests - Auto Decimals", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2alpha1.json index 12d4efa68b6..bcb9fba2fe9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2alpha1.json @@ -471,5 +471,10 @@ "title": "Gradient Color modes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2beta1.json index 3c1e8803dda..54a0b0d198d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.color_modes.v42.v2beta1.json @@ -481,5 +481,10 @@ "title": "Gradient Color modes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2alpha1.json index 379d5597285..92b60103171 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2alpha1.json @@ -132,7 +132,68 @@ "kind": "stat", "spec": { "pluginVersion": "6.2.0-pre", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p99", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -176,7 +237,68 @@ "kind": "stat", "spec": { "pluginVersion": "6.2.0-pre", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p95", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -220,7 +342,68 @@ "kind": "stat", "spec": { "pluginVersion": "6.2.0-pre", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p90", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -302,6 +485,71 @@ "spec": { "pluginVersion": "6.2.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -347,6 +595,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -392,6 +700,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "red" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 10, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 0, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -476,6 +844,71 @@ "spec": { "pluginVersion": "6.2.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -521,6 +954,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 8, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -566,7 +1057,68 @@ "kind": "stat", "spec": { "pluginVersion": "6.2.0-pre", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p90", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -610,6 +1162,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -655,6 +1267,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -700,6 +1372,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -745,6 +1477,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -790,6 +1582,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -835,6 +1687,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "purple" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -880,6 +1792,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "orange" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -964,6 +1936,71 @@ "spec": { "pluginVersion": "6.2.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1009,6 +2046,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1054,6 +2151,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1099,6 +2256,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "purple" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1144,6 +2361,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "orange" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -2073,5 +3350,10 @@ "title": "Lazy Loading", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2beta1.json index 2767a76315e..b1b07fa0f56 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.lazy_loading.v42.v2beta1.json @@ -140,7 +140,68 @@ "group": "stat", "version": "6.2.0-pre", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p99", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -187,7 +248,68 @@ "group": "stat", "version": "6.2.0-pre", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p95", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -234,7 +356,68 @@ "group": "stat", "version": "6.2.0-pre", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p90", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -325,6 +508,71 @@ "version": "6.2.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -373,6 +621,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -421,6 +729,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "red" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 10, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 0, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -514,6 +882,71 @@ "version": "6.2.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -562,6 +995,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 8, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -610,7 +1101,68 @@ "group": "stat", "version": "6.2.0-pre", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "#73BF69", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "p90", + "prefixFontSize": "80%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -657,6 +1209,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -705,6 +1317,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -753,6 +1425,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -801,6 +1533,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -849,6 +1641,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -897,6 +1749,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "purple" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -945,6 +1857,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "orange" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1038,6 +2010,71 @@ "version": "6.2.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue", + "B-series": "dark-purple", + "C-series": "purple", + "Q-series": "dark-blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 3, + "fillGradient": 0, + "legend": { + "alignAsTable": true, + "avg": false, + "current": false, + "max": false, + "min": false, + "rightSide": true, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1086,6 +2123,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1134,6 +2231,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "blue" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1182,6 +2339,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "purple" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -1230,6 +2447,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "orange" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -2229,5 +3506,10 @@ "title": "Lazy Loading", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2alpha1.json index 03cea1fc2c8..ce9d8e17187 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2alpha1.json @@ -1843,5 +1843,10 @@ "title": "Panel \u0026 data links in stat, gauge and bargauge", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2beta1.json index 6fbdb415483..fe5fbfda4aa 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.linked-viz.v42.v2beta1.json @@ -1881,5 +1881,10 @@ "title": "Panel \u0026 data links in stat, gauge and bargauge", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2alpha1.json index 5723bef32ca..0572d6b73c0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2alpha1.json @@ -67,7 +67,68 @@ "kind": "stat", "spec": { "pluginVersion": "6.2.0-pre", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -258,7 +319,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -354,7 +473,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -515,7 +695,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -676,7 +917,65 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -819,7 +1118,68 @@ "kind": "stat", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1107,5 +1467,10 @@ "title": "Panel Tests - With \u0026 Without title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2beta1.json index 93173c86f2b..deca04a6634 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.panels_without_title.v42.v2beta1.json @@ -71,7 +71,68 @@ "group": "stat", "version": "6.2.0-pre", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "none", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": true, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": false + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -268,7 +329,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -368,7 +487,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -534,7 +714,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -700,7 +941,65 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -847,7 +1146,68 @@ "group": "stat", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "singlestat", + "originalOptions": { + "colorBackground": false, + "colorValue": false, + "colors": [ + "#299c46", + "#5794F2", + "#d44a3a" + ], + "format": "ms", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "", + "postfixFontSize": "50%", + "prefix": "", + "prefixFontSize": "100%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": true, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "120%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1137,5 +1497,10 @@ "title": "Panel Tests - With \u0026 Without title", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2alpha1.json index 15f76709e5e..0c5ddf56280 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2alpha1.json @@ -614,5 +614,10 @@ "title": "Datasource tests - Shared Queries", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2beta1.json index be9740c4b92..15ca6962fc8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-common/v0alpha1.shared_queries.v42.v2beta1.json @@ -630,5 +630,10 @@ "title": "Datasource tests - Shared Queries", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2alpha1.json index d28a40a68f1..08343d13d55 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2alpha1.json @@ -139,5 +139,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2beta1.json index aedaf24d379..aaf9456f795 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-dashlist/v0alpha1.dashlist.v42.v2beta1.json @@ -141,5 +141,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2alpha1.json index 7b820200d04..1a01292a17e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2alpha1.json @@ -138,5 +138,10 @@ "title": "Datagrid example", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2beta1.json index ec12c171f3a..fc5049c6d79 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-datagrid/v0alpha1.datagrid_metric_values.v42.v2beta1.json @@ -144,5 +144,10 @@ "title": "Datagrid example", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2alpha1.json index 2ca31f3255f..69033e3dfc5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2alpha1.json @@ -130,5 +130,10 @@ "title": "Panel Tests - Flame Graph", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2beta1.json index 10b0b3ed930..982f4088303 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-flamegraph/v0alpha1.panel_tests_flame_graph.v42.v2beta1.json @@ -134,5 +134,10 @@ "title": "Panel Tests - Flame Graph", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2alpha1.json index f9046bea886..706d0bafd47 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2alpha1.json @@ -499,5 +499,10 @@ "title": "Panel Tests - Gauge Multi Series", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2beta1.json index da3a0f5e6f1..d0cbc9aa44e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge-multi-series.v42.v2beta1.json @@ -534,5 +534,10 @@ "title": "Panel Tests - Gauge Multi Series", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2alpha1.json index bd213346a6a..77874ee6291 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2alpha1.json @@ -1429,5 +1429,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2beta1.json index 4e6d53c09ab..663abfbf74c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests.v42.v2beta1.json @@ -1469,5 +1469,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json index 3084bbd32ea..2eeb3040e6d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v1beta1.json @@ -81,10 +81,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -160,10 +160,10 @@ "effects": { "barGlow": false, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -239,10 +239,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -318,10 +318,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -397,10 +397,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -476,10 +476,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -555,10 +555,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -647,10 +647,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -726,10 +726,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -805,10 +805,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -884,10 +884,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -980,10 +980,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1059,10 +1059,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1138,10 +1138,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1217,10 +1217,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1296,10 +1296,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1392,10 +1392,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1475,10 +1475,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1558,10 +1558,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1650,11 +1650,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1736,11 +1736,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1836,11 +1836,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1923,12 +1923,12 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "sparkline": false, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2010,11 +2010,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2096,11 +2096,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json index 5b5c3951ad8..4aecf4e0d9c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2alpha1.json @@ -77,10 +77,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -170,11 +170,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -267,11 +267,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -365,12 +365,12 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "sparkline": false, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -464,11 +464,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -561,11 +561,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -657,10 +657,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -749,10 +749,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -841,10 +841,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -933,10 +933,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1025,10 +1025,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1117,10 +1117,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1205,10 +1205,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1297,10 +1297,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1389,10 +1389,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1481,10 +1481,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1577,10 +1577,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1665,10 +1665,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1757,10 +1757,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1853,10 +1853,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1949,10 +1949,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2049,10 +2049,10 @@ "effects": { "barGlow": false, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2141,10 +2141,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2233,10 +2233,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2326,11 +2326,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2820,5 +2820,10 @@ "title": "Panel tests - Gauge (new)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json index 24125f197c5..6b567f19b5e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_new.v42.v2beta1.json @@ -81,10 +81,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -177,11 +177,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -277,11 +277,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -378,12 +378,12 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "sparkline": false, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -480,11 +480,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -580,11 +580,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -679,10 +679,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -774,10 +774,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -869,10 +869,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -964,10 +964,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1059,10 +1059,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1154,10 +1154,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1245,10 +1245,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1340,10 +1340,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1435,10 +1435,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1530,10 +1530,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1629,10 +1629,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1720,10 +1720,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1815,10 +1815,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1914,10 +1914,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2013,10 +2013,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2116,10 +2116,10 @@ "effects": { "barGlow": false, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2211,10 +2211,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2306,10 +2306,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2402,11 +2402,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2896,5 +2896,10 @@ "title": "Panel tests - Gauge (new)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json index ddad9707104..959f0193ad6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v1beta1.json @@ -961,10 +961,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json index b485fbf84ed..66b29e88d13 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2alpha1.json @@ -864,10 +864,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1614,5 +1614,10 @@ "title": "Panel tests - Old gauge to new", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json index 304058565f1..b870d0a91ad 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-gauge/v0alpha1.gauge_tests_old_to_new.v42.v2beta1.json @@ -901,10 +901,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1666,5 +1666,10 @@ "title": "Panel tests - Old gauge to new", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2alpha1.json index fe6b8e09647..8f6ae2065e2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2alpha1.json @@ -671,5 +671,10 @@ "title": "Geomap - color field Copy", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2beta1.json index ccd502e8e11..e567e6dbae2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-color-field.v42.v2beta1.json @@ -683,5 +683,10 @@ "title": "Geomap - color field Copy", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2alpha1.json index f55700a79cd..135c8d98558 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2alpha1.json @@ -201,5 +201,10 @@ "title": "Panel Tests - Geomap Photo Layer", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2beta1.json index 4a7594b73a9..ce7d1c02a17 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-photo-layer.v42.v2beta1.json @@ -205,5 +205,10 @@ "title": "Panel Tests - Geomap Photo Layer", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2alpha1.json index 92f520e0857..32cc829050d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2alpha1.json @@ -341,5 +341,10 @@ "title": "Panel Tests - Geomap Fit to Data - Multiple Layer Types", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2beta1.json index 82b86117485..758836fdd75 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-route-layer.v42.v2beta1.json @@ -347,5 +347,10 @@ "title": "Panel Tests - Geomap Fit to Data - Multiple Layer Types", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2alpha1.json index 87e64b32650..f6a93ab505e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2alpha1.json @@ -173,5 +173,10 @@ "title": "Panel Tests - Geomap geohash transformer", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2beta1.json index 5184ebb6680..376a2e0b52a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-spatial-operations-transformer.v42.v2beta1.json @@ -177,5 +177,10 @@ "title": "Panel Tests - Geomap geohash transformer", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2alpha1.json index 6ae35916b91..aecc89871f9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2alpha1.json @@ -457,5 +457,10 @@ "title": "Panel Tests - Geomap 9.1", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2beta1.json index a385b59567b..0bbab3d3711 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap-v91.v42.v2beta1.json @@ -467,5 +467,10 @@ "title": "Panel Tests - Geomap 9.1", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2alpha1.json index f7374506e86..d4c2a4a8145 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2alpha1.json @@ -538,5 +538,10 @@ "title": "Panel Tests - Geomap Multi Layers", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2beta1.json index b244899e6d4..4726ddb6e4b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.geomap_multi-layers.v42.v2beta1.json @@ -545,5 +545,10 @@ "title": "Panel Tests - Geomap Multi Layers", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2alpha1.json index 517c35c8e98..209afba2ff2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2alpha1.json @@ -594,5 +594,10 @@ "title": "Panel Tests - Geomap", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2beta1.json index 2d8549a8d89..4fdd338e7bd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-geomap/v0alpha1.panel-geomap.v42.v2beta1.json @@ -607,5 +607,10 @@ "title": "Panel Tests - Geomap", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2alpha1.json index 44ab8d372ff..ef393dae560 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2alpha1.json @@ -66,7 +66,68 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 10, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 0, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -114,7 +175,68 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "rgb(87, 186, 242)" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 4, + "fillGradient": 4, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -162,7 +284,68 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "rgb(48, 139, 237)" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -210,7 +393,68 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "red" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decgbytes", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -310,5 +554,10 @@ "title": "Panel Tests - Graph - Gradient Area Fills", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2beta1.json index 6beb26d4e70..e6def19e038 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-gradient-area-fills.v42.v2beta1.json @@ -70,7 +70,68 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "green" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "fillGradient": 10, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 0, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -120,7 +181,68 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "rgb(87, 186, 242)" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 4, + "fillGradient": 4, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -170,7 +292,68 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "rgb(48, 139, 237)" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -220,7 +403,68 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "red" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 5, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decgbytes", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -320,5 +564,10 @@ "title": "Panel Tests - Graph - Gradient Area Fills", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2alpha1.json index 4628e8234f0..6aab259eb23 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2alpha1.json @@ -63,6 +63,65 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -700,6 +759,65 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "celsius", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -971,5 +1089,10 @@ "title": "Panel Tests - shared tooltips", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2beta1.json index 540a9010d55..2ba9ec92cb6 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-shared-tooltips.v42.v2beta1.json @@ -67,6 +67,65 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -717,6 +776,65 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "celsius", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -990,5 +1108,10 @@ "title": "Panel Tests - shared tooltips", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2alpha1.json index 2dd4dd48907..894c33abef1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2alpha1.json @@ -61,7 +61,78 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "gray", + "fill": true, + "fillColor": "rgba(255, 255, 255, 0.03)", + "from": "08:30", + "fromDayOfWeek": 1, + "line": false, + "lineColor": "rgba(255, 255, 255, 0.2)", + "op": "time", + "to": "16:45", + "toDayOfWeek": 5 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -104,7 +175,140 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "#d683ce" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 0.5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 0, 0, 0.22)", + "from": "", + "fromDayOfWeek": 1, + "line": true, + "lineColor": "rgba(255, 0, 0, 0.32)", + "op": "time", + "to": "", + "toDayOfWeek": 1 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 127, 0, 0.22)", + "fromDayOfWeek": 2, + "line": true, + "lineColor": "rgba(255, 127, 0, 0.32)", + "op": "time", + "toDayOfWeek": 2 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 255, 0, 0.22)", + "fromDayOfWeek": 3, + "line": true, + "lineColor": "rgba(255, 255, 0, 0.22)", + "op": "time", + "toDayOfWeek": 3 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(0, 255, 0, 0.22)", + "fromDayOfWeek": 4, + "line": true, + "lineColor": "rgba(0, 255, 0, 0.32)", + "op": "time", + "toDayOfWeek": 4 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(0, 0, 255, 0.22)", + "fromDayOfWeek": 5, + "line": true, + "lineColor": "rgba(0, 0, 255, 0.32)", + "op": "time", + "toDayOfWeek": 5 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(75, 0, 130, 0.22)", + "fromDayOfWeek": 6, + "line": true, + "lineColor": "rgba(75, 0, 130, 0.32)", + "op": "time", + "toDayOfWeek": 6 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(148, 0, 211, 0.22)", + "fromDayOfWeek": 7, + "line": true, + "lineColor": "rgba(148, 0, 211, 0.32)", + "op": "time", + "toDayOfWeek": 7 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -150,7 +354,78 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "red", + "fill": true, + "fillColor": "rgba(255, 255, 255, 0.03)", + "from": "20:00", + "fromDayOfWeek": 7, + "line": false, + "lineColor": "rgba(255, 255, 255, 0.2)", + "op": "time", + "to": "23:00", + "toDayOfWeek": 7 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -196,7 +471,73 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "red", + "fill": false, + "from": "05:00", + "line": true, + "op": "time" + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -238,7 +579,76 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "gray", + "fill": true, + "fillColor": "rgba(234, 112, 112, 0.12)", + "from": "22:00", + "line": false, + "lineColor": "rgba(237, 46, 24, 0.60)", + "op": "time", + "to": "00:30" + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -351,5 +761,10 @@ "title": "Panel Tests - Graph Time Regions", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2beta1.json index 7a1aa009f08..69aceb23017 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph-time-regions.v42.v2beta1.json @@ -66,7 +66,78 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "gray", + "fill": true, + "fillColor": "rgba(255, 255, 255, 0.03)", + "from": "08:30", + "fromDayOfWeek": 1, + "line": false, + "lineColor": "rgba(255, 255, 255, 0.2)", + "op": "time", + "to": "16:45", + "toDayOfWeek": 5 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -112,7 +183,140 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": { + "A-series": "#d683ce" + }, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 0.5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 0, 0, 0.22)", + "from": "", + "fromDayOfWeek": 1, + "line": true, + "lineColor": "rgba(255, 0, 0, 0.32)", + "op": "time", + "to": "", + "toDayOfWeek": 1 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 127, 0, 0.22)", + "fromDayOfWeek": 2, + "line": true, + "lineColor": "rgba(255, 127, 0, 0.32)", + "op": "time", + "toDayOfWeek": 2 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(255, 255, 0, 0.22)", + "fromDayOfWeek": 3, + "line": true, + "lineColor": "rgba(255, 255, 0, 0.22)", + "op": "time", + "toDayOfWeek": 3 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(0, 255, 0, 0.22)", + "fromDayOfWeek": 4, + "line": true, + "lineColor": "rgba(0, 255, 0, 0.32)", + "op": "time", + "toDayOfWeek": 4 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(0, 0, 255, 0.22)", + "fromDayOfWeek": 5, + "line": true, + "lineColor": "rgba(0, 0, 255, 0.32)", + "op": "time", + "toDayOfWeek": 5 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(75, 0, 130, 0.22)", + "fromDayOfWeek": 6, + "line": true, + "lineColor": "rgba(75, 0, 130, 0.32)", + "op": "time", + "toDayOfWeek": 6 + }, + { + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(148, 0, 211, 0.22)", + "fromDayOfWeek": 7, + "line": true, + "lineColor": "rgba(148, 0, 211, 0.32)", + "op": "time", + "toDayOfWeek": 7 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -161,7 +365,78 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "red", + "fill": true, + "fillColor": "rgba(255, 255, 255, 0.03)", + "from": "20:00", + "fromDayOfWeek": 7, + "line": false, + "lineColor": "rgba(255, 255, 255, 0.2)", + "op": "time", + "to": "23:00", + "toDayOfWeek": 7 + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -210,7 +485,73 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 2, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "red", + "fill": false, + "from": "05:00", + "line": true, + "op": "time" + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -255,7 +596,76 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [ + { + "colorMode": "gray", + "fill": true, + "fillColor": "rgba(234, 112, 112, 0.12)", + "from": "22:00", + "line": false, + "lineColor": "rgba(237, 46, 24, 0.60)", + "op": "time", + "to": "00:30" + } + ], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -368,5 +778,10 @@ "title": "Panel Tests - Graph Time Regions", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2alpha1.json index e251ae6c6db..f93a54ad34d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2alpha1.json @@ -62,7 +62,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -106,7 +166,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -183,7 +303,72 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -404,7 +589,66 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -583,7 +827,66 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -672,7 +975,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -881,7 +1244,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -925,7 +1348,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -969,7 +1452,66 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1030,7 +1572,72 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "C-series", + "steppedLine": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1118,7 +1725,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1164,7 +1831,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1223,7 +1950,74 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "yaxis": 2 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "label": "Percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "label": "Pressure", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1355,7 +2149,67 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1431,7 +2285,72 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1752,5 +2671,10 @@ "title": "Panel Tests - Graph", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2beta1.json index a87d37bc099..d611243ea1d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_tests.v42.v2beta1.json @@ -67,7 +67,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -114,7 +174,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null as zero", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -198,7 +318,72 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -434,7 +619,66 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -634,7 +878,66 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -732,7 +1035,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -966,7 +1329,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "rightSide": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1013,7 +1436,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1060,7 +1543,66 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1126,7 +1668,72 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "C-series", + "steppedLine": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1219,7 +1826,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1268,7 +1935,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1332,7 +2059,74 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "yaxis": 2 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "label": "Percent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "label": "Pressure", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1471,7 +2265,67 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1554,7 +2408,72 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -1875,5 +2794,10 @@ "title": "Panel Tests - Graph", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2alpha1.json index 33b1bd246ee..f060ff213d2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2alpha1.json @@ -66,6 +66,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "label": "", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -115,6 +175,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -164,6 +284,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -213,6 +391,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -262,6 +500,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -311,6 +609,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -360,6 +716,66 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -409,6 +825,64 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -458,6 +932,65 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -623,5 +1156,10 @@ "title": "Panel Tests - Graph - Y axis ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2beta1.json index bf16659bc49..8202a6a7dd7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2beta1.json @@ -70,6 +70,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "label": "", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -121,6 +181,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -172,6 +292,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -223,6 +401,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "bytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -274,6 +512,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "decbytes", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -325,6 +623,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -376,6 +732,66 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "max": "10000", + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -427,6 +843,64 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "ms", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -478,6 +952,65 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "min": "0", + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -643,5 +1176,10 @@ "title": "Panel Tests - Graph - Y axis ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2alpha1.json index a5567148d48..fb399db27f9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2alpha1.json @@ -1113,5 +1113,10 @@ "title": "Heatmap calculate (log)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2beta1.json index 32816087c1d..1721f0b1c1f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-calculate-log.v42.v2beta1.json @@ -1133,5 +1133,10 @@ "title": "Heatmap calculate (log)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2alpha1.json index 69764686c12..4873fe5fc74 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2alpha1.json @@ -414,5 +414,10 @@ "title": "Legacy heatmap", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2beta1.json index 7450f5af8ed..2e11457ec4d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-legacy.v42.v2beta1.json @@ -432,5 +432,10 @@ "title": "Legacy heatmap", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2alpha1.json index fdcb368edc4..2eb67e36f2f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2alpha1.json @@ -542,5 +542,10 @@ "title": "Heatmap X axis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2beta1.json index b6d51918cbc..acba4cedbc2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-heatmap/v0alpha1.heatmap-x.v42.v2beta1.json @@ -554,5 +554,10 @@ "title": "Heatmap X axis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2alpha1.json index cc15b1c4c91..57fbcad9d99 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2alpha1.json @@ -1243,5 +1243,10 @@ "title": "Panel Tests - Histogram", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2beta1.json index 81e56c3d318..5b2ee8d8df2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-histogram/v0alpha1.histogram_tests.v42.v2beta1.json @@ -1276,5 +1276,10 @@ "title": "Panel Tests - Histogram", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2alpha1.json index 2efffd9390c..dc0aab46631 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2alpha1.json @@ -109,6 +109,65 @@ "spec": { "pluginVersion": "7.4.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -193,5 +252,10 @@ "title": "Panel - Panel Library", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2beta1.json index 20438d25434..50419f5a194 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-library/v0alpha1.panel-library.v42.v2beta1.json @@ -113,6 +113,65 @@ "version": "7.4.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -197,5 +256,10 @@ "title": "Panel - Panel Library", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2alpha1.json index 742bed31cf6..84c03baac66 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2alpha1.json @@ -770,5 +770,10 @@ "title": "Panel Tests - Pie chart", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2beta1.json index b79118ec1bb..4e946c6aee9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-piechart/v0alpha1.panel_test_piechart.v42.v2beta1.json @@ -786,5 +786,10 @@ "title": "Panel Tests - Pie chart", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2alpha1.json index 97d355f227a..68c7c2b6529 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2alpha1.json @@ -424,5 +424,10 @@ "title": "Panel Tests - Polystat", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2beta1.json index 46644077d0c..f72f1e3b485 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-polystat/v0alpha1.polystat_test.v42.v2beta1.json @@ -457,5 +457,10 @@ "title": "Panel Tests - Polystat", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2alpha1.json index acb35da6bb8..2074ff4fa12 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2alpha1.json @@ -2768,5 +2768,10 @@ "title": "Panel Tests - Stat", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2beta1.json index fb9f810cfaa..98b11ebadb3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-stat/v0alpha1.panel-stat-tests.v42.v2beta1.json @@ -2883,5 +2883,10 @@ "title": "Panel Tests - Stat", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2alpha1.json index 44db8ddd292..d90c8dc52cd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2alpha1.json @@ -1498,5 +1498,10 @@ "title": "StatusHistory - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2beta1.json index 513bc4d476c..7aaa0fff33a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-status-history/v0alpha1.status-history-thresholds-mappings.v42.v2beta1.json @@ -1537,5 +1537,10 @@ "title": "StatusHistory - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2alpha1.json index 2697100f4cd..540f0d9e54d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2alpha1.json @@ -1893,5 +1893,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2beta1.json index ec3f1d1ed5c..6c9aa023163 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_footer.v42.v2beta1.json @@ -1939,5 +1939,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2alpha1.json index d2ec399b434..bccce10d162 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2alpha1.json @@ -2192,5 +2192,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2beta1.json index a2ea184c554..5e186ef1443 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_kitchen_sink.v42.v2beta1.json @@ -2227,5 +2227,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2alpha1.json index 2bbd6a111bc..4863b46eeb3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2alpha1.json @@ -178,5 +178,10 @@ "title": "Panel Tests - Table - Markdown", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2beta1.json index 4a1f3a61afd..1964dd78543 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_markdown.v42.v2beta1.json @@ -181,5 +181,10 @@ "title": "Panel Tests - Table - Markdown", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2alpha1.json index e637af09f52..cb0c2bbc16d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2alpha1.json @@ -3000,5 +3000,10 @@ "title": "Panel Tests - Table - Pagination", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2beta1.json index bc15692c4cb..d79b6c9e68b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_pagination.v42.v2beta1.json @@ -3018,5 +3018,10 @@ "title": "Panel Tests - Table - Pagination", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2alpha1.json index 78012512792..e5e260fd150 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2alpha1.json @@ -824,5 +824,10 @@ "title": "Panel Tests - Table - Sparklines", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2beta1.json index 352bab0c09b..ac15a298939 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_sparkline_cell.v42.v2beta1.json @@ -846,5 +846,10 @@ "title": "Panel Tests - Table - Sparklines", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2alpha1.json index 9d3a3f84f61..c706000d557 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2alpha1.json @@ -80,7 +80,85 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -142,7 +220,86 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "pageSize": 10, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -204,7 +361,99 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [ + { + "text": "Avg", + "value": "avg" + }, + { + "text": "Max", + "value": "max" + }, + { + "text": "Current", + "value": "current" + } + ], + "fontSize": "100%", + "pageSize": 10, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_aggregations" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -251,7 +500,65 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "row", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "/Color/", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -313,7 +620,92 @@ "kind": "table", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "pageSize": 20, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.5)", + "rgba(237, 129, 40, 0.5)", + "rgba(50, 172, 45, 0.5)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "link": true, + "linkTargetBlank": true, + "linkTooltip": "", + "linkUrl": "http://www.grafana.com", + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.5)", + "rgba(237, 129, 40, 0.5)", + "rgba(50, 172, 45, 0.5)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "link": true, + "linkUrl": "http://www.grafana.com", + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -426,5 +818,10 @@ "title": "Panel Tests - Table", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2beta1.json index 2b97a31452a..3ddb128c20e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests.v42.v2beta1.json @@ -87,7 +87,85 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -154,7 +232,86 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "pageSize": 10, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_rows" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -221,7 +378,99 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [ + { + "text": "Avg", + "value": "avg" + }, + { + "text": "Max", + "value": "max" + }, + { + "text": "Current", + "value": "current" + } + ], + "fontSize": "100%", + "pageSize": 10, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_aggregations" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -271,7 +520,65 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "row", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "mappingType": 1, + "pattern": "/Color/", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -338,7 +645,92 @@ "group": "table", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "pageSize": 20, + "scroll": true, + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "auto", + "colorMode": "cell", + "colors": [ + "rgba(245, 54, 54, 0.5)", + "rgba(237, 129, 40, 0.5)", + "rgba(50, 172, 45, 0.5)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "link": true, + "linkTargetBlank": true, + "linkTooltip": "", + "linkUrl": "http://www.grafana.com", + "mappingType": 1, + "pattern": "ColorCell", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "currencyUSD" + }, + { + "alias": "", + "align": "auto", + "colorMode": "value", + "colors": [ + "rgba(245, 54, 54, 0.5)", + "rgba(237, 129, 40, 0.5)", + "rgba(50, 172, 45, 0.5)" + ], + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "decimals": 2, + "link": true, + "linkUrl": "http://www.grafana.com", + "mappingType": 1, + "pattern": "ColorValue", + "thresholds": [ + "5", + "10" + ], + "type": "number", + "unit": "Bps" + }, + { + "alias": "", + "align": "auto", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "timeseries_to_columns" + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -451,5 +843,10 @@ "title": "Panel Tests - Table", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2alpha1.json index 25624e5c6d1..4e35b317cd9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2alpha1.json @@ -1252,5 +1252,10 @@ "title": "Panel Tests - React Table", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2beta1.json index b8d5f8acae3..8911415d0fc 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_tests_new.v42.v2beta1.json @@ -1280,5 +1280,10 @@ "title": "Panel Tests - React Table", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2alpha1.json index b8e6725ca5a..1b6348c35d5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2alpha1.json @@ -2507,5 +2507,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2beta1.json index 4a7ea3bcf33..a77140c5beb 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-table/v0alpha1.table_v12_2_migrations.v42.v2beta1.json @@ -2550,5 +2550,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2alpha1.json index e0299a0be0f..3ac4d6901f4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2alpha1.json @@ -431,5 +431,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2beta1.json index a93a6c13852..6e8243f3131 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-text/v0alpha1.text-options.v42.v2beta1.json @@ -450,5 +450,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2alpha1.json index 15877291ee7..cb30e79d196 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2alpha1.json @@ -356,5 +356,10 @@ "title": "Panel Tests - StateTimeline - multiple frames with endTime", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2beta1.json index 1d857be3ea5..34c3f244b54 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-endtime.v42.v2beta1.json @@ -365,5 +365,10 @@ "title": "Panel Tests - StateTimeline - multiple frames with endTime", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2alpha1.json index 7a2c436af82..13303a094ec 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2alpha1.json @@ -263,5 +263,10 @@ "title": "Panel Tests - StateTimeline - multiple frames with nulls", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2beta1.json index 4b14dcf2810..7d8376e9106 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-align-nulls-retain.v42.v2beta1.json @@ -267,5 +267,10 @@ "title": "Panel Tests - StateTimeline - multiple frames with nulls", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2alpha1.json index 522ec817718..82500d25a30 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2alpha1.json @@ -670,5 +670,10 @@ "title": "Timeline Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2beta1.json index 8e01aece508..89c7db392ea 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-demo.v42.v2beta1.json @@ -699,5 +699,10 @@ "title": "Timeline Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2alpha1.json index 7c8170cbcf8..9b4b2edfb80 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2alpha1.json @@ -548,5 +548,10 @@ "title": "Timeline Modes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2beta1.json index f5f4d53dba6..35d2643cc81 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-modes.v42.v2beta1.json @@ -566,5 +566,10 @@ "title": "Timeline Modes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2alpha1.json index ff492690353..8dff3c34ccf 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2alpha1.json @@ -1498,5 +1498,10 @@ "title": "StateTimeline - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2beta1.json index 6dcd28290db..3baa3d21130 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeline/v0alpha1.timeline-thresholds-mappings.v42.v2beta1.json @@ -1537,5 +1537,10 @@ "title": "StateTimeline - Thresholds \u0026 Mappings", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2alpha1.json index f18b9741878..6f3390c4d11 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2alpha1.json @@ -790,5 +790,10 @@ "title": "Panel Tests - TimeSeries - bars high density (stroke + fill)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2beta1.json index 797c81e39f0..00de0e2092b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-bars-high-density.v42.v2beta1.json @@ -805,5 +805,10 @@ "title": "Panel Tests - TimeSeries - bars high density (stroke + fill)", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2alpha1.json index d51c3443680..2d0e6b76950 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2alpha1.json @@ -1374,5 +1374,10 @@ "title": "Panel Tests - Graph NG - By value color schemes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2beta1.json index cc2f62859f9..a3f729f9c5f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-by-value-color-schemes.v42.v2beta1.json @@ -1403,5 +1403,10 @@ "title": "Panel Tests - Graph NG - By value color schemes", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2alpha1.json index 766832b0cb7..ac083165532 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2alpha1.json @@ -1067,5 +1067,10 @@ "title": "Panel Tests - Timeseries - Supported input formats", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2beta1.json index da1784c2b52..25ed3a1cf9b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-formats.v42.v2beta1.json @@ -1076,5 +1076,10 @@ "title": "Panel Tests - Timeseries - Supported input formats", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2alpha1.json index 7ad3c386000..5b43876c65f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2alpha1.json @@ -799,5 +799,10 @@ "title": "Panel Tests - Graph NG - Gradient Area Fills", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2beta1.json index 4def562428b..ca96f9d5720 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-gradient-area.v42.v2beta1.json @@ -813,5 +813,10 @@ "title": "Panel Tests - Graph NG - Gradient Area Fills", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2alpha1.json index 0f5a4c7473e..74cba148009 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2alpha1.json @@ -1215,5 +1215,10 @@ "title": "Panel Tests - GraphNG - Hue Gradients", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2beta1.json index e7e54fd938b..7e64bc79ef3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-hue-gradients.v42.v2beta1.json @@ -1235,5 +1235,10 @@ "title": "Panel Tests - GraphNG - Hue Gradients", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2alpha1.json index 9bf92a90234..718a96c265c 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2alpha1.json @@ -4362,5 +4362,10 @@ "title": "Panel Tests - Graph NG - Discrete panels", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2beta1.json index 3678e2c1bb8..187a377bdf1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-nulls.v42.v2beta1.json @@ -4462,5 +4462,10 @@ "title": "Panel Tests - Graph NG - Discrete panels", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2alpha1.json index 7bfea9b01ad..f1bff310950 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2alpha1.json @@ -660,5 +660,10 @@ "title": "Panel Tests - Timeseries - Out of range", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2beta1.json index b0ee8fe1273..e868bafcffd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-out-of-rage.v42.v2beta1.json @@ -676,5 +676,10 @@ "title": "Panel Tests - Timeseries - Out of range", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2alpha1.json index 19003b3c112..dbe2ae22ebd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2alpha1.json @@ -821,5 +821,10 @@ "title": "Panel Tests - shared tooltips cursor positioning", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2beta1.json index 17006d8b0ac..5763494659d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-shared-tooltip-cursor-position.v42.v2beta1.json @@ -839,5 +839,10 @@ "title": "Panel Tests - shared tooltips cursor positioning", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2alpha1.json index 91ebfa89a29..3c8700d1c0a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2alpha1.json @@ -2849,5 +2849,10 @@ "title": "Panel Tests - Graph NG - softMin/softMax", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2beta1.json index b616f35f02f..5cd6604807a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-soft-limits.v42.v2beta1.json @@ -2887,5 +2887,10 @@ "title": "Panel Tests - Graph NG - softMin/softMax", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2alpha1.json index d5de67f8b7e..59b356d1a36 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2alpha1.json @@ -1521,5 +1521,10 @@ "title": "Panel Tests - TimeSeries - stacking", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2beta1.json index b14bc2dfae4..07c5f127c32 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking.v42.v2beta1.json @@ -1566,5 +1566,10 @@ "title": "Panel Tests - TimeSeries - stacking", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2alpha1.json index c37056e01ec..4c92eef28c1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2alpha1.json @@ -4629,5 +4629,10 @@ "title": "TimeSeries \u0026 BarChart Stacking", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2beta1.json index 200a8362e4e..486f41cdce0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-stacking2.v42.v2beta1.json @@ -4818,5 +4818,10 @@ "title": "TimeSeries \u0026 BarChart Stacking", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2alpha1.json index 99bf0a4bba4..b15dedc73a8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2alpha1.json @@ -176,6 +176,88 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": false, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": false, + "line": true, + "op": "gt", + "value": 50, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -339,6 +421,88 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:109", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "lt", + "value": 20, + "yaxis": "left" + }, + { + "$$hashKey": "object:115", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "lt", + "value": 60, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -826,6 +990,88 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "gt", + "value": 50, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -876,6 +1122,88 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:109", + "colorMode": "critical", + "fill": true, + "line": false, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:115", + "colorMode": "warning", + "fill": true, + "line": false, + "op": "gt", + "value": 60, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -928,6 +1256,97 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 1, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "lt", + "value": 40, + "yaxis": "left" + }, + { + "$$hashKey": "object:40", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "lt", + "value": 20, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -980,6 +1399,92 @@ "spec": { "pluginVersion": "7.5.0-pre", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 1, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(50, 161, 230, 0.13)", + "line": true, + "lineColor": "#B877D9", + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(184, 119, 217, 0.23)", + "line": true, + "lineColor": "rgba(93, 196, 31, 0.6)", + "op": "lt", + "value": 40, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -1185,5 +1690,10 @@ "title": "Panel Tests - GraphNG Thresholds", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2beta1.json index d1f32f0900d..0e9b32d82cf 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-thresholds.v42.v2beta1.json @@ -182,6 +182,88 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": false, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": false, + "line": true, + "op": "gt", + "value": 50, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -349,6 +431,88 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:109", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "lt", + "value": 20, + "yaxis": "left" + }, + { + "$$hashKey": "object:115", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "lt", + "value": 60, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -846,6 +1010,88 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "gt", + "value": 50, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -898,6 +1144,88 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:109", + "colorMode": "critical", + "fill": true, + "line": false, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:115", + "colorMode": "warning", + "fill": true, + "line": false, + "op": "gt", + "value": 60, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -952,6 +1280,97 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 1, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "warning", + "fill": true, + "line": true, + "op": "lt", + "value": 40, + "yaxis": "left" + }, + { + "$$hashKey": "object:40", + "colorMode": "critical", + "fill": true, + "line": true, + "op": "lt", + "value": 20, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -1006,6 +1425,92 @@ "version": "7.5.0-pre", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 1, + "points": true, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [ + { + "$$hashKey": "object:14", + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(50, 161, 230, 0.13)", + "line": true, + "lineColor": "#B877D9", + "op": "gt", + "value": 80, + "yaxis": "left" + }, + { + "$$hashKey": "object:44", + "colorMode": "custom", + "fill": true, + "fillColor": "rgba(184, 119, 217, 0.23)", + "line": true, + "lineColor": "rgba(93, 196, 31, 0.6)", + "op": "lt", + "value": 40, + "yaxis": "left" + } + ], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:26", + "format": "short", + "logBase": 1, + "max": "100", + "min": "0", + "show": true + }, + { + "$$hashKey": "object:27", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "alertThreshold": true }, "fieldConfig": { @@ -1211,5 +1716,10 @@ "title": "Panel Tests - GraphNG Thresholds", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2alpha1.json index cf0c37a3a79..43271c576dd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2alpha1.json @@ -735,5 +735,10 @@ "title": "Panel Tests - GraphNG - Time Axis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2beta1.json index f106b3c8e1a..3674472eb53 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-time.v42.v2beta1.json @@ -749,5 +749,10 @@ "title": "Panel Tests - GraphNG - Time Axis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2alpha1.json index 4a6a5b03287..27afd1ec327 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2alpha1.json @@ -1095,5 +1095,10 @@ "title": "Zero Decimals Y Ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2beta1.json index 0d41fc01b8f..ef2241fb8f3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-y-ticks-zero-decimals.v42.v2beta1.json @@ -1121,5 +1121,10 @@ "title": "Zero Decimals Y Ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2alpha1.json index d23c438178c..40bf202a1ae 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2alpha1.json @@ -1722,5 +1722,10 @@ "title": "Panel Tests - Graph NG - Y axis ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2beta1.json index 923573205a8..6e3377b4cc4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries-yaxis-ticks.v42.v2beta1.json @@ -1765,5 +1765,10 @@ "title": "Panel Tests - Graph NG - Y axis ticks", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2alpha1.json index cb50db62a68..e50b453076a 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2alpha1.json @@ -4371,5 +4371,10 @@ "title": "Panel Tests - Graph NG", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2beta1.json index 249af246ac9..65105663c85 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-timeseries/v0alpha1.timeseries.v42.v2beta1.json @@ -4445,5 +4445,10 @@ "title": "Panel Tests - Graph NG", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2alpha1.json index dda9209aa94..1439756b694 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2alpha1.json @@ -270,5 +270,10 @@ "title": "Panel Tests - Trend", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2beta1.json index 11683b31b98..65de2a79cf4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-trend/v0alpha1.trend_example.v42.v2beta1.json @@ -274,5 +274,10 @@ "title": "Panel Tests - Trend", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2alpha1.json index 53122268d1d..76278b42b57 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2alpha1.json @@ -1785,5 +1785,10 @@ "title": "Panel Tests - XY Chart Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2beta1.json index a4c1b86c07e..70a7b3b7537 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-demo.v42.v2beta1.json @@ -1825,5 +1825,10 @@ "title": "Panel Tests - XY Chart Demo", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2alpha1.json index 33d0b2ee9b2..ccb0c353c72 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2alpha1.json @@ -2478,5 +2478,10 @@ "title": "Panel Tests - XY Chart migrations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2beta1.json index a43b5c5e1e9..add31528134 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-migrations.v42.v2beta1.json @@ -2515,5 +2515,10 @@ "title": "Panel Tests - XY Chart migrations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2alpha1.json index 7583af8160e..1d60f0ef9bf 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2alpha1.json @@ -885,5 +885,10 @@ "title": "XYChart tooltip color test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2beta1.json index e10e9fc65ff..5a46646474d 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-xychart/v0alpha1.xychart-tooltip-color-test.v42.v2beta1.json @@ -907,5 +907,10 @@ "title": "XYChart tooltip color test", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2alpha1.json index 38e58c03f3a..d203fb8e357 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2alpha1.json @@ -150,5 +150,10 @@ "title": "Mostly blank dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2beta1.json index 45c5b980f7f..8f1a85fee5f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.mostly-blank-dashboard.v42.v2beta1.json @@ -153,5 +153,10 @@ "title": "Mostly blank dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2alpha1.json index a8c0c9f5617..7e915f70e20 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2alpha1.json @@ -250,5 +250,10 @@ "title": "Panel Tests - Relative time zone support", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2beta1.json index e8b38167a2a..545a6a234b4 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2beta1.json @@ -257,5 +257,10 @@ "title": "Panel Tests - Relative time zone support", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2alpha1.json index a738ad9daba..addd25f950f 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2alpha1.json @@ -86,7 +86,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -132,7 +189,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -178,7 +292,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -224,7 +395,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -270,7 +498,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -316,7 +601,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -362,7 +704,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -408,7 +807,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -454,7 +910,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -500,7 +1013,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -546,7 +1116,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -592,7 +1219,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -638,7 +1322,64 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -851,5 +1592,10 @@ "title": "Panel tests - Slow Queries \u0026 Annotations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2beta1.json index 2d018bf0db4..427a41ec1d7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.slow_queries_and_annotations.v42.v2beta1.json @@ -93,7 +93,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -142,7 +199,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -191,7 +305,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -240,7 +411,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -289,7 +517,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -338,7 +623,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -387,7 +729,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -436,7 +835,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -485,7 +941,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -534,7 +1047,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -583,7 +1153,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -632,7 +1259,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -681,7 +1365,64 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -894,5 +1635,10 @@ "title": "Panel tests - Slow Queries \u0026 Annotations", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2alpha1.json index 027ae6f3352..5fd3f355cbb 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2alpha1.json @@ -3416,5 +3416,10 @@ "title": "A tall dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2beta1.json index a225f2e7d81..b0d10fd280b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.tall_dashboard.v42.v2beta1.json @@ -3517,5 +3517,10 @@ "title": "A tall dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2alpha1.json index 0d6468c31f1..f95a6880b61 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2alpha1.json @@ -108,6 +108,67 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -171,6 +232,73 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "C-series", + "steppedLine": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -217,6 +345,68 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -265,6 +455,68 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -326,6 +578,75 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "yaxis": 2 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "label": "Perecent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "label": "Pressure", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -404,6 +725,73 @@ "spec": { "pluginVersion": "", "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -532,5 +920,10 @@ "title": "Panel Tests - Time zone support", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2beta1.json index 348f2876085..46da655452b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.time_zone_support.v42.v2beta1.json @@ -119,6 +119,67 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "decimals": 3, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": true, + "show": true, + "total": true, + "values": true + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -187,6 +248,73 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 0, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "C-series", + "steppedLine": true + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -236,6 +364,68 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -287,6 +477,68 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -353,6 +605,75 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "connected", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "yaxis": 2 + } + ], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "percent", + "label": "Perecent", + "logBase": 1, + "show": true + }, + { + "format": "short", + "label": "Pressure", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -438,6 +759,73 @@ "version": "", "spec": { "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "editable": true, + "error": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 2, + "nullPointMode": "null", + "percentage": false, + "pointradius": 5, + "points": false, + "renderer": "flot", + "seriesOverrides": [ + { + "alias": "B-series", + "zindex": -3 + } + ], + "spaceLength": 10, + "stack": true, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "msResolution": false, + "shared": true, + "sort": 0, + "value_type": "cumulative" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, "dataLinks": [] }, "fieldConfig": { @@ -566,5 +954,10 @@ "title": "Panel Tests - Time zone support", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2alpha1.json index 8808e6d73dc..a0e87e7d5f2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2alpha1.json @@ -1014,5 +1014,10 @@ "title": "Transforms - Config from query", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2beta1.json index 69930ae2e77..8134c573a69 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.config-from-query.v42.v2beta1.json @@ -1040,5 +1040,10 @@ "title": "Transforms - Config from query", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2alpha1.json index 469fca5d2aa..a611e5b0db2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2alpha1.json @@ -418,5 +418,10 @@ "title": "Transforms - Test extractFields JSON", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2beta1.json index 396cbc7348b..e1229efccac 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.extract-json-paths.v42.v2beta1.json @@ -428,5 +428,10 @@ "title": "Transforms - Test extractFields JSON", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2alpha1.json index 9202330a572..056fdc62383 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2alpha1.json @@ -227,5 +227,10 @@ "title": "Transforms - Filters", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2beta1.json index c9d1b8f11c4..57c5559add1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.filter.v42.v2beta1.json @@ -233,5 +233,10 @@ "title": "Transforms - Filters", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2alpha1.json index 9797be322d6..cbd2e994f15 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2alpha1.json @@ -865,5 +865,10 @@ "title": "Transforms - Join by field", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2beta1.json index ab0fb924f23..8fc053627fd 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-field.v42.v2beta1.json @@ -884,5 +884,10 @@ "title": "Transforms - Join by field", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2alpha1.json index 99353757d46..a10f2f6ed00 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2alpha1.json @@ -510,5 +510,10 @@ "title": "Transforms - Join by labels", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2beta1.json index fdc1b53ff36..73b06c4be7e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.join-by-labels.v42.v2beta1.json @@ -526,5 +526,10 @@ "title": "Transforms - Join by labels", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2alpha1.json index 22f053d066c..cab0fbea1e7 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2alpha1.json @@ -1348,5 +1348,10 @@ "title": "Transforms - Regression analysis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2beta1.json index 0d00e3f1021..464769f0e9e 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.regression-analysis.v42.v2beta1.json @@ -1371,5 +1371,10 @@ "title": "Transforms - Regression analysis", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2alpha1.json index fdea0031183..08b35165f79 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2alpha1.json @@ -741,5 +741,10 @@ "title": "Transforms - Reuse dashboard queries", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2beta1.json index 79002c2d12c..d8db8e1ada9 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.reuse.v42.v2beta1.json @@ -756,5 +756,10 @@ "title": "Transforms - Reuse dashboard queries", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2alpha1.json index 4d47c35593c..f89d509cae8 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2alpha1.json @@ -963,5 +963,10 @@ "title": "Transforms - Rows to fields", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2beta1.json index ddeb72b78f0..234f5dcbd63 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/transforms/v0alpha1.rows-to-fields.v42.v2beta1.json @@ -983,5 +983,10 @@ "title": "Transforms - Rows to fields", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2alpha1.json index b9aea52ad62..315164a75a3 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2alpha1.json @@ -1578,5 +1578,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2beta1.json index 0bd3a37b2d8..94f898bfa16 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.all-panels.v42.v2beta1.json @@ -1624,5 +1624,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2alpha1.json index d50e38918d2..2a6500f86db 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2alpha1.json @@ -379,5 +379,10 @@ "title": "Grafana Dev Overview \u0026 Home", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2beta1.json index dc06779b135..0580a517cb2 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/v0alpha1.v1beta1.v1beta1.home.v42.v2beta1.json @@ -386,5 +386,10 @@ "title": "Grafana Dev Overview \u0026 Home", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v0alpha1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v0alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v0alpha1.json new file mode 100644 index 00000000000..d1253a0a81d --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v0alpha1.json @@ -0,0 +1,1310 @@ +{ + "kind": "Dashboard", + "apiVersion": "dashboard.grafana.app/v0alpha1", + "metadata": { + "name": "angular-migrations-test" + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "links": [ + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate graph panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate graph panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate table (old) panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate table (old) panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate piechart panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate piechart panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate worldmap panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate worldmap panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate stat panel (TRUE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate stat panel (FALSE)", + "tooltip": "", + "type": "link", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate (TRUE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Auto migrate (FALSE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=false" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Disable angular (TRUE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.disableAngular=true" + }, + { + "asDropdown": false, + "icon": "external link", + "includeVars": false, + "keepTime": false, + "tags": [], + "targetBlank": true, + "title": "Disable angular (FALSE)", + "tooltip": "", + "type": "link", + "url": "/d/cdd412c4/?__feature.disableAngular=false" + } + ], + "liveNow": false, + "panels": [ + { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 0 + }, + "hiddenSeries": false, + "id": 4, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 3 + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph", + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "type": "graph", + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 0 + }, + "id": 6, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Timeseries panel\n\nKnown issues:\n* hiding null/empty series\n* time regions", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 11 + }, + "hiddenSeries": false, + "id": 28, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "rawFrameContent": "[\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.260951647569786,\n 1.887442338051216,\n 2.1526144400893514,\n 1.7287721375237766,\n 1.7262902137793208\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod1\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 1.589539045095202,\n 1.5914283506847613,\n 1.8976990616650726,\n 1.758223085999124,\n 2.2294649594813816\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod2\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.0914263380328766,\n 1.8164545521094575,\n 1.621111084665713,\n 1.3902653996444705,\n 1.482803315949775\n ]\n ]\n }\n }\n]", + "refId": "A", + "scenarioId": "raw_frame" + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis series mode", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "barchart", + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 11 + }, + "id": 29, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar chart panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "default": false, + "type": "datasource", + "uid": "-- Dashboard --" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 22 + }, + "hiddenSeries": false, + "id": 32, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.3.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "datasource", + "uid": "-- Dashboard --" + }, + "panelId": 28, + "refId": "A" + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis series mode (with legend calcs)", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "bargauge", + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "aliasColors": {}, + "autoMigrateFrom": "graph", + "bars": true, + "dashLength": 10, + "dashes": false, + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + }, + "fill": 1, + "fillGradient": 0, + "gridPos": { + "h": 11, + "w": 16, + "x": 0, + "y": 22 + }, + "hiddenSeries": false, + "id": 30, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "options": { + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "percentage": false, + "pluginVersion": "11.0.0-pre", + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 3 + } + ], + "thresholds": [], + "timeRegions": [], + "title": "Flot graph - x axis histogram mode", + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "type": "histogram", + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 22 + }, + "id": 33, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar gauge panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.3.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 11, + "w": 8, + "x": 16, + "y": 22 + }, + "id": 31, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Histogram panel\n", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "table-old", + "columns": [], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fontSize": "100%", + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 33 + }, + "id": 2, + "options": { + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "showRowNums": false + }, + "pluginVersion": "9.5.0-pre", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk_table" + } + ], + "title": "Table (old)", + "transform": "table", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + } + ], + "type": "table" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 33 + }, + "id": 7, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Table (old) \u003e\u003e Table\n\nKnown issues:\n* wrapping text\n* style changes", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-singlestat-panel", + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 43 + }, + "id": 9, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "maxDataPoints": 100, + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "thresholds": "", + "title": "grafana-singlestat-panel", + "type": "stat", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "match": "null", + "result": { + "text": "N/A" + } + }, + "type": "special" + } + ], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green" + }, + { + "color": "red", + "value": 80 + } + ] + }, + "unit": "ms" + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 43 + }, + "id": 23, + "maxDataPoints": 100, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "horizontal", + "reduceOptions": { + "calcs": [ + "mean" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "textMode": "auto", + "wideLayout": true + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "singlestat (old, internal. Migrated if schema \u003c 28)", + "type": "stat" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 43 + }, + "id": 10, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Singlestat \u003e\u003e Stat\n\nKnown issues:\n* limited options", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-piechart-panel", + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 51 + }, + "id": 24, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "9.5.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "random_walk_table" + } + ], + "title": "grafana-piechart-panel", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + } + ], + "type": "piechart" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 51 + }, + "id": 25, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-piechart-panel \u003e\u003e piechart\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + }, + { + "autoMigrateFrom": "grafana-worldmap-panel", + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "datasource": { + "type": "grafana-testdata-datasource" + }, + "decimals": 0, + "esMetric": "Count", + "gridPos": { + "h": 10, + "w": 16, + "x": 0, + "y": 61 + }, + "hideEmpty": false, + "hideZero": false, + "id": 26, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "maxDataPoints": 1, + "mouseWheelZoom": false, + "options": { + "basemap": { + "name": "Basemap", + "type": "default" + }, + "controls": { + "mouseWheelZoom": false, + "showAttribution": true, + "showDebug": false, + "showMeasure": false, + "showScale": false, + "showZoom": true + }, + "layers": [ + { + "config": { + "showLegend": true, + "style": { + "color": { + "fixed": "dark-green" + }, + "opacity": 0.4, + "rotation": { + "fixed": 0, + "max": 360, + "min": -360, + "mode": "mod" + }, + "size": { + "fixed": 5, + "max": 30, + "min": 2 + }, + "symbol": { + "fixed": "img/icons/marker/circle.svg", + "mode": "fixed" + }, + "symbolAlign": { + "horizontal": "center", + "vertical": "center" + }, + "textConfig": { + "fontSize": 12, + "offsetX": 0, + "offsetY": 0, + "textAlign": "center", + "textBaseline": "middle" + } + } + }, + "location": { + "gazetteer": "public/gazetteer/countries.json", + "mode": "lookup" + }, + "name": "Layer 0", + "tooltip": true, + "type": "markers" + } + ], + "tooltip": { + "mode": "details" + }, + "view": { + "allLayers": true, + "id": "zero", + "lat": 0, + "lon": 0, + "zoom": 1 + } + }, + "pluginVersion": "10.4.0-pre", + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "targets": [ + { + "csvFileName": "flight_info_by_state.csv", + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A", + "scenarioId": "csv_file" + } + ], + "thresholds": "0,10", + "title": "grafana-worldmap-panel", + "transformations": [ + { + "id": "merge", + "options": { + "reducers": [] + } + }, + { + "id": "reduce", + "options": { + "reducers": [ + "sum" + ] + } + } + ], + "type": "geomap", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "gridPos": { + "h": 10, + "w": 8, + "x": 16, + "y": 61 + }, + "id": 27, + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-worldmap-panel \u003e\u003e geomap\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "pluginVersion": "11.0.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "refId": "A" + } + ], + "title": "Status + Notes", + "type": "text" + } + ], + "refresh": "", + "schemaVersion": 42, + "tags": [ + "gdev", + "migrations", + "angular" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "", + "title": "Devenv - Panel migrations", + "uid": "cdd412c4", + "weekStart": "" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2alpha1.json new file mode 100644 index 00000000000..d9e72ec700a --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2alpha1.json @@ -0,0 +1,1861 @@ +{ + "kind": "Dashboard", + "apiVersion": "dashboard.grafana.app/v2alpha1", + "metadata": { + "name": "angular-migrations-test" + }, + "spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "query": { + "kind": "grafana", + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true, + "legacyOptions": { + "type": "dashboard" + } + } + } + ], + "cursorSync": "Off", + "editable": true, + "elements": { + "panel-10": { + "kind": "Panel", + "spec": { + "id": 10, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Singlestat \u003e\u003e Stat\n\nKnown issues:\n* limited options", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "Table (old)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "scenarioId": "random_walk_table" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + } + ], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "table", + "spec": { + "pluginVersion": "9.5.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + }, + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "showRowNums": false + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-23": { + "kind": "Panel", + "spec": { + "id": 23, + "title": "singlestat (old, internal. Migrated if schema \u003c 28)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": { + "maxDataPoints": 100 + } + } + }, + "vizConfig": { + "kind": "stat", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "horizontal", + "reduceOptions": { + "calcs": [ + "mean" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "textMode": "auto", + "wideLayout": true + }, + "fieldConfig": { + "defaults": { + "unit": "ms", + "mappings": [ + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "N/A" + } + } + } + ], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": null, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + } + }, + "overrides": [] + } + } + } + } + }, + "panel-24": { + "kind": "Panel", + "spec": { + "id": 24, + "title": "grafana-piechart-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "scenarioId": "random_walk_table" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + } + ], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "piechart", + "spec": { + "pluginVersion": "9.5.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-piechart-panel", + "originalOptions": {} + }, + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-25": { + "kind": "Panel", + "spec": { + "id": 25, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-piechart-panel \u003e\u003e piechart\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-26": { + "kind": "Panel", + "spec": { + "id": 26, + "title": "grafana-worldmap-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "csvFileName": "flight_info_by_state.csv", + "scenarioId": "csv_file" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + }, + { + "kind": "reduce", + "spec": { + "id": "reduce", + "options": { + "reducers": [ + "sum" + ] + } + } + } + ], + "queryOptions": { + "maxDataPoints": 1 + } + } + }, + "vizConfig": { + "kind": "geomap", + "spec": { + "pluginVersion": "10.4.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-worldmap-panel", + "originalOptions": { + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 0, + "esMetric": "Count", + "hideEmpty": false, + "hideZero": false, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "mouseWheelZoom": false, + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "thresholds": "0,10", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + } + }, + "basemap": { + "name": "Basemap", + "type": "default" + }, + "controls": { + "mouseWheelZoom": false, + "showAttribution": true, + "showDebug": false, + "showMeasure": false, + "showScale": false, + "showZoom": true + }, + "layers": [ + { + "config": { + "showLegend": true, + "style": { + "color": { + "fixed": "dark-green" + }, + "opacity": 0.4, + "rotation": { + "fixed": 0, + "max": 360, + "min": -360, + "mode": "mod" + }, + "size": { + "fixed": 5, + "max": 30, + "min": 2 + }, + "symbol": { + "fixed": "img/icons/marker/circle.svg", + "mode": "fixed" + }, + "symbolAlign": { + "horizontal": "center", + "vertical": "center" + }, + "textConfig": { + "fontSize": 12, + "offsetX": 0, + "offsetY": 0, + "textAlign": "center", + "textBaseline": "middle" + } + } + }, + "location": { + "gazetteer": "public/gazetteer/countries.json", + "mode": "lookup" + }, + "name": "Layer 0", + "tooltip": true, + "type": "markers" + } + ], + "tooltip": { + "mode": "details" + }, + "view": { + "allLayers": true, + "id": "zero", + "lat": 0, + "lon": 0, + "zoom": 1 + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-27": { + "kind": "Panel", + "spec": { + "id": 27, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-worldmap-panel \u003e\u003e geomap\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-28": { + "kind": "Panel", + "spec": { + "id": 28, + "title": "Flot graph - x axis series mode", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "rawFrameContent": "[\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.260951647569786,\n 1.887442338051216,\n 2.1526144400893514,\n 1.7287721375237766,\n 1.7262902137793208\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod1\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 1.589539045095202,\n 1.5914283506847613,\n 1.8976990616650726,\n 1.758223085999124,\n 2.2294649594813816\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod2\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.0914263380328766,\n 1.8164545521094575,\n 1.621111084665713,\n 1.3902653996444705,\n 1.482803315949775\n ]\n ]\n }\n }\n]", + "scenarioId": "raw_frame" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "barchart", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-29": { + "kind": "Panel", + "spec": { + "id": 29, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar chart panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-30": { + "kind": "Panel", + "spec": { + "id": 30, + "title": "Flot graph - x axis histogram mode", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "scenarioId": "random_walk", + "seriesCount": 3 + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "histogram", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-31": { + "kind": "Panel", + "spec": { + "id": 31, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Histogram panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-32": { + "kind": "Panel", + "spec": { + "id": 32, + "title": "Flot graph - x axis series mode (with legend calcs)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "datasource", + "spec": { + "panelId": 28 + } + }, + "datasource": { + "type": "datasource", + "uid": "-- Dashboard --" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "bargauge", + "spec": { + "pluginVersion": "11.3.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-33": { + "kind": "Panel", + "spec": { + "id": 33, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.3.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar gauge panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "Flot graph", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": { + "scenarioId": "random_walk", + "seriesCount": 3 + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-6": { + "kind": "Panel", + "spec": { + "id": 6, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Timeseries panel\n\nKnown issues:\n* hiding null/empty series\n* time regions", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-7": { + "kind": "Panel", + "spec": { + "id": 7, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "text", + "spec": { + "pluginVersion": "11.0.0-pre", + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Table (old) \u003e\u003e Table\n\nKnown issues:\n* wrapping text\n* style changes", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-9": { + "kind": "Panel", + "spec": { + "id": 9, + "title": "grafana-singlestat-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": { + "maxDataPoints": 100 + } + } + }, + "vizConfig": { + "kind": "stat", + "spec": { + "pluginVersion": "", + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + } + }, + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 0, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-6" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 11, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-28" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 11, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-29" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 22, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-32" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 22, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-30" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 22, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-33" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 22, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-31" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 33, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 33, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-7" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-9" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 8, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-23" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-10" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 51, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-24" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 51, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-25" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 61, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-26" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 61, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-27" + } + } + } + ] + } + }, + "links": [ + { + "title": "Auto migrate graph panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate graph panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate table (old) panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate table (old) panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate piechart panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate piechart panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate worldmap panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate worldmap panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate stat panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate stat panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Disable angular (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.disableAngular=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Disable angular (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.disableAngular=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + } + ], + "liveNow": false, + "preload": false, + "tags": [ + "gdev", + "migrations", + "angular" + ], + "timeSettings": { + "timezone": "", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Devenv - Panel migrations", + "variables": [] + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2beta1.json new file mode 100644 index 00000000000..63447487dca --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.angular-migrations.v2beta1.json @@ -0,0 +1,1912 @@ +{ + "kind": "Dashboard", + "apiVersion": "dashboard.grafana.app/v2beta1", + "metadata": { + "name": "angular-migrations-test" + }, + "spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana", + "version": "v0", + "datasource": { + "name": "-- Grafana --" + }, + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true, + "legacyOptions": { + "type": "dashboard" + } + } + } + ], + "cursorSync": "Off", + "editable": true, + "elements": { + "panel-10": { + "kind": "Panel", + "spec": { + "id": 10, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Singlestat \u003e\u003e Stat\n\nKnown issues:\n* limited options", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "Table (old)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "scenarioId": "random_walk_table" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + } + ], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "table", + "version": "9.5.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "table-old", + "originalOptions": { + "columns": [], + "fontSize": "100%", + "showHeader": true, + "sort": { + "col": 0, + "desc": true + }, + "styles": [ + { + "alias": "Time", + "align": "auto", + "dateFormat": "YYYY-MM-DD HH:mm:ss", + "pattern": "Time", + "type": "date" + }, + { + "alias": "", + "align": "right", + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 2, + "pattern": "/.*/", + "thresholds": [], + "type": "number", + "unit": "short" + } + ], + "transform": "table" + } + }, + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true, + "showRowNums": false + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-23": { + "kind": "Panel", + "spec": { + "id": 23, + "title": "singlestat (old, internal. Migrated if schema \u003c 28)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": { + "maxDataPoints": 100 + } + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "stat", + "version": "11.0.0-pre", + "spec": { + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "horizontal", + "reduceOptions": { + "calcs": [ + "mean" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "textMode": "auto", + "wideLayout": true + }, + "fieldConfig": { + "defaults": { + "unit": "ms", + "mappings": [ + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "N/A" + } + } + } + ], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": null, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + } + }, + "overrides": [] + } + } + } + } + }, + "panel-24": { + "kind": "Panel", + "spec": { + "id": 24, + "title": "grafana-piechart-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "scenarioId": "random_walk_table" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + } + ], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "piechart", + "version": "9.5.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-piechart-panel", + "originalOptions": {} + }, + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "pieType": "pie", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "tooltip": { + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-25": { + "kind": "Panel", + "spec": { + "id": 25, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-piechart-panel \u003e\u003e piechart\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-26": { + "kind": "Panel", + "spec": { + "id": 26, + "title": "grafana-worldmap-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "csvFileName": "flight_info_by_state.csv", + "scenarioId": "csv_file" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [ + { + "kind": "merge", + "spec": { + "id": "merge", + "options": { + "reducers": [] + } + } + }, + { + "kind": "reduce", + "spec": { + "id": "reduce", + "options": { + "reducers": [ + "sum" + ] + } + } + } + ], + "queryOptions": { + "maxDataPoints": 1 + } + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "geomap", + "version": "10.4.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-worldmap-panel", + "originalOptions": { + "circleMaxSize": 30, + "circleMinSize": 2, + "colors": [ + "rgba(245, 54, 54, 0.9)", + "rgba(237, 129, 40, 0.89)", + "rgba(50, 172, 45, 0.97)" + ], + "decimals": 0, + "esMetric": "Count", + "hideEmpty": false, + "hideZero": false, + "initialZoom": 1, + "locationData": "countries", + "mapCenter": "(0°, 0°)", + "mapCenterLatitude": 0, + "mapCenterLongitude": 0, + "mouseWheelZoom": false, + "showLegend": true, + "stickyLabels": false, + "tableQueryOptions": { + "geohashField": "geohash", + "latitudeField": "latitude", + "longitudeField": "longitude", + "metricField": "metric", + "queryType": "geohash" + }, + "thresholds": "0,10", + "unitPlural": "", + "unitSingle": "", + "valueName": "total" + } + }, + "basemap": { + "name": "Basemap", + "type": "default" + }, + "controls": { + "mouseWheelZoom": false, + "showAttribution": true, + "showDebug": false, + "showMeasure": false, + "showScale": false, + "showZoom": true + }, + "layers": [ + { + "config": { + "showLegend": true, + "style": { + "color": { + "fixed": "dark-green" + }, + "opacity": 0.4, + "rotation": { + "fixed": 0, + "max": 360, + "min": -360, + "mode": "mod" + }, + "size": { + "fixed": 5, + "max": 30, + "min": 2 + }, + "symbol": { + "fixed": "img/icons/marker/circle.svg", + "mode": "fixed" + }, + "symbolAlign": { + "horizontal": "center", + "vertical": "center" + }, + "textConfig": { + "fontSize": 12, + "offsetX": 0, + "offsetY": 0, + "textAlign": "center", + "textBaseline": "middle" + } + } + }, + "location": { + "gazetteer": "public/gazetteer/countries.json", + "mode": "lookup" + }, + "name": "Layer 0", + "tooltip": true, + "type": "markers" + } + ], + "tooltip": { + "mode": "details" + }, + "view": { + "allLayers": true, + "id": "zero", + "lat": 0, + "lon": 0, + "zoom": 1 + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-27": { + "kind": "Panel", + "spec": { + "id": 27, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# grafana-worldmap-panel \u003e\u003e geomap\n\nKnown issues:\n* TBD", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-28": { + "kind": "Panel", + "spec": { + "id": 28, + "title": "Flot graph - x axis series mode", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "rawFrameContent": "[\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.260951647569786,\n 1.887442338051216,\n 2.1526144400893514,\n 1.7287721375237766,\n 1.7262902137793208\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod1\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 1.589539045095202,\n 1.5914283506847613,\n 1.8976990616650726,\n 1.758223085999124,\n 2.2294649594813816\n ]\n ]\n }\n },\n {\n \"schema\": {\n \"refId\": \"A\",\n \"meta\": {\n \"typeVersion\": [\n 0,\n 0\n ],\n \"custom\": {\n \"customStat\": 10\n }\n },\n \"fields\": [\n {\n \"name\": \"time\",\n \"type\": \"time\",\n \"typeInfo\": {\n \"frame\": \"time.Time\",\n \"nullable\": true\n },\n \"config\": {\n \"interval\": 3600000\n }\n },\n {\n \"name\": \"Value\",\n \"type\": \"number\",\n \"typeInfo\": {\n \"frame\": \"float64\",\n \"nullable\": true\n },\n \"labels\": {\n \"pod\": \"A-pod2\"\n },\n \"config\": {}\n }\n ]\n },\n \"data\": {\n \"values\": [\n [\n 1727107111901,\n 1727110711901,\n 1727114311901,\n 1727117911901,\n 1727121511901,\n 1727125111901\n ],\n [\n 1.907286825122581,\n 2.0914263380328766,\n 1.8164545521094575,\n 1.621111084665713,\n 1.3902653996444705,\n 1.482803315949775\n ]\n ]\n }\n }\n]", + "scenarioId": "raw_frame" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "barchart", + "version": "11.0.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-29": { + "kind": "Panel", + "spec": { + "id": 29, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar chart panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-30": { + "kind": "Panel", + "spec": { + "id": 30, + "title": "Flot graph - x axis histogram mode", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "scenarioId": "random_walk", + "seriesCount": 3 + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "histogram", + "version": "11.0.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": false, + "total": false, + "values": false + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "histogram", + "show": true, + "values": [] + }, + "yaxes": [ + { + "$$hashKey": "object:193", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:194", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-31": { + "kind": "Panel", + "spec": { + "id": 31, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Histogram panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-32": { + "kind": "Panel", + "spec": { + "id": 32, + "title": "Flot graph - x axis series mode (with legend calcs)", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "datasource", + "version": "v0", + "datasource": { + "name": "-- Dashboard --" + }, + "spec": { + "panelId": 28 + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "bargauge", + "version": "11.3.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": true, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "alignAsTable": true, + "avg": true, + "current": true, + "max": true, + "min": false, + "show": true, + "total": false, + "values": true + }, + "lines": false, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": false, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "series", + "show": true, + "values": [ + "total" + ] + }, + "yaxes": [ + { + "$$hashKey": "object:88", + "format": "short", + "logBase": 1, + "show": true + }, + { + "$$hashKey": "object:89", + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-33": { + "kind": "Panel", + "spec": { + "id": 33, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.3.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Bar gauge panel\n", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "Flot graph", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": { + "scenarioId": "random_walk", + "seriesCount": 3 + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "timeseries", + "version": "11.0.0-pre", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": { + "aliasColors": {}, + "bars": false, + "dashLength": 10, + "dashes": false, + "fill": 1, + "fillGradient": 0, + "hiddenSeries": false, + "legend": { + "avg": false, + "current": false, + "max": false, + "min": false, + "show": true, + "total": false, + "values": false + }, + "lines": true, + "linewidth": 1, + "nullPointMode": "null", + "percentage": false, + "pointradius": 2, + "points": false, + "renderer": "flot", + "seriesOverrides": [], + "spaceLength": 10, + "stack": false, + "steppedLine": false, + "thresholds": [], + "timeRegions": [], + "tooltip": { + "shared": true, + "sort": 0, + "value_type": "individual" + }, + "xaxis": { + "mode": "time", + "show": true, + "values": [] + }, + "yaxes": [ + { + "format": "short", + "logBase": 1, + "show": true + }, + { + "format": "short", + "logBase": 1, + "show": true + } + ], + "yaxis": { + "align": false + } + } + }, + "alertThreshold": true, + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + } + } + }, + "panel-6": { + "kind": "Panel", + "spec": { + "id": 6, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Graph panel \u003e\u003e Timeseries panel\n\nKnown issues:\n* hiding null/empty series\n* time regions", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-7": { + "kind": "Panel", + "spec": { + "id": 7, + "title": "Status + Notes", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "text", + "version": "11.0.0-pre", + "spec": { + "options": { + "code": { + "language": "plaintext", + "showLineNumbers": false, + "showMiniMap": false + }, + "content": "# Table (old) \u003e\u003e Table\n\nKnown issues:\n* wrapping text\n* style changes", + "mode": "markdown" + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + }, + "panel-9": { + "kind": "Panel", + "spec": { + "id": 9, + "title": "grafana-singlestat-panel", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana-testdata-datasource", + "version": "v0", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": { + "maxDataPoints": 100 + } + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "stat", + "version": "", + "spec": { + "options": { + "__angularMigration": { + "autoMigrateFrom": "grafana-singlestat-panel", + "originalOptions": { + "colorBackground": false, + "colorValue": true, + "colors": [ + "#299c46", + "rgba(237, 129, 40, 0.89)", + "#d44a3a" + ], + "format": "areaF2", + "gauge": { + "maxValue": 100, + "minValue": 0, + "show": false, + "thresholdLabels": false, + "thresholdMarkers": true + }, + "mappingType": 1, + "mappingTypes": [ + { + "name": "value to text", + "value": 1 + }, + { + "name": "range to text", + "value": 2 + } + ], + "nullPointMode": "connected", + "postfix": "b", + "postfixFontSize": "50%", + "prefix": "a", + "prefixFontSize": "50%", + "rangeMaps": [ + { + "from": "null", + "text": "N/A", + "to": "null" + } + ], + "sparkline": { + "fillColor": "rgba(31, 118, 189, 0.18)", + "full": false, + "lineColor": "rgb(31, 120, 193)", + "show": true + }, + "tableColumn": "", + "thresholds": "", + "valueFontSize": "80%", + "valueMaps": [ + { + "op": "=", + "text": "N/A", + "value": "null" + } + ], + "valueName": "avg" + } + } + }, + "fieldConfig": { + "defaults": {}, + "overrides": [] + } + } + } + } + } + }, + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 0, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-6" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 11, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-28" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 11, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-29" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 22, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-32" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 22, + "width": 16, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-30" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 22, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-33" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 22, + "width": 8, + "height": 11, + "element": { + "kind": "ElementReference", + "name": "panel-31" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 33, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 33, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-7" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-9" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 8, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-23" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 43, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-10" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 51, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-24" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 51, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-25" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 61, + "width": 16, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-26" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 16, + "y": 61, + "width": 8, + "height": 10, + "element": { + "kind": "ElementReference", + "name": "panel-27" + } + } + } + ] + } + }, + "links": [ + { + "title": "Auto migrate graph panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate graph panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateGraphPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate table (old) panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate table (old) panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateTablePanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate piechart panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate piechart panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigratePiechartPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate worldmap panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate worldmap panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateWorldmapPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate stat panel (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate stat panel (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": " /d/cdd412c4/?__feature.autoMigrateStatPanel=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Auto migrate (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.autoMigrateOldPanels=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Disable angular (TRUE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.disableAngular=true", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + }, + { + "title": "Disable angular (FALSE)", + "type": "link", + "icon": "external link", + "tooltip": "", + "url": "/d/cdd412c4/?__feature.disableAngular=false", + "tags": [], + "asDropdown": false, + "targetBlank": true, + "includeVars": false, + "keepTime": false + } + ], + "liveNow": false, + "preload": false, + "tags": [ + "gdev", + "migrations", + "angular" + ], + "timeSettings": { + "timezone": "", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Devenv - Panel migrations", + "variables": [] + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2alpha1.json index 387ba145494..5f94f0d555b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2alpha1.json @@ -335,5 +335,10 @@ "title": "Annotation Conversions Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2beta1.json index a4dde4d26ac..c728d8dd513 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.annotation-conversions.v2beta1.json @@ -346,5 +346,10 @@ "title": "Annotation Conversions Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2alpha1.json index 3e9132d9ea9..4de46378b53 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2alpha1.json @@ -200,5 +200,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2beta1.json index 951eeaac0f6..7576414d605 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.dashboard-properties.v2beta1.json @@ -205,5 +205,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2alpha1.json index a614f32dda6..a9b876424be 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2alpha1.json @@ -165,5 +165,10 @@ "title": "Library Panel Repeat Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2beta1.json index d06d12848e6..8b2eb35cef1 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.library-panel-repeat-options.v2beta1.json @@ -165,5 +165,10 @@ "title": "Library Panel Repeat Options Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2alpha1.json index 9e0d5378f9b..f1004780fb0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2alpha1.json @@ -181,7 +181,12 @@ "kind": "timeseries", "spec": { "pluginVersion": "", - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -501,5 +506,10 @@ "title": "Panel Conversions Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2beta1.json index 8eac23d96c0..84064324429 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-conversions.v2beta1.json @@ -186,7 +186,12 @@ "group": "timeseries", "version": "", "spec": { - "options": {}, + "options": { + "__angularMigration": { + "autoMigrateFrom": "graph", + "originalOptions": {} + } + }, "fieldConfig": { "defaults": {}, "overrides": [] @@ -510,5 +515,10 @@ "title": "Panel Conversions Test Dashboard", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2alpha1.json index 5a0a8e074e6..55b0af155ff 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2alpha1.json @@ -201,5 +201,10 @@ "title": "Panel ds inheritance ", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2beta1.json index 3a13853c08e..48ec1ca758b 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.panel-datasource-type-datasource.v2beta1.json @@ -204,5 +204,10 @@ "title": "Panel ds inheritance ", "variables": [] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v0alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v0alpha1.json new file mode 100644 index 00000000000..c824b19412d --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v0alpha1.json @@ -0,0 +1,580 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v0alpha1", + "metadata": { + "name": "value-mapping-test", + "namespace": "default", + "uid": "value-mapping-test", + "resourceVersion": "1765384157199094", + "generation": 2, + "creationTimestamp": "2025-11-19T20:09:28Z", + "labels": { + "grafana.app/deprecatedInternalID": "646372978987008" + } + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "type": "dashboard" + } + ] + }, + "description": "Test dashboard for all value mapping types and override matcher types", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "links": [], + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with ValueMap mapping type - maps specific text values to colors and display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "critical": { + "color": "red", + "index": 0, + "text": "Critical!" + }, + "ok": { + "color": "green", + "index": 2, + "text": "OK" + }, + "warning": { + "color": "orange", + "index": 1, + "text": "Warning" + } + }, + "type": "value" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 100 + }, + { + "id": "custom.align", + "value": "center" + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 0 + }, + "id": 1, + "targets": [ + { + "expr": "up", + "refId": "A" + } + ], + "title": "ValueMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with RangeMap mapping type - maps numerical ranges to colors and display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "from": 0, + "result": { + "color": "green", + "index": 0, + "text": "Low" + }, + "to": 50 + }, + "type": "range" + }, + { + "options": { + "from": 50, + "result": { + "color": "orange", + "index": 1, + "text": "Medium" + }, + "to": 80 + }, + "type": "range" + }, + { + "options": { + "from": 80, + "result": { + "color": "red", + "index": 2, + "text": "High" + }, + "to": 100 + }, + "type": "range" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byRegexp", + "options": "/^cpu_/" + }, + "properties": [ + { + "id": "unit", + "value": "percent" + }, + { + "id": "decimals", + "value": 2 + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 0 + }, + "id": 2, + "targets": [ + { + "expr": "cpu_usage_percent", + "refId": "A" + } + ], + "title": "RangeMap Example", + "type": "gauge" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with RegexMap mapping type - maps values matching regex patterns to colors", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "pattern": "/^error.*/", + "result": { + "color": "red", + "index": 0, + "text": "Error" + } + }, + "type": "regex" + }, + { + "options": { + "pattern": "/^warn.*/", + "result": { + "color": "orange", + "index": 1, + "text": "Warning" + } + }, + "type": "regex" + }, + { + "options": { + "pattern": "/^info.*/", + "result": { + "color": "blue", + "index": 2, + "text": "Info" + } + }, + "type": "regex" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byType", + "options": "string" + }, + "properties": [ + { + "id": "custom.cellOptions", + "value": { + "type": "color-text" + } + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 8 + }, + "id": 3, + "targets": [ + { + "expr": "log_level", + "refId": "A" + } + ], + "title": "RegexMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with SpecialValueMap mapping type - maps special values like null, NaN, true, false to display text", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "match": "null", + "result": { + "color": "gray", + "index": 0, + "text": "No Data" + } + }, + "type": "special" + }, + { + "options": { + "match": "nan", + "result": { + "color": "gray", + "index": 1, + "text": "Not a Number" + } + }, + "type": "special" + }, + { + "options": { + "match": "null+nan", + "result": { + "color": "gray", + "index": 2, + "text": "N/A" + } + }, + "type": "special" + }, + { + "options": { + "match": "true", + "result": { + "color": "green", + "index": 3, + "text": "Yes" + } + }, + "type": "special" + }, + { + "options": { + "match": "false", + "result": { + "color": "red", + "index": 4, + "text": "No" + } + }, + "type": "special" + }, + { + "options": { + "match": "empty", + "result": { + "color": "gray", + "index": 5, + "text": "Empty" + } + }, + "type": "special" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "A" + }, + "properties": [ + { + "id": "color", + "value": { + "fixedColor": "blue", + "mode": "fixed" + } + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 8 + }, + "id": 4, + "targets": [ + { + "expr": "some_metric", + "refId": "A" + } + ], + "title": "SpecialValueMap Example", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "description": "Panel with all mapping types combined - demonstrates mixing different mapping types and multiple override matchers", + "fieldConfig": { + "defaults": { + "mappings": [ + { + "options": { + "failure": { + "color": "red", + "index": 1, + "text": "Failure" + }, + "success": { + "color": "green", + "index": 0, + "text": "Success" + } + }, + "type": "value" + }, + { + "options": { + "from": 0, + "result": { + "color": "blue", + "index": 2, + "text": "In Range" + }, + "to": 100 + }, + "type": "range" + }, + { + "options": { + "pattern": "/^[A-Z]{3}-\\d+$/", + "result": { + "color": "purple", + "index": 3, + "text": "ID Format" + } + }, + "type": "regex" + }, + { + "options": { + "match": "null", + "result": { + "color": "gray", + "index": 4, + "text": "Missing" + } + }, + "type": "special" + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 120 + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + } + ] + }, + { + "matcher": { + "id": "byRegexp", + "options": "/^value_/" + }, + "properties": [ + { + "id": "unit", + "value": "short" + }, + { + "id": "min", + "value": 0 + }, + { + "id": "max", + "value": 100 + } + ] + }, + { + "matcher": { + "id": "byType", + "options": "number" + }, + "properties": [ + { + "id": "decimals", + "value": 2 + }, + { + "id": "thresholds", + "value": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "yellow", + "value": 50 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + ] + }, + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "displayName", + "value": "Secondary Query" + } + ] + }, + { + "matcher": { + "id": "byValue", + "options": { + "op": "gte", + "reducer": "allIsNull", + "value": 0 + } + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + }, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 16 + }, + "id": 5, + "targets": [ + { + "expr": "combined_metric", + "refId": "A" + }, + { + "expr": "secondary_metric", + "refId": "B" + } + ], + "title": "Combined Mappings and Overrides Example", + "type": "table" + } + ], + "schemaVersion": 42, + "tags": [ + "value-mapping", + "overrides", + "test" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": {}, + "timezone": "browser", + "title": "Value Mapping and Overrides Test", + "weekStart": "" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2alpha1.json new file mode 100644 index 00000000000..f4a950d53a6 --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2alpha1.json @@ -0,0 +1,783 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v2alpha1", + "metadata": { + "name": "value-mapping-test", + "namespace": "default", + "uid": "value-mapping-test", + "resourceVersion": "1765384157199094", + "generation": 2, + "creationTimestamp": "2025-11-19T20:09:28Z", + "labels": { + "grafana.app/deprecatedInternalID": "646372978987008" + } + }, + "spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "query": { + "kind": "grafana", + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true, + "legacyOptions": { + "type": "dashboard" + } + } + } + ], + "cursorSync": "Off", + "description": "Test dashboard for all value mapping types and override matcher types", + "editable": true, + "elements": { + "panel-1": { + "kind": "Panel", + "spec": { + "id": 1, + "title": "ValueMap Example", + "description": "Panel with ValueMap mapping type - maps specific text values to colors and display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "up" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "stat", + "spec": { + "pluginVersion": "", + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "value", + "options": { + "critical": { + "text": "Critical!", + "color": "red", + "index": 0 + }, + "ok": { + "text": "OK", + "color": "green", + "index": 2 + }, + "warning": { + "text": "Warning", + "color": "orange", + "index": 1 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 100 + }, + { + "id": "custom.align", + "value": "center" + } + ] + } + ] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "RangeMap Example", + "description": "Panel with RangeMap mapping type - maps numerical ranges to colors and display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "cpu_usage_percent" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "gauge", + "spec": { + "pluginVersion": "", + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "range", + "options": { + "from": 0, + "to": 50, + "result": { + "text": "Low", + "color": "green", + "index": 0 + } + } + }, + { + "type": "range", + "options": { + "from": 50, + "to": 80, + "result": { + "text": "Medium", + "color": "orange", + "index": 1 + } + } + }, + { + "type": "range", + "options": { + "from": 80, + "to": 100, + "result": { + "text": "High", + "color": "red", + "index": 2 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byRegexp", + "options": "/^cpu_/" + }, + "properties": [ + { + "id": "unit", + "value": "percent" + }, + { + "id": "decimals", + "value": 2 + } + ] + } + ] + } + } + } + } + }, + "panel-3": { + "kind": "Panel", + "spec": { + "id": 3, + "title": "RegexMap Example", + "description": "Panel with RegexMap mapping type - maps values matching regex patterns to colors", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "log_level" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "stat", + "spec": { + "pluginVersion": "", + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "regex", + "options": { + "pattern": "/^error.*/", + "result": { + "text": "Error", + "color": "red", + "index": 0 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^warn.*/", + "result": { + "text": "Warning", + "color": "orange", + "index": 1 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^info.*/", + "result": { + "text": "Info", + "color": "blue", + "index": 2 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byType", + "options": "string" + }, + "properties": [ + { + "id": "custom.cellOptions", + "value": { + "type": "color-text" + } + } + ] + } + ] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "SpecialValueMap Example", + "description": "Panel with SpecialValueMap mapping type - maps special values like null, NaN, true, false to display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "some_metric" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "stat", + "spec": { + "pluginVersion": "", + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "No Data", + "color": "gray", + "index": 0 + } + } + }, + { + "type": "special", + "options": { + "match": "nan", + "result": { + "text": "Not a Number", + "color": "gray", + "index": 1 + } + } + }, + { + "type": "special", + "options": { + "match": "null+nan", + "result": { + "text": "N/A", + "color": "gray", + "index": 2 + } + } + }, + { + "type": "special", + "options": { + "match": "true", + "result": { + "text": "Yes", + "color": "green", + "index": 3 + } + } + }, + { + "type": "special", + "options": { + "match": "false", + "result": { + "text": "No", + "color": "red", + "index": 4 + } + } + }, + { + "type": "special", + "options": { + "match": "empty", + "result": { + "text": "Empty", + "color": "gray", + "index": 5 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "A" + }, + "properties": [ + { + "id": "color", + "value": { + "fixedColor": "blue", + "mode": "fixed" + } + } + ] + } + ] + } + } + } + } + }, + "panel-5": { + "kind": "Panel", + "spec": { + "id": 5, + "title": "Combined Mappings and Overrides Example", + "description": "Panel with all mapping types combined - demonstrates mixing different mapping types and multiple override matchers", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "combined_metric" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "A", + "hidden": false + } + }, + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "prometheus", + "spec": { + "expr": "secondary_metric" + } + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus-uid" + }, + "refId": "B", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "table", + "spec": { + "pluginVersion": "", + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "value", + "options": { + "failure": { + "text": "Failure", + "color": "red", + "index": 1 + }, + "success": { + "text": "Success", + "color": "green", + "index": 0 + } + } + }, + { + "type": "range", + "options": { + "from": 0, + "to": 100, + "result": { + "text": "In Range", + "color": "blue", + "index": 2 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^[A-Z]{3}-\\d+$/", + "result": { + "text": "ID Format", + "color": "purple", + "index": 3 + } + } + }, + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "Missing", + "color": "gray", + "index": 4 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 120 + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + } + ] + }, + { + "matcher": { + "id": "byRegexp", + "options": "/^value_/" + }, + "properties": [ + { + "id": "unit", + "value": "short" + }, + { + "id": "min", + "value": 0 + }, + { + "id": "max", + "value": 100 + } + ] + }, + { + "matcher": { + "id": "byType", + "options": "number" + }, + "properties": [ + { + "id": "decimals", + "value": 2 + }, + { + "id": "thresholds", + "value": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "yellow", + "value": 50 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + ] + }, + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "displayName", + "value": "Secondary Query" + } + ] + }, + { + "matcher": { + "id": "byValue", + "options": { + "op": "gte", + "reducer": "allIsNull", + "value": 0 + } + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + } + } + } + } + } + }, + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-1" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 0, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-3" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 16, + "width": 24, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-5" + } + } + } + ] + } + }, + "links": [], + "liveNow": false, + "preload": false, + "tags": [ + "value-mapping", + "overrides", + "test" + ], + "timeSettings": { + "timezone": "browser", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Value Mapping and Overrides Test", + "variables": [] + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2beta1.json new file mode 100644 index 00000000000..ad492e24a6e --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.value-mapping-and-overrides.v2beta1.json @@ -0,0 +1,795 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v2beta1", + "metadata": { + "name": "value-mapping-test", + "namespace": "default", + "uid": "value-mapping-test", + "resourceVersion": "1765384157199094", + "generation": 2, + "creationTimestamp": "2025-11-19T20:09:28Z", + "labels": { + "grafana.app/deprecatedInternalID": "646372978987008" + } + }, + "spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "grafana", + "version": "v0", + "datasource": { + "name": "-- Grafana --" + }, + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true, + "legacyOptions": { + "type": "dashboard" + } + } + } + ], + "cursorSync": "Off", + "description": "Test dashboard for all value mapping types and override matcher types", + "editable": true, + "elements": { + "panel-1": { + "kind": "Panel", + "spec": { + "id": 1, + "title": "ValueMap Example", + "description": "Panel with ValueMap mapping type - maps specific text values to colors and display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "up" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "stat", + "version": "", + "spec": { + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "value", + "options": { + "critical": { + "text": "Critical!", + "color": "red", + "index": 0 + }, + "ok": { + "text": "OK", + "color": "green", + "index": 2 + }, + "warning": { + "text": "Warning", + "color": "orange", + "index": 1 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 100 + }, + { + "id": "custom.align", + "value": "center" + } + ] + } + ] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "RangeMap Example", + "description": "Panel with RangeMap mapping type - maps numerical ranges to colors and display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "cpu_usage_percent" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "gauge", + "version": "", + "spec": { + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "range", + "options": { + "from": 0, + "to": 50, + "result": { + "text": "Low", + "color": "green", + "index": 0 + } + } + }, + { + "type": "range", + "options": { + "from": 50, + "to": 80, + "result": { + "text": "Medium", + "color": "orange", + "index": 1 + } + } + }, + { + "type": "range", + "options": { + "from": 80, + "to": 100, + "result": { + "text": "High", + "color": "red", + "index": 2 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byRegexp", + "options": "/^cpu_/" + }, + "properties": [ + { + "id": "unit", + "value": "percent" + }, + { + "id": "decimals", + "value": 2 + } + ] + } + ] + } + } + } + } + }, + "panel-3": { + "kind": "Panel", + "spec": { + "id": 3, + "title": "RegexMap Example", + "description": "Panel with RegexMap mapping type - maps values matching regex patterns to colors", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "log_level" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "stat", + "version": "", + "spec": { + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "regex", + "options": { + "pattern": "/^error.*/", + "result": { + "text": "Error", + "color": "red", + "index": 0 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^warn.*/", + "result": { + "text": "Warning", + "color": "orange", + "index": 1 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^info.*/", + "result": { + "text": "Info", + "color": "blue", + "index": 2 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byType", + "options": "string" + }, + "properties": [ + { + "id": "custom.cellOptions", + "value": { + "type": "color-text" + } + } + ] + } + ] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "SpecialValueMap Example", + "description": "Panel with SpecialValueMap mapping type - maps special values like null, NaN, true, false to display text", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "some_metric" + } + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "stat", + "version": "", + "spec": { + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "No Data", + "color": "gray", + "index": 0 + } + } + }, + { + "type": "special", + "options": { + "match": "nan", + "result": { + "text": "Not a Number", + "color": "gray", + "index": 1 + } + } + }, + { + "type": "special", + "options": { + "match": "null+nan", + "result": { + "text": "N/A", + "color": "gray", + "index": 2 + } + } + }, + { + "type": "special", + "options": { + "match": "true", + "result": { + "text": "Yes", + "color": "green", + "index": 3 + } + } + }, + { + "type": "special", + "options": { + "match": "false", + "result": { + "text": "No", + "color": "red", + "index": 4 + } + } + }, + { + "type": "special", + "options": { + "match": "empty", + "result": { + "text": "Empty", + "color": "gray", + "index": 5 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byFrameRefID", + "options": "A" + }, + "properties": [ + { + "id": "color", + "value": { + "fixedColor": "blue", + "mode": "fixed" + } + } + ] + } + ] + } + } + } + } + }, + "panel-5": { + "kind": "Panel", + "spec": { + "id": 5, + "title": "Combined Mappings and Overrides Example", + "description": "Panel with all mapping types combined - demonstrates mixing different mapping types and multiple override matchers", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "combined_metric" + } + }, + "refId": "A", + "hidden": false + } + }, + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "DataQuery", + "group": "prometheus", + "version": "v0", + "datasource": { + "name": "prometheus-uid" + }, + "spec": { + "expr": "secondary_metric" + } + }, + "refId": "B", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "VizConfig", + "group": "table", + "version": "", + "spec": { + "options": {}, + "fieldConfig": { + "defaults": { + "mappings": [ + { + "type": "value", + "options": { + "failure": { + "text": "Failure", + "color": "red", + "index": 1 + }, + "success": { + "text": "Success", + "color": "green", + "index": 0 + } + } + }, + { + "type": "range", + "options": { + "from": 0, + "to": 100, + "result": { + "text": "In Range", + "color": "blue", + "index": 2 + } + } + }, + { + "type": "regex", + "options": { + "pattern": "/^[A-Z]{3}-\\d+$/", + "result": { + "text": "ID Format", + "color": "purple", + "index": 3 + } + } + }, + { + "type": "special", + "options": { + "match": "null", + "result": { + "text": "Missing", + "color": "gray", + "index": 4 + } + } + } + ] + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "status" + }, + "properties": [ + { + "id": "custom.width", + "value": 120 + }, + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + } + ] + }, + { + "matcher": { + "id": "byRegexp", + "options": "/^value_/" + }, + "properties": [ + { + "id": "unit", + "value": "short" + }, + { + "id": "min", + "value": 0 + }, + { + "id": "max", + "value": 100 + } + ] + }, + { + "matcher": { + "id": "byType", + "options": "number" + }, + "properties": [ + { + "id": "decimals", + "value": 2 + }, + { + "id": "thresholds", + "value": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "yellow", + "value": 50 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + ] + }, + { + "matcher": { + "id": "byFrameRefID", + "options": "B" + }, + "properties": [ + { + "id": "displayName", + "value": "Secondary Query" + } + ] + }, + { + "matcher": { + "id": "byValue", + "options": { + "op": "gte", + "reducer": "allIsNull", + "value": 0 + } + }, + "properties": [ + { + "id": "custom.hidden", + "value": true + } + ] + } + ] + } + } + } + } + } + }, + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-1" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 0, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-3" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 16, + "width": 24, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-5" + } + } + } + ] + } + }, + "links": [], + "liveNow": false, + "preload": false, + "tags": [ + "value-mapping", + "overrides", + "test" + ], + "timeSettings": { + "timezone": "browser", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Value Mapping and Overrides Test", + "variables": [] + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2alpha1.json index c51582691b9..040513a3ce5 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2alpha1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2alpha1.json @@ -414,5 +414,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2beta1.json index 441258438a9..cf3ff5443c0 100644 --- a/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2beta1.json +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v1beta1.variable-conversions.v2beta1.json @@ -417,5 +417,10 @@ } ] }, - "status": {} + "status": { + "conversion": { + "failed": false, + "storedVersion": "v1beta1" + } + } } \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v0alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v0alpha1.json new file mode 100644 index 00000000000..0357c22536a --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v0alpha1.json @@ -0,0 +1,511 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v0alpha1", + "metadata": { + "name": "adt885j", + "namespace": "default", + "uid": "yTWet6JgBjlRIWnqRE9ZOmUycfT0tEkr2mljaln1GWIX", + "resourceVersion": "2", + "generation": 2, + "creationTimestamp": "2025-12-16T10:44:31Z", + "labels": { + "grafana.app/deprecatedInternalID": "2409" + }, + "annotations": { + "grafana.app/createdBy": "user:u000000001", + "grafana.app/updatedBy": "user:u000000001", + "grafana.app/updatedTimestamp": "2025-12-16T10:51:14Z" + } + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "type": "dashboard" + } + ] + }, + "description": "", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "liveNow": false, + "panels": [ + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "id": -1, + "panels": [], + "title": "Tab1", + "type": "row" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 7, + "x": 0, + "y": 1 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource", + "uid": "PD8C576611E62080A" + }, + "refId": "A" + } + ], + "title": "Panel1", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 7, + "y": 1 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel2", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 9, + "x": 15, + "y": 1 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel3", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel4", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "id": 5, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel5", + "type": "timeseries" + } + ], + "preload": false, + "refresh": "", + "schemaVersion": 42, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": { + "refresh_intervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ] + }, + "timezone": "browser", + "title": "Dashboard with tabs" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v2beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v1beta1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v1beta1.json new file mode 100644 index 00000000000..7a9ea77ba65 --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v1beta1.json @@ -0,0 +1,511 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v1beta1", + "metadata": { + "name": "adt885j", + "namespace": "default", + "uid": "yTWet6JgBjlRIWnqRE9ZOmUycfT0tEkr2mljaln1GWIX", + "resourceVersion": "2", + "generation": 2, + "creationTimestamp": "2025-12-16T10:44:31Z", + "labels": { + "grafana.app/deprecatedInternalID": "2409" + }, + "annotations": { + "grafana.app/createdBy": "user:u000000001", + "grafana.app/updatedBy": "user:u000000001", + "grafana.app/updatedTimestamp": "2025-12-16T10:51:14Z" + } + }, + "spec": { + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "type": "dashboard" + } + ] + }, + "description": "", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "liveNow": false, + "panels": [ + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "id": -1, + "panels": [], + "title": "Tab1", + "type": "row" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 7, + "x": 0, + "y": 1 + }, + "id": 1, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "datasource": { + "type": "grafana-testdata-datasource", + "uid": "PD8C576611E62080A" + }, + "refId": "A" + } + ], + "title": "Panel1", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 7, + "y": 1 + }, + "id": 2, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel2", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 9, + "x": 15, + "y": 1 + }, + "id": 3, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel3", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 9 + }, + "id": 4, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel4", + "type": "timeseries" + }, + { + "fieldConfig": { + "defaults": { + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + } + }, + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 9 + }, + "id": 5, + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "pluginVersion": "12.4.0-pre", + "targets": [ + { + "refId": "A" + } + ], + "title": "Panel5", + "type": "timeseries" + } + ], + "preload": false, + "refresh": "", + "schemaVersion": 42, + "time": { + "from": "now-6h", + "to": "now" + }, + "timepicker": { + "refresh_intervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ] + }, + "timezone": "browser", + "title": "Dashboard with tabs" + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v2beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v2alpha1.json b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v2alpha1.json new file mode 100644 index 00000000000..b7739508c2d --- /dev/null +++ b/apps/dashboard/pkg/migration/conversion/testdata/output/v2beta1.tab-with-multiple-panels.v2alpha1.json @@ -0,0 +1,683 @@ +{ + "kind": "DashboardWithAccessInfo", + "apiVersion": "dashboard.grafana.app/v2alpha1", + "metadata": { + "name": "adt885j", + "namespace": "default", + "uid": "yTWet6JgBjlRIWnqRE9ZOmUycfT0tEkr2mljaln1GWIX", + "resourceVersion": "2", + "generation": 2, + "creationTimestamp": "2025-12-16T10:44:31Z", + "labels": { + "grafana.app/deprecatedInternalID": "2409" + }, + "annotations": { + "grafana.app/createdBy": "user:u000000001", + "grafana.app/updatedBy": "user:u000000001", + "grafana.app/updatedTimestamp": "2025-12-16T10:51:14Z" + } + }, + "spec": { + "annotations": [ + { + "kind": "AnnotationQuery", + "spec": { + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "query": { + "kind": "grafana", + "spec": {} + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations \u0026 Alerts", + "builtIn": true + } + } + ], + "cursorSync": "Off", + "description": "", + "editable": true, + "elements": { + "panel-1": { + "kind": "Panel", + "spec": { + "id": 1, + "title": "Panel1", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "grafana-testdata-datasource", + "spec": {} + }, + "datasource": { + "type": "grafana-testdata-datasource", + "uid": "PD8C576611E62080A" + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "12.4.0-pre", + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-2": { + "kind": "Panel", + "spec": { + "id": 2, + "title": "Panel2", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "12.4.0-pre", + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-3": { + "kind": "Panel", + "spec": { + "id": 3, + "title": "Panel3", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "12.4.0-pre", + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-4": { + "kind": "Panel", + "spec": { + "id": 4, + "title": "Panel4", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "12.4.0-pre", + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + }, + "panel-5": { + "kind": "Panel", + "spec": { + "id": 5, + "title": "Panel5", + "description": "", + "links": [], + "data": { + "kind": "QueryGroup", + "spec": { + "queries": [ + { + "kind": "PanelQuery", + "spec": { + "query": { + "kind": "", + "spec": {} + }, + "refId": "A", + "hidden": false + } + } + ], + "transformations": [], + "queryOptions": {} + } + }, + "vizConfig": { + "kind": "timeseries", + "spec": { + "pluginVersion": "12.4.0-pre", + "options": { + "legend": { + "calcs": [], + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "hideZeros": false, + "mode": "single", + "sort": "none" + } + }, + "fieldConfig": { + "defaults": { + "thresholds": { + "mode": "absolute", + "steps": [ + { + "value": 0, + "color": "green" + }, + { + "value": 80, + "color": "red" + } + ] + }, + "color": { + "mode": "palette-classic" + }, + "custom": { + "axisBorderShow": false, + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "", + "axisPlacement": "auto", + "barAlignment": 0, + "barWidthFactor": 0.6, + "drawStyle": "line", + "fillOpacity": 0, + "gradientMode": "none", + "hideFrom": { + "legend": false, + "tooltip": false, + "viz": false + }, + "insertNulls": false, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { + "type": "linear" + }, + "showPoints": "auto", + "showValues": false, + "spanNulls": false, + "stacking": { + "group": "A", + "mode": "none" + }, + "thresholdsStyle": { + "mode": "off" + } + } + }, + "overrides": [] + } + } + } + } + } + }, + "layout": { + "kind": "TabsLayout", + "spec": { + "tabs": [ + { + "kind": "TabsLayoutTab", + "spec": { + "title": "Tab1", + "layout": { + "kind": "GridLayout", + "spec": { + "items": [ + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 0, + "width": 7, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-1" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 7, + "y": 0, + "width": 8, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-2" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 15, + "y": 0, + "width": 9, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-3" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 0, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-4" + } + } + }, + { + "kind": "GridLayoutItem", + "spec": { + "x": 12, + "y": 8, + "width": 12, + "height": 8, + "element": { + "kind": "ElementReference", + "name": "panel-5" + } + } + } + ] + } + } + } + } + ] + } + }, + "links": [], + "liveNow": false, + "preload": false, + "tags": [], + "timeSettings": { + "timezone": "browser", + "from": "now-6h", + "to": "now", + "autoRefresh": "", + "autoRefreshIntervals": [ + "5s", + "10s", + "30s", + "1m", + "5m", + "15m", + "30m", + "1h", + "2h", + "1d" + ], + "hideTimepicker": false, + "fiscalYearStartMonth": 0 + }, + "title": "Dashboard with tabs", + "variables": [] + }, + "status": { + "conversion": { + "failed": false, + "storedVersion": "v2beta1" + } + } +} \ No newline at end of file diff --git a/apps/dashboard/pkg/migration/conversion/v0.go b/apps/dashboard/pkg/migration/conversion/v0.go index 826293d9564..513f6975516 100644 --- a/apps/dashboard/pkg/migration/conversion/v0.go +++ b/apps/dashboard/pkg/migration/conversion/v0.go @@ -13,6 +13,9 @@ import ( func Convert_V0_to_V1beta1(in *dashv0.Dashboard, out *dashv1.Dashboard, scope conversion.Scope) error { if err := ConvertDashboard_V0_to_V1beta1(in, out, scope); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv1.APIVERSION + out.Kind = in.Kind out.Status = dashv1.DashboardStatus{ Conversion: &dashv1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -22,12 +25,24 @@ func Convert_V0_to_V1beta1(in *dashv0.Dashboard, out *dashv1.Dashboard, scope co } return err } + + // Set successful conversion status + out.Status = dashv1.DashboardStatus{ + Conversion: &dashv1.DashboardConversionStatus{ + StoredVersion: ptr.To(dashv0.VERSION), + Failed: false, + }, + } + return nil } func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, scope conversion.Scope, dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) error { v1beta1 := &dashv1.Dashboard{} if err := ConvertDashboard_V0_to_V1beta1(in, v1beta1, scope); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2alpha1.APIVERSION + out.Kind = in.Kind out.Status = dashv2alpha1.DashboardStatus{ Conversion: &dashv2alpha1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -35,7 +50,6 @@ func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, s Error: ptr.To(err.Error()), }, } - // Don't return error - just set status (matches test expectations) // Ensure layout is set even on error to prevent JSON marshaling issues if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { out.Spec.Layout = dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ @@ -45,10 +59,13 @@ func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, s }, } } - return nil + return err } if err := ConvertDashboard_V1beta1_to_V2alpha1(v1beta1, out, scope, dsIndexProvider, leIndexProvider); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2alpha1.APIVERSION + out.Kind = in.Kind out.Status = dashv2alpha1.DashboardStatus{ Conversion: &dashv2alpha1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -56,7 +73,6 @@ func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, s Error: ptr.To(err.Error()), }, } - // Don't return error - just set status (matches test expectations) // Ensure layout is set even on error to prevent JSON marshaling issues if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { out.Spec.Layout = dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ @@ -66,7 +82,15 @@ func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, s }, } } - return nil + return err + } + + // Set successful conversion status + out.Status = dashv2alpha1.DashboardStatus{ + Conversion: &dashv2alpha1.DashboardConversionStatus{ + StoredVersion: ptr.To(dashv0.VERSION), + Failed: false, + }, } return nil @@ -75,6 +99,9 @@ func Convert_V0_to_V2alpha1(in *dashv0.Dashboard, out *dashv2alpha1.Dashboard, s func Convert_V0_to_V2beta1(in *dashv0.Dashboard, out *dashv2beta1.Dashboard, scope conversion.Scope, dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) error { v1beta1 := &dashv1.Dashboard{} if err := ConvertDashboard_V0_to_V1beta1(in, v1beta1, scope); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2beta1.APIVERSION + out.Kind = in.Kind out.Status = dashv2beta1.DashboardStatus{ Conversion: &dashv2beta1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -82,11 +109,23 @@ func Convert_V0_to_V2beta1(in *dashv0.Dashboard, out *dashv2beta1.Dashboard, sco Error: ptr.To(err.Error()), }, } + // Ensure layout is set even on error to prevent JSON marshaling issues + if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { + out.Spec.Layout = dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + } + } return err } v2alpha1 := &dashv2alpha1.Dashboard{} if err := ConvertDashboard_V1beta1_to_V2alpha1(v1beta1, v2alpha1, scope, dsIndexProvider, leIndexProvider); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2beta1.APIVERSION + out.Kind = in.Kind out.Status = dashv2beta1.DashboardStatus{ Conversion: &dashv2beta1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -94,10 +133,22 @@ func Convert_V0_to_V2beta1(in *dashv0.Dashboard, out *dashv2beta1.Dashboard, sco Error: ptr.To(err.Error()), }, } + // Ensure layout is set even on error to prevent JSON marshaling issues + if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { + out.Spec.Layout = dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + } + } return err } if err := ConvertDashboard_V2alpha1_to_V2beta1(v2alpha1, out, scope); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2beta1.APIVERSION + out.Kind = in.Kind out.Status = dashv2beta1.DashboardStatus{ Conversion: &dashv2beta1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv0.VERSION), @@ -105,8 +156,25 @@ func Convert_V0_to_V2beta1(in *dashv0.Dashboard, out *dashv2beta1.Dashboard, sco Error: ptr.To(err.Error()), }, } + // Ensure layout is set even on error to prevent JSON marshaling issues + if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { + out.Spec.Layout = dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + } + } return err } + // Set successful conversion status + out.Status = dashv2beta1.DashboardStatus{ + Conversion: &dashv2beta1.DashboardConversionStatus{ + StoredVersion: ptr.To(dashv0.VERSION), + Failed: false, + }, + } + return nil } diff --git a/apps/dashboard/pkg/migration/conversion/v0_test.go b/apps/dashboard/pkg/migration/conversion/v0_test.go index ca2210f01e8..3620ea4d099 100644 --- a/apps/dashboard/pkg/migration/conversion/v0_test.go +++ b/apps/dashboard/pkg/migration/conversion/v0_test.go @@ -20,7 +20,7 @@ func TestV0ConversionErrorHandling(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) tests := []struct { name string @@ -54,7 +54,7 @@ func TestV0ConversionErrorHandling(t *testing.T) { }, }, { - name: "Convert_V0_to_V2alpha1 sets status on first step migration failure", + name: "Convert_V0_to_V2alpha1 returns error and sets status on first step migration failure", source: &dashv0.Dashboard{ ObjectMeta: metav1.ObjectMeta{ Namespace: "org-1", @@ -67,7 +67,7 @@ func TestV0ConversionErrorHandling(t *testing.T) { }, }, target: &dashv2alpha1.Dashboard{}, - expectError: false, // Convert_V0_to_V2alpha1 doesn't return error, just sets status + expectError: true, // Convert_V0_to_V2alpha1 now returns error for proper metrics/logging expectStatusSet: true, checkStatus: func(t *testing.T, target interface{}) { out := target.(*dashv2alpha1.Dashboard) @@ -132,7 +132,7 @@ func TestV0ConversionErrorPropagation(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("ConvertDashboard_V0_to_V1beta1 returns error on migration failure", func(t *testing.T) { source := &dashv0.Dashboard{ @@ -206,7 +206,7 @@ func TestV0ConversionSuccessPaths(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("Convert_V0_to_V1beta1 success path returns nil", func(t *testing.T) { source := &dashv0.Dashboard{ @@ -275,9 +275,9 @@ func TestV0ConversionSecondStepErrors(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) - t.Run("Convert_V0_to_V2alpha1 sets status on first step error", func(t *testing.T) { + t.Run("Convert_V0_to_V2alpha1 returns error and sets status on first step error", func(t *testing.T) { // Create a dashboard that will fail v0->v1beta1 conversion // Use schemaVersion 0 which will cause migration to fail source := &dashv0.Dashboard{ @@ -295,16 +295,16 @@ func TestV0ConversionSecondStepErrors(t *testing.T) { err := Convert_V0_to_V2alpha1(source, target, nil, dsProvider, leProvider) - // Convert_V0_to_V2alpha1 doesn't return error, just sets status - require.NoError(t, err, "Convert_V0_to_V2alpha1 doesn't return error") - // Status should be set when first step fails + // Convert_V0_to_V2alpha1 returns error for proper metrics/logging + require.Error(t, err, "Convert_V0_to_V2alpha1 should return error") + // Status should also be set when first step fails require.NotNil(t, target.Status.Conversion, "Status should be set on first step error") require.True(t, target.Status.Conversion.Failed, "Failed should be true") require.NotNil(t, target.Status.Conversion.Error, "Error should be set") require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) }) - t.Run("Convert_V0_to_V2alpha1 sets status on second step error", func(t *testing.T) { + t.Run("Convert_V0_to_V2alpha1 returns error and sets status on second step error", func(t *testing.T) { // Create a dashboard that will pass v0->v1beta1 but fail v1beta1->v2alpha1 // We need to create invalid JSON structure that will cause JSON marshaling to fail // or create a dashboard with invalid structure that causes transformation to fail @@ -329,16 +329,13 @@ func TestV0ConversionSecondStepErrors(t *testing.T) { err := Convert_V0_to_V2alpha1(source, target, nil, dsProvider, leProvider) - // Convert_V0_to_V2alpha1 doesn't return error, just sets status - require.NoError(t, err, "Convert_V0_to_V2alpha1 doesn't return error") - // If second step fails, status should be set - // Note: The error might occur in first step if JSON marshal fails early, - // but we're testing that the error handling path exists - if target.Status.Conversion != nil && target.Status.Conversion.Failed { - require.True(t, target.Status.Conversion.Failed) - require.NotNil(t, target.Status.Conversion.Error) - require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) - } + // Convert_V0_to_V2alpha1 returns error for proper metrics/logging + require.Error(t, err, "Convert_V0_to_V2alpha1 should return error") + // Status should also be set + require.NotNil(t, target.Status.Conversion, "Status should be set on error") + require.True(t, target.Status.Conversion.Failed, "Failed should be true") + require.NotNil(t, target.Status.Conversion.Error, "Error should be set") + require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) }) t.Run("Convert_V0_to_V2beta1 returns error on second step failure", func(t *testing.T) { @@ -394,3 +391,177 @@ func TestV0ConversionSecondStepErrors(t *testing.T) { } }) } + +// TestV0ConversionConsistency_ErrorsMustBeReturned ensures v0 conversion functions +// return errors instead of swallowing them. This prevents metrics and logs from being silently dropped. +func TestV0ConversionConsistency_ErrorsMustBeReturned(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Create a v0 dashboard that will fail conversion (invalid schema version) + invalidV0 := &dashv0.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 0, // Invalid schema version causes migration to fail + }, + }, + } + + t.Run("Convert_V0_to_V1beta1 must return error on failure", func(t *testing.T) { + target := &dashv1.Dashboard{} + err := Convert_V0_to_V1beta1(invalidV0, target, nil) + require.Error(t, err, "Convert_V0_to_V1beta1 must return error, not swallow it") + require.True(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be true") + }) + + t.Run("Convert_V0_to_V2alpha1 must return error on failure", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + err := Convert_V0_to_V2alpha1(invalidV0, target, nil, dsProvider, leProvider) + require.Error(t, err, "Convert_V0_to_V2alpha1 must return error, not swallow it") + require.True(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be true") + }) + + t.Run("Convert_V0_to_V2beta1 must return error on failure", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + err := Convert_V0_to_V2beta1(invalidV0, target, nil, dsProvider, leProvider) + require.Error(t, err, "Convert_V0_to_V2beta1 must return error, not swallow it") + require.True(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be true") + }) +} + +// TestV0ConversionConsistency_SuccessStatusMustBeSet ensures v0 conversion functions +// set Status.Conversion with Failed=false on successful conversion. +func TestV0ConversionConsistency_SuccessStatusMustBeSet(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Create a valid v0 dashboard + validV0 := &dashv0.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 42, + }, + }, + } + + t.Run("Convert_V0_to_V1beta1 must set success status", func(t *testing.T) { + target := &dashv1.Dashboard{} + err := Convert_V0_to_V1beta1(validV0, target, nil) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) + }) + + t.Run("Convert_V0_to_V2alpha1 must set success status", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + err := Convert_V0_to_V2alpha1(validV0, target, nil, dsProvider, leProvider) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) + }) + + t.Run("Convert_V0_to_V2beta1 must set success status", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + err := Convert_V0_to_V2beta1(validV0, target, nil, dsProvider, leProvider) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + require.Equal(t, dashv0.VERSION, *target.Status.Conversion.StoredVersion) + }) +} + +// TestV0ConversionConsistency_ObjectMetaMustBeSetOnError ensures v0 conversion functions +// set ObjectMeta, APIVersion, and Kind on the target even when conversion fails. +func TestV0ConversionConsistency_ObjectMetaMustBeSetOnError(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + invalidV0 := &dashv0.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + UID: "test-uid", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 0, + }, + }, + } + + t.Run("Convert_V0_to_V1beta1 must set ObjectMeta on error", func(t *testing.T) { + target := &dashv1.Dashboard{} + _ = Convert_V0_to_V1beta1(invalidV0, target, nil) + require.Equal(t, invalidV0.Name, target.Name, "Name must be set on error") + require.Equal(t, invalidV0.Namespace, target.Namespace, "Namespace must be set on error") + require.Equal(t, dashv1.APIVERSION, target.APIVersion, "APIVersion must be set on error") + }) + + t.Run("Convert_V0_to_V2alpha1 must set ObjectMeta on error", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + _ = Convert_V0_to_V2alpha1(invalidV0, target, nil, dsProvider, leProvider) + require.Equal(t, invalidV0.Name, target.Name, "Name must be set on error") + require.Equal(t, invalidV0.Namespace, target.Namespace, "Namespace must be set on error") + require.Equal(t, dashv2alpha1.APIVERSION, target.APIVersion, "APIVersion must be set on error") + }) + + t.Run("Convert_V0_to_V2beta1 must set ObjectMeta on error", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + _ = Convert_V0_to_V2beta1(invalidV0, target, nil, dsProvider, leProvider) + require.Equal(t, invalidV0.Name, target.Name, "Name must be set on error") + require.Equal(t, invalidV0.Namespace, target.Namespace, "Namespace must be set on error") + require.Equal(t, dashv2beta1.APIVERSION, target.APIVersion, "APIVersion must be set on error") + }) +} + +// TestV0ConversionConsistency_LayoutMustBeSetOnError ensures v2alpha1 and v2beta1 targets +// have a default layout set even when conversion fails to prevent JSON marshaling errors. +func TestV0ConversionConsistency_LayoutMustBeSetOnError(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + invalidV0 := &dashv0.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 0, + }, + }, + } + + t.Run("Convert_V0_to_V2alpha1 must set default layout on error", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + _ = Convert_V0_to_V2alpha1(invalidV0, target, nil, dsProvider, leProvider) + require.NotNil(t, target.Spec.Layout.GridLayoutKind, "GridLayoutKind must be set on error to prevent JSON marshaling issues") + }) + + t.Run("Convert_V0_to_V2beta1 must set default layout on error", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + _ = Convert_V0_to_V2beta1(invalidV0, target, nil, dsProvider, leProvider) + require.NotNil(t, target.Spec.Layout.GridLayoutKind, "GridLayoutKind must be set on error to prevent JSON marshaling issues") + }) +} diff --git a/apps/dashboard/pkg/migration/conversion/v1.go b/apps/dashboard/pkg/migration/conversion/v1.go index a6f2836b464..ac538e01e02 100644 --- a/apps/dashboard/pkg/migration/conversion/v1.go +++ b/apps/dashboard/pkg/migration/conversion/v1.go @@ -29,6 +29,9 @@ func Convert_V1beta1_to_V0(in *dashv1.Dashboard, out *dashv0.Dashboard, scope co func Convert_V1beta1_to_V2alpha1(in *dashv1.Dashboard, out *dashv2alpha1.Dashboard, scope conversion.Scope, dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) error { if err := ConvertDashboard_V1beta1_to_V2alpha1(in, out, scope, dsIndexProvider, leIndexProvider); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2alpha1.APIVERSION + out.Kind = in.Kind out.Status = dashv2alpha1.DashboardStatus{ Conversion: &dashv2alpha1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv1.VERSION), @@ -36,7 +39,6 @@ func Convert_V1beta1_to_V2alpha1(in *dashv1.Dashboard, out *dashv2alpha1.Dashboa Error: ptr.To(err.Error()), }, } - // Don't return error - just set status (matches test expectations and V0 pattern for Convert_V0_to_V2alpha1) // Ensure layout is set even on error to prevent JSON marshaling issues if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { out.Spec.Layout = dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ @@ -46,7 +48,7 @@ func Convert_V1beta1_to_V2alpha1(in *dashv1.Dashboard, out *dashv2alpha1.Dashboa }, } } - return nil + return err } // We need to make sure the layout is set to some value, otherwise the JSON marshaling will fail. @@ -59,12 +61,23 @@ func Convert_V1beta1_to_V2alpha1(in *dashv1.Dashboard, out *dashv2alpha1.Dashboa } } + // Set successful conversion status + out.Status = dashv2alpha1.DashboardStatus{ + Conversion: &dashv2alpha1.DashboardConversionStatus{ + StoredVersion: ptr.To(dashv1.VERSION), + Failed: false, + }, + } + return nil } func Convert_V1beta1_to_V2beta1(in *dashv1.Dashboard, out *dashv2beta1.Dashboard, scope conversion.Scope, dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) error { v2alpha1 := &dashv2alpha1.Dashboard{} if err := ConvertDashboard_V1beta1_to_V2alpha1(in, v2alpha1, scope, dsIndexProvider, leIndexProvider); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2beta1.APIVERSION + out.Kind = in.Kind out.Status = dashv2beta1.DashboardStatus{ Conversion: &dashv2beta1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv1.VERSION), @@ -72,10 +85,22 @@ func Convert_V1beta1_to_V2beta1(in *dashv1.Dashboard, out *dashv2beta1.Dashboard Error: ptr.To(err.Error()), }, } + // Ensure layout is set even on error to prevent JSON marshaling issues + if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { + out.Spec.Layout = dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + } + } return err } if err := ConvertDashboard_V2alpha1_to_V2beta1(v2alpha1, out, scope); err != nil { + out.ObjectMeta = in.ObjectMeta + out.APIVersion = dashv2beta1.APIVERSION + out.Kind = in.Kind out.Status = dashv2beta1.DashboardStatus{ Conversion: &dashv2beta1.DashboardConversionStatus{ StoredVersion: ptr.To(dashv1.VERSION), @@ -83,8 +108,25 @@ func Convert_V1beta1_to_V2beta1(in *dashv1.Dashboard, out *dashv2beta1.Dashboard Error: ptr.To(err.Error()), }, } + // Ensure layout is set even on error to prevent JSON marshaling issues + if out.Spec.Layout.GridLayoutKind == nil && out.Spec.Layout.RowsLayoutKind == nil { + out.Spec.Layout = dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + } + } return err } + // Set successful conversion status + out.Status = dashv2beta1.DashboardStatus{ + Conversion: &dashv2beta1.DashboardConversionStatus{ + StoredVersion: ptr.To(dashv1.VERSION), + Failed: false, + }, + } + return nil } diff --git a/apps/dashboard/pkg/migration/conversion/v1_test.go b/apps/dashboard/pkg/migration/conversion/v1_test.go index 4525e974e01..6eca186d3ee 100644 --- a/apps/dashboard/pkg/migration/conversion/v1_test.go +++ b/apps/dashboard/pkg/migration/conversion/v1_test.go @@ -19,11 +19,10 @@ func TestV1ConversionErrorHandling(t *testing.T) { // Initialize the migrator with a test data source provider dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) - t.Run("Convert_V1beta1_to_V2alpha1 sets status on conversion error", func(t *testing.T) { - // Create a dashboard that will cause conversion to fail - // We can use an invalid dashboard structure + t.Run("Convert_V1beta1_to_V2alpha1 sets status on successful conversion", func(t *testing.T) { + // Create a simple dashboard that will convert successfully source := &dashv1.Dashboard{ ObjectMeta: metav1.ObjectMeta{ Namespace: "org-1", @@ -31,7 +30,6 @@ func TestV1ConversionErrorHandling(t *testing.T) { Spec: common.Unstructured{ Object: map[string]interface{}{ "title": "test dashboard", - // Missing required fields that might cause conversion to fail }, }, } @@ -39,15 +37,14 @@ func TestV1ConversionErrorHandling(t *testing.T) { err := Convert_V1beta1_to_V2alpha1(source, target, nil, dsProvider, leProvider) - // Convert_V1beta1_to_V2alpha1 doesn't return error, just sets status - require.NoError(t, err, "Convert_V1beta1_to_V2alpha1 doesn't return error") + // Conversion should succeed + require.NoError(t, err) // Layout should always be set require.NotNil(t, target.Spec.Layout.GridLayoutKind) - // If conversion failed, status should be set - if target.Status.Conversion != nil { - require.True(t, target.Status.Conversion.Failed) - require.NotNil(t, target.Status.Conversion.Error) - } + // Status should be set with success + require.NotNil(t, target.Status.Conversion) + require.False(t, target.Status.Conversion.Failed) + require.Equal(t, dashv1.VERSION, *target.Status.Conversion.StoredVersion) }) t.Run("Convert_V1beta1_to_V2beta1 returns error on first step failure", func(t *testing.T) { @@ -126,3 +123,156 @@ func TestV1ConversionErrorHandling(t *testing.T) { } }) } + +// TestV1ConversionConsistency_ErrorsMustBeReturned ensures v1 conversion functions +// return errors instead of swallowing them. This prevents metrics and logs from being silently dropped. +func TestV1ConversionConsistency_ErrorsMustBeReturned(t *testing.T) { + leProvider := migrationtestutil.NewLibraryElementProvider() + + // Create a valid v1 dashboard - the nil dsProvider will cause conversion to fail + validV1 := &dashv1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 42, + }, + }, + } + + t.Run("Convert_V1beta1_to_V2alpha1 must return error on failure", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2alpha1(validV1, target, nil, nil, leProvider) + require.Error(t, err, "Convert_V1beta1_to_V2alpha1 must return error, not swallow it") + require.True(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be true") + }) + + t.Run("Convert_V1beta1_to_V2beta1 must return error on failure", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2beta1(validV1, target, nil, nil, leProvider) + require.Error(t, err, "Convert_V1beta1_to_V2beta1 must return error, not swallow it") + require.True(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be true") + }) +} + +// TestV1ConversionConsistency_SuccessStatusMustBeSet ensures v1 conversion functions +// set Status.Conversion with Failed=false on successful conversion. +func TestV1ConversionConsistency_SuccessStatusMustBeSet(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Create a valid v1 dashboard + validV1 := &dashv1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 42, + }, + }, + } + + t.Run("Convert_V1beta1_to_V2alpha1 must set success status", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + err := Convert_V1beta1_to_V2alpha1(validV1, target, nil, dsProvider, leProvider) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + require.Equal(t, dashv1.VERSION, *target.Status.Conversion.StoredVersion) + }) + + t.Run("Convert_V1beta1_to_V2beta1 must set success status", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + err := Convert_V1beta1_to_V2beta1(validV1, target, nil, dsProvider, leProvider) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + require.Equal(t, dashv1.VERSION, *target.Status.Conversion.StoredVersion) + }) +} + +// TestV1ConversionConsistency_ObjectMetaMustBeSetOnError ensures v1 conversion functions +// set ObjectMeta, APIVersion, and Kind on the target even when conversion fails. +func TestV1ConversionConsistency_ObjectMetaMustBeSetOnError(t *testing.T) { + leProvider := migrationtestutil.NewLibraryElementProvider() + + validV1 := &dashv1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + UID: "test-uid", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 42, + }, + }, + } + + t.Run("Convert_V1beta1_to_V2alpha1 must set ObjectMeta on error", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2alpha1(validV1, target, nil, nil, leProvider) + require.Error(t, err) + require.Equal(t, validV1.Name, target.Name, "Name must be set on error") + require.Equal(t, validV1.Namespace, target.Namespace, "Namespace must be set on error") + require.Equal(t, dashv2alpha1.APIVERSION, target.APIVersion, "APIVersion must be set on error") + }) + + t.Run("Convert_V1beta1_to_V2beta1 must set ObjectMeta on error", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2beta1(validV1, target, nil, nil, leProvider) + require.Error(t, err) + require.Equal(t, validV1.Name, target.Name, "Name must be set on error") + require.Equal(t, validV1.Namespace, target.Namespace, "Namespace must be set on error") + require.Equal(t, dashv2beta1.APIVERSION, target.APIVersion, "APIVersion must be set on error") + }) +} + +// TestV1ConversionConsistency_LayoutMustBeSetOnError ensures v2alpha1 and v2beta1 targets +// have a default layout set even when conversion fails to prevent JSON marshaling errors. +func TestV1ConversionConsistency_LayoutMustBeSetOnError(t *testing.T) { + leProvider := migrationtestutil.NewLibraryElementProvider() + + validV1 := &dashv1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "org-1", + Name: "test-dashboard", + }, + Spec: common.Unstructured{ + Object: map[string]interface{}{ + "title": "test dashboard", + "schemaVersion": 42, + }, + }, + } + + t.Run("Convert_V1beta1_to_V2alpha1 must set default layout on error", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2alpha1(validV1, target, nil, nil, leProvider) + require.Error(t, err) + require.NotNil(t, target.Spec.Layout.GridLayoutKind, "GridLayoutKind must be set on error to prevent JSON marshaling issues") + }) + + t.Run("Convert_V1beta1_to_V2beta1 must set default layout on error", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + // Pass nil dsProvider to cause conversion to fail + err := Convert_V1beta1_to_V2beta1(validV1, target, nil, nil, leProvider) + require.Error(t, err) + require.NotNil(t, target.Spec.Layout.GridLayoutKind, "GridLayoutKind must be set on error to prevent JSON marshaling issues") + }) +} diff --git a/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1.go b/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1.go index 4d6fd791fa9..81c52bcc43e 100644 --- a/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1.go +++ b/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1.go @@ -501,11 +501,9 @@ func convertToRowsLayout(ctx context.Context, panels []interface{}, dsIndexProvi if currentRow != nil { // If currentRow is a hidden-header row (panels before first explicit row), - // set its collapse to match the first explicit row's collapsed value - // This matches frontend behavior: collapse: panel.collapsed + // it should not be collapsed because it will disappear and be visible only in edit mode if currentRow.Spec.HideHeader != nil && *currentRow.Spec.HideHeader { - rowCollapsed := getBoolField(panelMap, "collapsed", false) - currentRow.Spec.Collapse = &rowCollapsed + currentRow.Spec.Collapse = &[]bool{false}[0] } // Flush current row to layout rows = append(rows, *currentRow) @@ -2022,6 +2020,9 @@ func transformPanelQueries(ctx context.Context, panelMap map[string]interface{}, func transformSingleQuery(ctx context.Context, targetMap map[string]interface{}, panelDatasource *dashv2alpha1.DashboardDataSourceRef, dsIndexProvider schemaversion.DataSourceIndexProvider) dashv2alpha1.DashboardPanelQueryKind { refId := schemaversion.GetStringValue(targetMap, "refId", "A") + if refId == "" { + refId = "A" + } hidden := getBoolField(targetMap, "hide", false) // Extract datasource from query or use panel datasource @@ -2195,6 +2196,32 @@ func transformDataLinks(panelMap map[string]interface{}) []dashv2alpha1.Dashboar return result } +// knownPanelProperties lists all properties defined in the Panel schema (dashboard_kind.cue) +// that should NOT be passed to Angular migration handlers. Only "unknown" Angular-specific +// properties should be passed to migration handlers. +var knownPanelProperties = map[string]bool{ + "type": true, "id": true, "pluginVersion": true, "targets": true, + "title": true, "description": true, "transparent": true, "datasource": true, + "gridPos": true, "links": true, "repeat": true, "repeatDirection": true, + "maxPerRow": true, "maxDataPoints": true, "transformations": true, + "interval": true, "timeFrom": true, "timeShift": true, "hideTimeOverride": true, + "timeCompare": true, "libraryPanel": true, "cacheTimeout": true, + "queryCachingTTL": true, "options": true, "fieldConfig": true, "autoMigrateFrom": true, +} + +// extractAngularOptions extracts only the Angular-specific options from a panel map, +// filtering out all known Panel schema properties. This is used to pass just the +// Angular options to migration handlers (e.g., sparkline, valueName, format for singlestat). +func extractAngularOptions(panelMap map[string]interface{}) map[string]interface{} { + result := make(map[string]interface{}) + for key, value := range panelMap { + if !knownPanelProperties[key] { + result[key] = value + } + } + return result +} + func buildVizConfig(panelMap map[string]interface{}) dashv2alpha1.DashboardVizConfigKind { panelType := schemaversion.GetStringValue(panelMap, "type", "timeseries") pluginVersion := schemaversion.GetStringValue(panelMap, "pluginVersion") @@ -2207,7 +2234,10 @@ func buildVizConfig(panelMap map[string]interface{}) dashv2alpha1.DashboardVizCo options := make(map[string]interface{}) if opts, ok := panelMap["options"].(map[string]interface{}); ok { - options = opts + // Deep copy options to avoid modifying the original + for k, v := range opts { + options[k] = v + } } // Add frontend-style default options to match frontend behavior @@ -2218,11 +2248,33 @@ func buildVizConfig(panelMap map[string]interface{}) dashv2alpha1.DashboardVizCo options["legend"] = legend } + // Handle Angular panel migrations + // This replicates the v0→v1 migration logic for panels that weren't migrated yet. + // We check two cases: + // 1. Panel already has autoMigrateFrom set (from v0→v1 migration) - panel type already converted + // 2. Panel type is a known Angular panel - need to convert type AND set autoMigrateFrom + autoMigrateFrom, hasAutoMigrateFrom := panelMap["autoMigrateFrom"].(string) + + if !hasAutoMigrateFrom || autoMigrateFrom == "" { + // Check if panel type is an Angular type that needs migration + if newType := getAngularPanelMigration(panelType, panelMap); newType != "" { + autoMigrateFrom = panelType // Original Angular type + panelType = newType // New modern type + } + } + + if autoMigrateFrom != "" { + options["__angularMigration"] = map[string]interface{}{ + "autoMigrateFrom": autoMigrateFrom, + "originalOptions": extractAngularOptions(panelMap), + } + } + // Build field config by mapping each field individually fieldConfigSource := extractFieldConfigSource(fieldConfig) return dashv2alpha1.DashboardVizConfigKind{ - Kind: panelType, // Use panelType as Kind (plugin ID) to match schema comment + Kind: panelType, // Use panelType as Kind (plugin ID) - may be converted from Angular type Spec: dashv2alpha1.DashboardVizConfigSpec{ PluginVersion: pluginVersion, FieldConfig: fieldConfigSource, @@ -2518,22 +2570,15 @@ func buildRegexMap(mappingMap map[string]interface{}) *dashv2alpha1.DashboardReg regexMap := &dashv2alpha1.DashboardRegexMap{} regexMap.Type = dashv2alpha1.DashboardMappingTypeRegex - opts, ok := mappingMap["options"].([]interface{}) - if !ok || len(opts) == 0 { - return nil - } - - optMap, ok := opts[0].(map[string]interface{}) + optMap, ok := mappingMap["options"].(map[string]interface{}) if !ok { return nil } r := dashv2alpha1.DashboardV2alpha1RegexMapOptions{} - if pattern, ok := optMap["regex"].(string); ok { + if pattern, ok := optMap["pattern"].(string); ok { r.Pattern = pattern } - - // Result is a DashboardValueMappingResult if resMap, ok := optMap["result"].(map[string]interface{}); ok { r.Result = buildValueMappingResult(resMap) } @@ -2670,3 +2715,10 @@ func extractFieldConfigOverrides(fieldConfig map[string]interface{}) []dashv2alp return result } + +// getAngularPanelMigration is a convenience wrapper around schemaversion.GetAngularPanelMigration. +// It checks if a panel type is an Angular panel and returns the new type to migrate to. +// Returns the new panel type if migration is needed, empty string otherwise. +func getAngularPanelMigration(panelType string, panelMap map[string]interface{}) string { + return schemaversion.GetAngularPanelMigration(panelType, panelMap) +} diff --git a/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1_test.go b/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1_test.go index 3dad9188fe7..a80bf9c8072 100644 --- a/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1_test.go +++ b/apps/dashboard/pkg/migration/conversion/v1beta1_to_v2alpha1_test.go @@ -19,7 +19,7 @@ func TestV1beta1ToV2alpha1(t *testing.T) { // Initialize the migrator with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() diff --git a/apps/dashboard/pkg/migration/conversion/v2.go b/apps/dashboard/pkg/migration/conversion/v2.go index fa8a49e91b4..beed5679b85 100644 --- a/apps/dashboard/pkg/migration/conversion/v2.go +++ b/apps/dashboard/pkg/migration/conversion/v2.go @@ -26,8 +26,7 @@ func Convert_V2alpha1_to_V0(in *dashv2alpha1.Dashboard, out *dashv0.Dashboard, s Source: in, }, } - // For errors, set status but don't return error - return nil + return err } // Convert v1beta1 → v0 @@ -43,8 +42,7 @@ func Convert_V2alpha1_to_V0(in *dashv2alpha1.Dashboard, out *dashv0.Dashboard, s Source: in, }, } - // For errors, set status but don't return error - return nil + return err } // Update the stored version to reflect the original source @@ -68,9 +66,7 @@ func Convert_V2alpha1_to_V1beta1(in *dashv2alpha1.Dashboard, out *dashv1.Dashboa Source: in, }, } - - // For errors, set status but don't return error - return nil + return err } // Set successful conversion status @@ -129,8 +125,7 @@ func Convert_V2beta1_to_V0(in *dashv2beta1.Dashboard, out *dashv0.Dashboard, sco Source: in, }, } - // For errors, set status but don't return error - return nil + return err } // Convert v1beta1 → v0 @@ -146,7 +141,7 @@ func Convert_V2beta1_to_V0(in *dashv2beta1.Dashboard, out *dashv0.Dashboard, sco Source: in, }, } - return nil + return err } // Update the stored version to reflect the original source @@ -172,8 +167,7 @@ func Convert_V2beta1_to_V1beta1(in *dashv2beta1.Dashboard, out *dashv1.Dashboard Source: in, }, } - // For errors, set status but don't return error - return nil + return err } // Convert v2alpha1 → v1beta1 @@ -188,8 +182,7 @@ func Convert_V2beta1_to_V1beta1(in *dashv2beta1.Dashboard, out *dashv1.Dashboard Source: in, }, } - // For errors, set status but don't return error - return nil + return err } // Set successful conversion status diff --git a/apps/dashboard/pkg/migration/conversion/v2_test.go b/apps/dashboard/pkg/migration/conversion/v2_test.go index cbacde6746e..3e218da9f81 100644 --- a/apps/dashboard/pkg/migration/conversion/v2_test.go +++ b/apps/dashboard/pkg/migration/conversion/v2_test.go @@ -18,7 +18,7 @@ func TestV2alpha1ConversionErrorHandling(t *testing.T) { // Initialize the migrator with test data source and library element providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("Convert_V2alpha1_to_V1beta1 sets status on conversion", func(t *testing.T) { // Create a dashboard for conversion @@ -90,7 +90,7 @@ func TestV2beta1ConversionErrorHandling(t *testing.T) { // Initialize the migrator with test data source and library element providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) t.Run("Convert_V2beta1_to_V1beta1 sets status on first step failure", func(t *testing.T) { // Create a dashboard that might cause conversion to fail on first step (v2beta1 -> v2alpha1) @@ -186,3 +186,141 @@ func TestV2beta1ConversionErrorHandling(t *testing.T) { } }) } + +// TestV2ConversionConsistency_SuccessStatusMustBeSet ensures v2 conversion functions +// set Status.Conversion with Failed=false on successful conversion. +func TestV2ConversionConsistency_SuccessStatusMustBeSet(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Create valid v2alpha1 dashboard + validV2alpha1 := &dashv2alpha1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: dashv2alpha1.DashboardSpec{ + Title: "test dashboard", + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{}, + }, + }, + }, + } + + // Create valid v2beta1 dashboard + validV2beta1 := &dashv2beta1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: dashv2beta1.DashboardSpec{ + Title: "test dashboard", + Layout: dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + }, + }, + } + + t.Run("Convert_V2alpha1_to_V1beta1 must set success status", func(t *testing.T) { + target := &dashv1.Dashboard{} + err := Convert_V2alpha1_to_V1beta1(validV2alpha1, target, nil) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + }) + + t.Run("Convert_V2alpha1_to_V2beta1 must set success status", func(t *testing.T) { + target := &dashv2beta1.Dashboard{} + err := Convert_V2alpha1_to_V2beta1(validV2alpha1, target, nil) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + }) + + t.Run("Convert_V2beta1_to_V1beta1 must set success status", func(t *testing.T) { + target := &dashv1.Dashboard{} + err := Convert_V2beta1_to_V1beta1(validV2beta1, target, nil, dsProvider) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + }) + + t.Run("Convert_V2beta1_to_V2alpha1 must set success status", func(t *testing.T) { + target := &dashv2alpha1.Dashboard{} + err := Convert_V2beta1_to_V2alpha1(validV2beta1, target, nil) + require.NoError(t, err) + require.NotNil(t, target.Status.Conversion, "Status.Conversion must be set on success") + require.False(t, target.Status.Conversion.Failed, "Status.Conversion.Failed must be false on success") + require.NotNil(t, target.Status.Conversion.StoredVersion, "StoredVersion must be set") + }) +} + +// TestV2ConversionConsistency_ErrorsMustBeReturned ensures v2 conversion functions +// return errors instead of swallowing them. This prevents metrics and logs from being silently dropped. +func TestV2ConversionConsistency_ErrorsMustBeReturned(t *testing.T) { + dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) + leProvider := migrationtestutil.NewLibraryElementProvider() + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) + + // Note: v2 conversions are harder to make fail since they don't go through schema migration. + // These tests verify that IF an error occurs, it is returned (not swallowed). + // The existing tests already cover this, but we add explicit assertions here. + + t.Run("Convert_V2alpha1_to_V2beta1 returns error on conversion failure", func(t *testing.T) { + // Valid dashboard should succeed + source := &dashv2alpha1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: dashv2alpha1.DashboardSpec{ + Title: "test dashboard", + Layout: dashv2alpha1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2alpha1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2alpha1.DashboardGridLayoutSpec{}, + }, + }, + }, + } + target := &dashv2beta1.Dashboard{} + err := Convert_V2alpha1_to_V2beta1(source, target, nil) + // This should succeed, verifying the function works + require.NoError(t, err) + require.False(t, target.Status.Conversion.Failed) + }) + + t.Run("Convert_V2beta1_to_V2alpha1 returns error on conversion failure", func(t *testing.T) { + // Valid dashboard should succeed + source := &dashv2beta1.Dashboard{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "default", + Name: "test-dashboard", + }, + Spec: dashv2beta1.DashboardSpec{ + Title: "test dashboard", + Layout: dashv2beta1.DashboardGridLayoutKindOrRowsLayoutKindOrAutoGridLayoutKindOrTabsLayoutKind{ + GridLayoutKind: &dashv2beta1.DashboardGridLayoutKind{ + Kind: "GridLayout", + Spec: dashv2beta1.DashboardGridLayoutSpec{}, + }, + }, + }, + } + target := &dashv2alpha1.Dashboard{} + err := Convert_V2beta1_to_V2alpha1(source, target, nil) + // This should succeed, verifying the function works + require.NoError(t, err) + require.False(t, target.Status.Conversion.Failed) + }) +} diff --git a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1.go b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1.go index fed2691db27..438aad5ead7 100644 --- a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1.go +++ b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1.go @@ -495,6 +495,9 @@ func processTabItem(elements map[string]dashv2alpha1.DashboardElement, tab *dash currentY = getMaxYFromPanels(nestedPanels, currentY) } else if tab.Spec.Layout.GridLayoutKind != nil { // GridLayout inside tab + baseY := currentY + maxY := currentY + for _, item := range tab.Spec.Layout.GridLayoutKind.Spec.Items { element, ok := elements[item.Spec.Element.Name] if !ok { @@ -502,7 +505,7 @@ func processTabItem(elements map[string]dashv2alpha1.DashboardElement, tab *dash } adjustedItem := item - adjustedItem.Spec.Y = item.Spec.Y + currentY + adjustedItem.Spec.Y = item.Spec.Y + baseY panel, err := convertPanelFromElement(&element, &adjustedItem) if err != nil { @@ -511,10 +514,12 @@ func processTabItem(elements map[string]dashv2alpha1.DashboardElement, tab *dash panels = append(panels, panel) panelEndY := adjustedItem.Spec.Y + item.Spec.Height - if panelEndY > currentY { - currentY = panelEndY + if panelEndY > maxY { + maxY = panelEndY } } + + currentY = maxY } else if tab.Spec.Layout.AutoGridLayoutKind != nil { // AutoGridLayout inside tab - convert with Y offset autoGridPanels, err := convertAutoGridLayoutToPanelsWithOffset(elements, tab.Spec.Layout.AutoGridLayoutKind, currentY) @@ -1059,7 +1064,8 @@ func convertPanelKindToV1(panelKind *dashv2alpha1.DashboardPanelKind, panel map[ } // Convert queries (targets) - targets := make([]map[string]interface{}, 0, len(spec.Data.Spec.Queries)) + // Use []interface{} for consistency with JSON unmarshaling and other code paths + targets := make([]interface{}, 0, len(spec.Data.Spec.Queries)) for _, query := range spec.Data.Spec.Queries { target := convertPanelQueryToV1(&query) targets = append(targets, target) diff --git a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1_test.go b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1_test.go index 6ed9804fc68..b3b4fb98395 100644 --- a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1_test.go +++ b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v1beta1_test.go @@ -282,7 +282,7 @@ func TestV2alpha1ToV1beta1LayoutErrors(t *testing.T) { // Initialize the migrator with test data source and library element providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -498,7 +498,7 @@ func TestV2alpha1ToV1beta1BasicFields(t *testing.T) { // Initialize the migrator with test data source and library element providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() diff --git a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v2beta1_test.go b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v2beta1_test.go index 028197bd655..e92c9215c34 100644 --- a/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v2beta1_test.go +++ b/apps/dashboard/pkg/migration/conversion/v2alpha1_to_v2beta1_test.go @@ -18,7 +18,7 @@ func TestV2alpha1ToV2beta1(t *testing.T) { // Initialize the migrator with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() diff --git a/apps/dashboard/pkg/migration/conversion/v2beta1_to_v2alpha1_test.go b/apps/dashboard/pkg/migration/conversion/v2beta1_to_v2alpha1_test.go index 23dcd36ee17..8b84ab40928 100644 --- a/apps/dashboard/pkg/migration/conversion/v2beta1_to_v2alpha1_test.go +++ b/apps/dashboard/pkg/migration/conversion/v2beta1_to_v2alpha1_test.go @@ -24,7 +24,7 @@ func TestV2beta1ToV2alpha1RoundTrip(t *testing.T) { // Initialize the migrator with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -107,7 +107,7 @@ func TestV2beta1ToV2alpha1FromOutputFiles(t *testing.T) { // Initialize the migrator with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() @@ -193,7 +193,7 @@ func TestV2beta1ToV2alpha1(t *testing.T) { // Initialize the migrator with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - migration.Initialize(dsProvider, leProvider) + migration.Initialize(dsProvider, leProvider, migration.DefaultCacheTTL) // Set up conversion scheme scheme := runtime.NewScheme() diff --git a/apps/dashboard/pkg/migration/frontend_defaults.go b/apps/dashboard/pkg/migration/frontend_defaults.go index 1df28c4de27..e8c779406a6 100644 --- a/apps/dashboard/pkg/migration/frontend_defaults.go +++ b/apps/dashboard/pkg/migration/frontend_defaults.go @@ -940,31 +940,12 @@ func applyPanelAutoMigration(panel map[string]interface{}) { return } - var newType string - // Graph needs special logic as it can be migrated to multiple panels // Including graphite which was previously migrated to graph in the schema version 2 migration in DashboardMigrator.ts // but this was a bug because in there graphite was set to graph, but since those migrations run // after PanelModel.restoreModel where autoMigrateFrom is set, this caused the graph migration to be skipped. // And this resulted in a dashboard with invalid panels. - if panelType == "graph" || panelType == "graphite" { - // Check xaxis mode for special cases - newType = getGraphAutoMigration(panel) - } else { - // Check autoMigrateAngular mapping - autoMigrateAngular := map[string]string{ - "table-old": "table", - "singlestat": "stat", - "grafana-singlestat-panel": "stat", - "grafana-piechart-panel": "piechart", - "grafana-worldmap-panel": "geomap", - "natel-discrete-panel": "state-timeline", - } - - if mappedType, exists := autoMigrateAngular[panelType]; exists { - newType = mappedType - } - } + newType := schemaversion.GetAngularPanelMigration(panelType, panel) // Apply auto-migration if a new type was determined if newType != "" { @@ -973,36 +954,6 @@ func applyPanelAutoMigration(panel map[string]interface{}) { } } -func getGraphAutoMigration(panel map[string]interface{}) string { - newType := "" - if xaxis, ok := panel["xaxis"].(map[string]interface{}); ok { - if mode, ok := xaxis["mode"].(string); ok { - switch mode { - case "series": - // Check legend values for bargauge - if legend, ok := panel["legend"].(map[string]interface{}); ok { - if values, ok := legend["values"].(bool); ok && values { - newType = "bargauge" - } else { - newType = "barchart" - } - } else { - newType = "barchart" - } - case "histogram": - newType = "histogram" - } - } - } - - // Default graph migration to timeseries - if newType == "" { - newType = "timeseries" - } - - return newType -} - // removeNullValuesRecursively removes null values from nested objects and arrays // This matches the frontend's JSON.stringify/parse behavior func removeNullValuesRecursively(data interface{}) { diff --git a/apps/dashboard/pkg/migration/migrate.go b/apps/dashboard/pkg/migration/migrate.go index 87940e943a3..d1b0fcbb7af 100644 --- a/apps/dashboard/pkg/migration/migrate.go +++ b/apps/dashboard/pkg/migration/migrate.go @@ -4,13 +4,19 @@ import ( "context" "fmt" "sync" + "time" + "github.com/grafana/authlib/types" + "github.com/grafana/grafana-app-sdk/logging" "github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion" ) +// DefaultCacheTTL is the default TTL for the datasource and library element caches. +const DefaultCacheTTL = time.Minute + // Initialize provides the migrator singleton with required dependencies and builds the map of migrations. -func Initialize(dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) { - migratorInstance.init(dsIndexProvider, leIndexProvider) +func Initialize(dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider, cacheTTL time.Duration) { + migratorInstance.init(dsIndexProvider, leIndexProvider, cacheTTL) } // GetDataSourceIndexProvider returns the datasource index provider instance that was initialized. @@ -38,6 +44,34 @@ func ResetForTesting() { initOnce = sync.Once{} } +// PreloadCache preloads the datasource and library element caches for the given namespaces. +func PreloadCache(ctx context.Context, nsInfos []types.NamespaceInfo) { + // Wait for initialization to complete + <-migratorInstance.ready + + // Try to preload datasource cache + if preloadable, ok := migratorInstance.dsIndexProvider.(schemaversion.PreloadableCache); ok { + preloadable.Preload(ctx, nsInfos) + } + + // Try to preload library element cache + if preloadable, ok := migratorInstance.leIndexProvider.(schemaversion.PreloadableCache); ok { + preloadable.Preload(ctx, nsInfos) + } +} + +// PreloadCacheInBackground starts a goroutine that preloads the caches for the given namespaces. +func PreloadCacheInBackground(nsInfos []types.NamespaceInfo) { + go func() { + defer func() { + if r := recover(); r != nil { + logging.DefaultLogger.Error("panic during cache preloading", "error", r) + } + }() + PreloadCache(context.Background(), nsInfos) + }() +} + // Migrate migrates the given dashboard to the target version. // This will block until the migrator is initialized. func Migrate(ctx context.Context, dash map[string]interface{}, targetVersion int) error { @@ -59,14 +93,14 @@ type migrator struct { leIndexProvider schemaversion.LibraryElementIndexProvider } -func (m *migrator) init(dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider) { +func (m *migrator) init(dsIndexProvider schemaversion.DataSourceIndexProvider, leIndexProvider schemaversion.LibraryElementIndexProvider, cacheTTL time.Duration) { initOnce.Do(func() { - // Wrap the provider once with 10s caching for all conversions. + // Wrap the provider with org-aware TTL caching for all conversions. // This prevents repeated DB queries across multiple conversion calls while allowing // the cache to refresh periodically, making it suitable for long-lived singleton usage. - m.dsIndexProvider = schemaversion.WrapIndexProviderWithCache(dsIndexProvider) + m.dsIndexProvider = schemaversion.WrapIndexProviderWithCache(dsIndexProvider, cacheTTL) // Wrap library element provider with caching as well - m.leIndexProvider = schemaversion.WrapLibraryElementProviderWithCache(leIndexProvider) + m.leIndexProvider = schemaversion.WrapLibraryElementProviderWithCache(leIndexProvider, cacheTTL) m.migrations = schemaversion.GetMigrations(m.dsIndexProvider, m.leIndexProvider) close(m.ready) }) diff --git a/apps/dashboard/pkg/migration/migrate_test.go b/apps/dashboard/pkg/migration/migrate_test.go index 8bb150f91ca..4fe4ea90a60 100644 --- a/apps/dashboard/pkg/migration/migrate_test.go +++ b/apps/dashboard/pkg/migration/migrate_test.go @@ -10,10 +10,13 @@ import ( "path/filepath" "strconv" "strings" + "sync/atomic" "testing" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "k8s.io/apiserver/pkg/endpoints/request" "github.com/grafana/grafana/apps/dashboard/pkg/migration/schemaversion" migrationtestutil "github.com/grafana/grafana/apps/dashboard/pkg/migration/testutil" @@ -31,7 +34,7 @@ func TestMigrate(t *testing.T) { ResetForTesting() dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - Initialize(dsProvider, leProvider) + Initialize(dsProvider, leProvider, DefaultCacheTTL) t.Run("minimum version check", func(t *testing.T) { err := Migrate(context.Background(), map[string]interface{}{ @@ -49,7 +52,7 @@ func TestMigrateSingleVersion(t *testing.T) { // Use the same datasource provider as the frontend test to ensure consistency dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - Initialize(dsProvider, leProvider) + Initialize(dsProvider, leProvider, DefaultCacheTTL) runSingleVersionMigrationTests(t, SINGLE_VERSION_OUTPUT_DIR) } @@ -218,7 +221,7 @@ func TestSchemaMigrationMetrics(t *testing.T) { // Initialize migration with test providers dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - Initialize(dsProvider, leProvider) + Initialize(dsProvider, leProvider, DefaultCacheTTL) // Create a test registry for metrics registry := prometheus.NewRegistry() @@ -304,7 +307,7 @@ func TestSchemaMigrationMetrics(t *testing.T) { func TestSchemaMigrationLogging(t *testing.T) { dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.StandardTestConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - Initialize(dsProvider, leProvider) + Initialize(dsProvider, leProvider, DefaultCacheTTL) tests := []struct { name string @@ -423,7 +426,7 @@ func TestMigrateDevDashboards(t *testing.T) { ResetForTesting() dsProvider := migrationtestutil.NewDataSourceProvider(migrationtestutil.DevDashboardConfig) leProvider := migrationtestutil.NewLibraryElementProvider() - Initialize(dsProvider, leProvider) + Initialize(dsProvider, leProvider, DefaultCacheTTL) runDevDashboardMigrationTests(t, schemaversion.LATEST_VERSION, DEV_DASHBOARDS_OUTPUT_DIR) } @@ -449,3 +452,232 @@ func runDevDashboardMigrationTests(t *testing.T, targetVersion int, outputDir st }) } } + +func TestMigrateWithCache(t *testing.T) { + // Reset the migration singleton before each test + ResetForTesting() + datasources := []schemaversion.DataSourceInfo{ + {UID: "ds-uid-1", Type: "prometheus", Name: "Prometheus", Default: true, APIVersion: "v1"}, + {UID: "ds-uid-2", Type: "loki", Name: "Loki", Default: false, APIVersion: "v1"}, + {UID: "ds-uid-3", Type: "prometheus", Name: "Prometheus 2", Default: false, APIVersion: "v1"}, + } + + // Create a dashboard at schema version 32 for V33 and V36 migration with datasource references + dashboard1 := map[string]interface{}{ + "schemaVersion": 32, + "title": "Test Dashboard 1", + "panels": []interface{}{ + map[string]interface{}{ + "id": 1, + "type": "timeseries", + // String datasource that V33 will migrate to object reference + "datasource": "Prometheus", + "targets": []interface{}{ + map[string]interface{}{ + "refId": "A", + "datasource": "Loki", + }, + }, + }, + }, + } + + // Create a dashboard at schema version 35 for testing V36 migration with datasource references in annotations + dashboard2 := map[string]interface{}{ + "schemaVersion": 35, + "title": "Test Dashboard 2", + "annotations": map[string]interface{}{ + "list": []interface{}{ + map[string]interface{}{ + "name": "Test Annotation", + "datasource": "Prometheus 2", // String reference that V36 should convert + "enable": true, + }, + }, + }, + } + + t.Run("with datasources", func(t *testing.T) { + ResetForTesting() + dsProvider := newCountingProvider(datasources) + leProvider := newCountingLibraryProvider(nil) + // Initialize the migration system with our counting providers + Initialize(dsProvider, leProvider, DefaultCacheTTL) + // Verify initial call count is zero + assert.Equal(t, dsProvider.GetCallCount(), int64(0)) + // Create a context with namespace (required for caching) + ctx := request.WithNamespace(context.Background(), "default") + + // First migration - should invoke the provider once to build the cache + dash1 := deepCopyDashboard(dashboard1) + err := Migrate(ctx, dash1, schemaversion.LATEST_VERSION) + require.NoError(t, err) + assert.Equal(t, int64(1), dsProvider.GetCallCount()) + + // Verify datasource conversion from string to object reference + panels := dash1["panels"].([]interface{}) + panel := panels[0].(map[string]interface{}) + panelDS, ok := panel["datasource"].(map[string]interface{}) + require.True(t, ok, "panel datasource should be converted to object") + assert.Equal(t, "ds-uid-1", panelDS["uid"]) + assert.Equal(t, "prometheus", panelDS["type"]) + + // Verify target datasource conversion + targets := panel["targets"].([]interface{}) + target := targets[0].(map[string]interface{}) + targetDS, ok := target["datasource"].(map[string]interface{}) + require.True(t, ok, "target datasource should be converted to object") + assert.Equal(t, "ds-uid-2", targetDS["uid"]) + assert.Equal(t, "loki", targetDS["type"]) + + // Migration with V35 dashboard - should use the cached index from first migration + dash2 := deepCopyDashboard(dashboard2) + err = Migrate(ctx, dash2, schemaversion.LATEST_VERSION) + require.NoError(t, err, "second migration should succeed") + assert.Equal(t, int64(1), dsProvider.GetCallCount()) + + // Verify the annotation datasource was converted to object reference + annotations := dash2["annotations"].(map[string]interface{}) + list := annotations["list"].([]interface{}) + var testAnnotation map[string]interface{} + for _, a := range list { + ann := a.(map[string]interface{}) + if ann["name"] == "Test Annotation" { + testAnnotation = ann + break + } + } + require.NotNil(t, testAnnotation, "Test Annotation should exist") + annotationDS, ok := testAnnotation["datasource"].(map[string]interface{}) + require.True(t, ok, "annotation datasource should be converted to object") + assert.Equal(t, "ds-uid-3", annotationDS["uid"]) + assert.Equal(t, "prometheus", annotationDS["type"]) + }) + + // tests that cache isolates data per namespace + t.Run("with multiple orgs", func(t *testing.T) { + // Reset the migration singleton + ResetForTesting() + dsProvider := newCountingProvider(datasources) + leProvider := newCountingLibraryProvider(nil) + Initialize(dsProvider, leProvider, DefaultCacheTTL) + // Create contexts for different orgs with proper namespace format (org-ID) + ctx1 := request.WithNamespace(context.Background(), "default") // org 1 + ctx2 := request.WithNamespace(context.Background(), "stacks-2") // stack 2 + + // Migrate for org 1 + err := Migrate(ctx1, deepCopyDashboard(dashboard1), schemaversion.LATEST_VERSION) + require.NoError(t, err) + callsAfterOrg1 := dsProvider.GetCallCount() + + // Migrate for org 2 - should build separate cache + err = Migrate(ctx2, deepCopyDashboard(dashboard2), schemaversion.LATEST_VERSION) + require.NoError(t, err) + callsAfterOrg2 := dsProvider.GetCallCount() + + assert.Greater(t, callsAfterOrg2, callsAfterOrg1, + "org 2 migration should have called provider (separate cache)") + + // Migrate again for org 1 - should use cache + err = Migrate(ctx1, deepCopyDashboard(dashboard1), schemaversion.LATEST_VERSION) + require.NoError(t, err) + callsAfterOrg1Again := dsProvider.GetCallCount() + assert.Equal(t, callsAfterOrg2, callsAfterOrg1Again, + "second org 1 migration should use cache") + + // Migrate again for org 2 - should use cache + err = Migrate(ctx2, deepCopyDashboard(dashboard1), schemaversion.LATEST_VERSION) + require.NoError(t, err) + callsAfterOrg2Again := dsProvider.GetCallCount() + assert.Equal(t, callsAfterOrg2, callsAfterOrg2Again, + "second org 2 migration should use cache") + }) +} + +// countingProvider wraps a datasource provider and counts calls to Index() +type countingProvider struct { + datasources []schemaversion.DataSourceInfo + callCount atomic.Int64 +} + +func newCountingProvider(datasources []schemaversion.DataSourceInfo) *countingProvider { + return &countingProvider{ + datasources: datasources, + } +} + +func (p *countingProvider) Index(_ context.Context) *schemaversion.DatasourceIndex { + p.callCount.Add(1) + return schemaversion.NewDatasourceIndex(p.datasources) +} + +func (p *countingProvider) GetCallCount() int64 { + return p.callCount.Load() +} + +// countingLibraryProvider wraps a library element provider and counts calls +type countingLibraryProvider struct { + elements []schemaversion.LibraryElementInfo + callCount atomic.Int64 +} + +func newCountingLibraryProvider(elements []schemaversion.LibraryElementInfo) *countingLibraryProvider { + return &countingLibraryProvider{ + elements: elements, + } +} + +func (p *countingLibraryProvider) GetLibraryElementInfo(_ context.Context) []schemaversion.LibraryElementInfo { + p.callCount.Add(1) + return p.elements +} + +func (p *countingLibraryProvider) GetCallCount() int64 { + return p.callCount.Load() +} + +// deepCopyDashboard creates a deep copy of a dashboard map +func deepCopyDashboard(dash map[string]interface{}) map[string]interface{} { + cpy := make(map[string]interface{}) + for k, v := range dash { + switch val := v.(type) { + case []interface{}: + cpy[k] = deepCopySlice(val) + case map[string]interface{}: + cpy[k] = deepCopyMapForCache(val) + default: + cpy[k] = v + } + } + return cpy +} + +func deepCopySlice(s []interface{}) []interface{} { + cpy := make([]interface{}, len(s)) + for i, v := range s { + switch val := v.(type) { + case []interface{}: + cpy[i] = deepCopySlice(val) + case map[string]interface{}: + cpy[i] = deepCopyMapForCache(val) + default: + cpy[i] = v + } + } + return cpy +} + +func deepCopyMapForCache(m map[string]interface{}) map[string]interface{} { + cpy := make(map[string]interface{}) + for k, v := range m { + switch val := v.(type) { + case []interface{}: + cpy[k] = deepCopySlice(val) + case map[string]interface{}: + cpy[k] = deepCopyMapForCache(val) + default: + cpy[k] = v + } + } + return cpy +} diff --git a/apps/dashboard/pkg/migration/schemaversion/cache.go b/apps/dashboard/pkg/migration/schemaversion/cache.go new file mode 100644 index 00000000000..2548c2cc5ba --- /dev/null +++ b/apps/dashboard/pkg/migration/schemaversion/cache.go @@ -0,0 +1,100 @@ +package schemaversion + +import ( + "context" + "sync" + "time" + + "github.com/hashicorp/golang-lru/v2/expirable" + "k8s.io/apiserver/pkg/endpoints/request" + + "github.com/grafana/authlib/types" + "github.com/grafana/grafana-app-sdk/logging" +) + +const defaultCacheSize = 1000 + +// CacheProvider is a generic cache interface for schema version providers. +type CacheProvider[T any] interface { + // Get returns the cached value if it's still valid, otherwise calls fetch and caches the result. + Get(ctx context.Context) T +} + +// PreloadableCache is an interface for providers that support preloading the cache. +type PreloadableCache interface { + // Preload loads data into the cache for the given namespaces. + Preload(ctx context.Context, nsInfos []types.NamespaceInfo) +} + +// cachedProvider is a thread-safe TTL cache that wraps any fetch function. +type cachedProvider[T any] struct { + fetch func(context.Context) T + cache *expirable.LRU[string, T] // LRU cache: namespace to cache entry + inFlight sync.Map // map[string]*sync.Mutex - per-namespace fetch locks +} + +// newCachedProvider creates a new cachedProvider. +// The fetch function should be able to handle context with different namespaces. +// A non-positive size turns LRU mechanism off (cache of unlimited size). +// A non-positive cacheTTL disables TTL expiration. +func newCachedProvider[T any](fetch func(context.Context) T, size int, cacheTTL time.Duration) *cachedProvider[T] { + cacheProvider := &cachedProvider[T]{ + fetch: fetch, + } + cacheProvider.cache = expirable.NewLRU(size, func(key string, value T) { + cacheProvider.inFlight.Delete(key) + }, cacheTTL) + return cacheProvider +} + +// Get returns the cached value if it's still valid, otherwise calls fetch and caches the result. +func (p *cachedProvider[T]) Get(ctx context.Context) T { + // Get namespace info from ctx + namespace, ok := request.NamespaceFrom(ctx) + if !ok { + // No namespace, fall back to direct fetch call without caching + logging.FromContext(ctx).Warn("Unable to get namespace info from context, skipping cache") + return p.fetch(ctx) + } + + // Fast path: check if cache is still valid + if entry, ok := p.cache.Get(namespace); ok { + return entry + } + + // Get or create a per-namespace lock for this fetch operation + // This ensures only one fetch happens per namespace at a time + lockInterface, _ := p.inFlight.LoadOrStore(namespace, &sync.Mutex{}) + nsMutex := lockInterface.(*sync.Mutex) + + // Lock this specific namespace - other namespaces can still proceed + nsMutex.Lock() + defer nsMutex.Unlock() + + // Double-check: another goroutine might have already fetched while we waited + if entry, ok := p.cache.Get(namespace); ok { + return entry + } + + // Fetch outside the main lock - only this namespace is blocked + logging.FromContext(ctx).Debug("cache miss or expired, fetching new value", "namespace", namespace) + value := p.fetch(ctx) + + // Update the cache for this namespace + p.cache.Add(namespace, value) + + return value +} + +// Preload loads data into the cache for the given namespaces. +func (p *cachedProvider[T]) Preload(ctx context.Context, nsInfos []types.NamespaceInfo) { + // Build the cache using a context with the namespace + logging.FromContext(ctx).Info("preloading cache", "nsInfos", len(nsInfos)) + startedAt := time.Now() + defer func() { + logging.FromContext(ctx).Info("finished preloading cache", "nsInfos", len(nsInfos), "elapsed", time.Since(startedAt)) + }() + for _, nsInfo := range nsInfos { + p.cache.Add(nsInfo.Value, p.fetch(request.WithNamespace(ctx, nsInfo.Value))) + } +} diff --git a/apps/dashboard/pkg/migration/schemaversion/cache_test.go b/apps/dashboard/pkg/migration/schemaversion/cache_test.go new file mode 100644 index 00000000000..081455143e4 --- /dev/null +++ b/apps/dashboard/pkg/migration/schemaversion/cache_test.go @@ -0,0 +1,478 @@ +package schemaversion + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/apiserver/pkg/endpoints/request" + + authlib "github.com/grafana/authlib/types" +) + +// testProvider tracks how many times get() is called +type testProvider struct { + testData any + callCount atomic.Int64 +} + +func newTestProvider(testData any) *testProvider { + return &testProvider{ + testData: testData, + } +} + +func (p *testProvider) get(_ context.Context) any { + p.callCount.Add(1) + return p.testData +} + +func (p *testProvider) getCallCount() int64 { + return p.callCount.Load() +} + +func TestCachedProvider_CacheHit(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + {UID: "ds2", Type: "loki", Name: "Loki"}, + } + + underlying := newTestProvider(datasources) + // Test newCachedProvider directly instead of the wrapper + cached := newCachedProvider(underlying.get, defaultCacheSize, time.Minute) + + // Use "default" namespace (org 1) - this is the standard Grafana namespace format + ctx := request.WithNamespace(context.Background(), "default") + + // First call should hit the underlying provider + idx1 := cached.Get(ctx) + require.NotNil(t, idx1) + assert.Equal(t, int64(1), underlying.getCallCount(), "first call should invoke underlying provider") + + // Second call should use cache + idx2 := cached.Get(ctx) + require.NotNil(t, idx2) + assert.Equal(t, int64(1), underlying.getCallCount(), "second call should use cache, not invoke underlying provider") + + // Both should return the same data + assert.Equal(t, idx1, idx2) +} + +func TestCachedProvider_NamespaceIsolation(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + + underlying := newTestProvider(datasources) + cached := newCachedProvider(underlying.get, defaultCacheSize, time.Minute) + + // Use "default" (org 1) and "org-2" (org 2) - standard Grafana namespace formats + ctx1 := request.WithNamespace(context.Background(), "default") + ctx2 := request.WithNamespace(context.Background(), "org-2") + + // First call for org 1 + idx1 := cached.Get(ctx1) + require.NotNil(t, idx1) + assert.Equal(t, int64(1), underlying.getCallCount(), "first org-1 call should invoke underlying provider") + + // Call for org 2 should also invoke underlying provider (different namespace) + idx2 := cached.Get(ctx2) + require.NotNil(t, idx2) + assert.Equal(t, int64(2), underlying.getCallCount(), "org-2 call should invoke underlying provider (separate cache)") + + // Second call for org 1 should use cache + idx3 := cached.Get(ctx1) + require.NotNil(t, idx3) + assert.Equal(t, int64(2), underlying.getCallCount(), "second org-1 call should use cache") + + // Second call for org 2 should use cache + idx4 := cached.Get(ctx2) + require.NotNil(t, idx4) + assert.Equal(t, int64(2), underlying.getCallCount(), "second org-2 call should use cache") +} + +func TestCachedProvider_NoNamespaceFallback(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + + underlying := newTestProvider(datasources) + cached := newCachedProvider(underlying.get, defaultCacheSize, time.Minute) + + // Context without namespace - should fall back to direct provider call + ctx := context.Background() + + idx1 := cached.Get(ctx) + require.NotNil(t, idx1) + assert.Equal(t, int64(1), underlying.getCallCount()) + + // Second call without namespace should also invoke underlying (no caching for unknown namespace) + idx2 := cached.Get(ctx) + require.NotNil(t, idx2) + assert.Equal(t, int64(2), underlying.getCallCount(), "without namespace, each call should invoke underlying provider") +} + +func TestCachedProvider_ConcurrentAccess(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + + underlying := newTestProvider(datasources) + cached := newCachedProvider(underlying.get, defaultCacheSize, time.Minute) + + // Use "default" namespace (org 1) + ctx := request.WithNamespace(context.Background(), "default") + + var wg sync.WaitGroup + numGoroutines := 100 + + // Launch many goroutines that all try to access the cache simultaneously + for i := 0; i < numGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + idx := cached.Get(ctx) + require.NotNil(t, idx) + }() + } + + wg.Wait() + + // Due to double-check locking, only 1 goroutine should have actually built the cache + // In practice, there might be a few more due to timing, but it should be much less than numGoroutines + callCount := underlying.getCallCount() + assert.LessOrEqual(t, callCount, int64(5), "with proper locking, very few goroutines should invoke underlying provider; got %d", callCount) +} + +func TestCachedProvider_ConcurrentNamespaces(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + + underlying := newTestProvider(datasources) + cached := newCachedProvider(underlying.get, defaultCacheSize, time.Minute) + + var wg sync.WaitGroup + numOrgs := 10 + callsPerOrg := 20 + + // Launch goroutines for multiple namespaces + // Use valid namespace formats: "default" for org 1, "org-N" for N > 1 + namespaces := make([]string, numOrgs) + namespaces[0] = "default" + for i := 1; i < numOrgs; i++ { + namespaces[i] = fmt.Sprintf("org-%d", i+1) + } + + for _, ns := range namespaces { + ctx := request.WithNamespace(context.Background(), ns) + for i := 0; i < callsPerOrg; i++ { + wg.Add(1) + go func(ctx context.Context) { + defer wg.Done() + idx := cached.Get(ctx) + require.NotNil(t, idx) + }(ctx) + } + } + + wg.Wait() + + // Each org should have at most a few calls (ideally 1, but timing can cause a few more) + callCount := underlying.getCallCount() + // With 10 orgs, we expect around 10 calls (one per org) + assert.LessOrEqual(t, callCount, int64(numOrgs), "expected roughly one call per org, got %d calls for %d orgs", callCount, numOrgs) +} + +// Test that cache returns correct data for each namespace +func TestCachedProvider_CorrectDataPerNamespace(t *testing.T) { + // Provider that returns different data based on namespace + underlying := &namespaceAwareProvider{ + datasourcesByNamespace: map[string][]DataSourceInfo{ + "default": {{UID: "org1-ds", Type: "prometheus", Name: "Org1 DS", Default: true}}, + "org-2": {{UID: "org2-ds", Type: "loki", Name: "Org2 DS", Default: true}}, + }, + } + cached := newCachedProvider(underlying.Index, defaultCacheSize, time.Minute) + + // Use valid namespace formats + ctx1 := request.WithNamespace(context.Background(), "default") + ctx2 := request.WithNamespace(context.Background(), "org-2") + + idx1 := cached.Get(ctx1) + idx2 := cached.Get(ctx2) + + assert.Equal(t, "org1-ds", idx1.GetDefault().UID, "org 1 should get org-1 datasources") + assert.Equal(t, "org2-ds", idx2.GetDefault().UID, "org 2 should get org-2 datasources") + + // Subsequent calls should still return correct data + idx1Again := cached.Get(ctx1) + idx2Again := cached.Get(ctx2) + + assert.Equal(t, "org1-ds", idx1Again.GetDefault().UID, "org 1 should still get org-1 datasources from cache") + assert.Equal(t, "org2-ds", idx2Again.GetDefault().UID, "org 2 should still get org-2 datasources from cache") +} + +// TestCachedProvider_PreloadMultipleNamespaces verifies preloading multiple namespaces +func TestCachedProvider_PreloadMultipleNamespaces(t *testing.T) { + // Provider that returns different data based on namespace + underlying := &namespaceAwareProvider{ + datasourcesByNamespace: map[string][]DataSourceInfo{ + "default": {{UID: "org1-ds", Type: "prometheus", Name: "Org1 DS", Default: true}}, + "org-2": {{UID: "org2-ds", Type: "loki", Name: "Org2 DS", Default: true}}, + "org-3": {{UID: "org3-ds", Type: "tempo", Name: "Org3 DS", Default: true}}, + }, + } + cached := newCachedProvider(underlying.Index, defaultCacheSize, time.Minute) + + // Preload multiple namespaces + nsInfos := []authlib.NamespaceInfo{ + createNamespaceInfo(1, 0, "default"), + createNamespaceInfo(2, 0, "org-2"), + createNamespaceInfo(3, 0, "org-3"), + } + cached.Preload(context.Background(), nsInfos) + + // After preload, the underlying provider should have been called once per namespace + assert.Equal(t, 3, underlying.callCount, "preload should call underlying provider once per namespace") + + // Access all namespaces - should use preloaded data and get correct data per namespace + expectedUIDs := map[string]string{ + "default": "org1-ds", + "org-2": "org2-ds", + "org-3": "org3-ds", + } + + for _, ns := range []string{"default", "org-2", "org-3"} { + ctx := request.WithNamespace(context.Background(), ns) + idx := cached.Get(ctx) + require.NotNil(t, idx, "index for namespace %s should not be nil", ns) + assert.Equal(t, expectedUIDs[ns], idx.GetDefault().UID, "namespace %s should get correct datasource", ns) + } + + // The underlying provider should still have been called only 3 times (from preload) + assert.Equal(t, 3, underlying.callCount, + "access after preload should use cached data for all namespaces") +} + +// namespaceAwareProvider returns different datasources based on namespace +type namespaceAwareProvider struct { + datasourcesByNamespace map[string][]DataSourceInfo + callCount int +} + +func (p *namespaceAwareProvider) Index(ctx context.Context) *DatasourceIndex { + p.callCount++ + ns := request.NamespaceValue(ctx) + if ds, ok := p.datasourcesByNamespace[ns]; ok { + return NewDatasourceIndex(ds) + } + return NewDatasourceIndex(nil) +} + +// createNamespaceInfo creates a NamespaceInfo for testing +func createNamespaceInfo(orgID, stackID int64, value string) authlib.NamespaceInfo { + return authlib.NamespaceInfo{ + OrgID: orgID, + StackID: stackID, + Value: value, + } +} + +// Test DatasourceIndex functionality +func TestDatasourceIndex_Lookup(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds-uid-1", Type: "prometheus", Name: "Prometheus DS", Default: true, APIVersion: "v1"}, + {UID: "ds-uid-2", Type: "loki", Name: "Loki DS", Default: false, APIVersion: "v1"}, + } + idx := NewDatasourceIndex(datasources) + + t.Run("lookup by name", func(t *testing.T) { + ds := idx.Lookup("Prometheus DS") + require.NotNil(t, ds) + assert.Equal(t, "ds-uid-1", ds.UID) + }) + + t.Run("lookup by UID", func(t *testing.T) { + ds := idx.Lookup("ds-uid-2") + require.NotNil(t, ds) + assert.Equal(t, "Loki DS", ds.Name) + }) + + t.Run("lookup unknown returns nil", func(t *testing.T) { + ds := idx.Lookup("unknown") + assert.Nil(t, ds) + }) + + t.Run("get default", func(t *testing.T) { + ds := idx.GetDefault() + require.NotNil(t, ds) + assert.Equal(t, "ds-uid-1", ds.UID) + }) + + t.Run("lookup by UID directly", func(t *testing.T) { + ds := idx.LookupByUID("ds-uid-1") + require.NotNil(t, ds) + assert.Equal(t, "Prometheus DS", ds.Name) + }) + + t.Run("lookup by name directly", func(t *testing.T) { + ds := idx.LookupByName("Loki DS") + require.NotNil(t, ds) + assert.Equal(t, "ds-uid-2", ds.UID) + }) +} + +func TestDatasourceIndex_EmptyIndex(t *testing.T) { + idx := NewDatasourceIndex(nil) + + assert.Nil(t, idx.GetDefault()) + assert.Nil(t, idx.Lookup("anything")) + assert.Nil(t, idx.LookupByUID("anything")) + assert.Nil(t, idx.LookupByName("anything")) +} + +// TestCachedProvider_TTLExpiration verifies that cache expires after TTL +func TestCachedProvider_TTLExpiration(t *testing.T) { + datasources := []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + } + + underlying := newTestProvider(datasources) + // Use a very short TTL for testing + shortTTL := 50 * time.Millisecond + cached := newCachedProvider(underlying.get, defaultCacheSize, shortTTL) + + ctx := request.WithNamespace(context.Background(), "default") + + // First call - should call underlying provider + idx1 := cached.Get(ctx) + require.NotNil(t, idx1) + assert.Equal(t, int64(1), underlying.getCallCount(), "first call should invoke underlying provider") + + // Second call immediately - should use cache + idx2 := cached.Get(ctx) + require.NotNil(t, idx2) + assert.Equal(t, int64(1), underlying.getCallCount(), "second call should use cache") + + // Wait for TTL to expire + time.Sleep(shortTTL + 20*time.Millisecond) + + // Third call after TTL - should call underlying provider again + idx3 := cached.Get(ctx) + require.NotNil(t, idx3) + assert.Equal(t, int64(2), underlying.getCallCount(), + "after TTL expiration, underlying provider should be called again") +} + +// TestCachedProvider_ParallelNamespacesFetch verifies that different namespaces can fetch in parallel +func TestCachedProvider_ParallelNamespacesFetch(t *testing.T) { + // Create a blocking provider that tracks concurrent executions + provider := &blockingProvider{ + blockDuration: 100 * time.Millisecond, + datasources: []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + }, + } + cached := newCachedProvider(provider.get, defaultCacheSize, time.Minute) + + numNamespaces := 5 + var wg sync.WaitGroup + + // Launch fetches for different namespaces simultaneously + startTime := time.Now() + for i := 0; i < numNamespaces; i++ { + wg.Add(1) + namespace := fmt.Sprintf("org-%d", i+1) + go func(ns string) { + defer wg.Done() + ctx := request.WithNamespace(context.Background(), ns) + idx := cached.Get(ctx) + require.NotNil(t, idx) + }(namespace) + } + wg.Wait() + elapsed := time.Since(startTime) + + // Verify that all namespaces were called + assert.Equal(t, int64(numNamespaces), provider.callCount.Load()) + + // Verify max concurrent executions shows parallelism + maxConcurrent := provider.maxConcurrent.Load() + assert.Equal(t, int64(numNamespaces), maxConcurrent) + + // If all namespaces had to wait sequentially, it would take numNamespaces * blockDuration + // With parallelism, it should be much faster (close to just blockDuration) + sequentialTime := time.Duration(numNamespaces) * provider.blockDuration + assert.Less(t, elapsed, sequentialTime) +} + +// TestCachedProvider_SameNamespaceSerialFetch verifies that the same namespace doesn't fetch concurrently +func TestCachedProvider_SameNamespaceSerialFetch(t *testing.T) { + // Create a blocking provider that tracks concurrent executions + provider := &blockingProvider{ + blockDuration: 100 * time.Millisecond, + datasources: []DataSourceInfo{ + {UID: "ds1", Type: "prometheus", Name: "Prometheus", Default: true}, + }, + } + cached := newCachedProvider(provider.get, defaultCacheSize, time.Minute) + + numGoroutines := 10 + var wg sync.WaitGroup + + // Launch multiple fetches for the SAME namespace simultaneously + ctx := request.WithNamespace(context.Background(), "default") + for i := 0; i < numGoroutines; i++ { + wg.Add(1) + go func() { + defer wg.Done() + idx := cached.Get(ctx) + require.NotNil(t, idx) + }() + } + wg.Wait() + + // Max concurrent should be 1 since all goroutines are for the same namespace + maxConcurrent := provider.maxConcurrent.Load() + assert.Equal(t, int64(1), maxConcurrent) +} + +// blockingProvider is a test provider that simulates slow fetch operations +// and tracks concurrent executions +type blockingProvider struct { + blockDuration time.Duration + datasources []DataSourceInfo + callCount atomic.Int64 + currentActive atomic.Int64 + maxConcurrent atomic.Int64 +} + +func (p *blockingProvider) get(_ context.Context) any { + p.callCount.Add(1) + + // Track concurrent executions + current := p.currentActive.Add(1) + + // Update max concurrent if this is a new peak + for { + maxVal := p.maxConcurrent.Load() + if current <= maxVal { + break + } + if p.maxConcurrent.CompareAndSwap(maxVal, current) { + break + } + } + + // Simulate slow operation + time.Sleep(p.blockDuration) + + p.currentActive.Add(-1) + return p.datasources +} diff --git a/apps/dashboard/pkg/migration/schemaversion/datasource_utils.go b/apps/dashboard/pkg/migration/schemaversion/datasource_utils.go index 18bc2fc17c4..c7215495dc9 100644 --- a/apps/dashboard/pkg/migration/schemaversion/datasource_utils.go +++ b/apps/dashboard/pkg/migration/schemaversion/datasource_utils.go @@ -2,7 +2,6 @@ package schemaversion import ( "context" - "sync" "time" ) @@ -11,65 +10,41 @@ import ( // string names/UIDs to structured reference objects with uid, type, and apiVersion. // cachedIndexProvider wraps a DataSourceIndexProvider with time-based caching. -// This prevents multiple DB queries and index builds during operations that may call -// provider.Index() multiple times (e.g., dashboard conversions with many datasource lookups). -// The cache expires after 10 seconds, allowing it to be used as a long-lived singleton -// while still refreshing periodically. -// -// Thread-safe: Uses sync.RWMutex to guarantee safe concurrent access. type cachedIndexProvider struct { - provider DataSourceIndexProvider - mu sync.RWMutex - index *DatasourceIndex - cachedAt time.Time - cacheTTL time.Duration + *cachedProvider[*DatasourceIndex] } -// Index returns the cached index if it's still valid (< 10s old), otherwise rebuilds it. -// Uses RWMutex for efficient concurrent reads when cache is valid. +// Index returns the cached index if it's still valid (< TTL old), otherwise rebuilds it. func (p *cachedIndexProvider) Index(ctx context.Context) *DatasourceIndex { - // Fast path: check if cache is still valid using read lock - p.mu.RLock() - if p.index != nil && time.Since(p.cachedAt) < p.cacheTTL { - idx := p.index - p.mu.RUnlock() - return idx - } - p.mu.RUnlock() - - // Slow path: cache expired or not yet built, acquire write lock - p.mu.Lock() - defer p.mu.Unlock() - - // Double-check: another goroutine might have refreshed the cache - // while we were waiting for the write lock - if p.index != nil && time.Since(p.cachedAt) < p.cacheTTL { - return p.index - } - - // Rebuild the cache - p.index = p.provider.Index(ctx) - p.cachedAt = time.Now() - return p.index + return p.Get(ctx) } -// WrapIndexProviderWithCache wraps a provider to cache the index with a 10-second TTL. -// Useful for conversions or migrations that may call provider.Index() multiple times. -// The cache expires after 10 seconds, making it suitable for use as a long-lived singleton -// at the top level of dependency injection while still refreshing periodically. -// -// Example usage in dashboard conversion: -// -// cachedDsIndexProvider := schemaversion.WrapIndexProviderWithCache(dsIndexProvider) -// // Now all calls to cachedDsIndexProvider.Index(ctx) return the same cached index -// // for up to 10 seconds before refreshing -func WrapIndexProviderWithCache(provider DataSourceIndexProvider) DataSourceIndexProvider { - if provider == nil { - return nil +// cachedLibraryElementProvider wraps a LibraryElementIndexProvider with time-based caching. +type cachedLibraryElementProvider struct { + *cachedProvider[[]LibraryElementInfo] +} + +func (p *cachedLibraryElementProvider) GetLibraryElementInfo(ctx context.Context) []LibraryElementInfo { + return p.Get(ctx) +} + +// WrapIndexProviderWithCache wraps a DataSourceIndexProvider to cache indexes with a configurable TTL. +func WrapIndexProviderWithCache(provider DataSourceIndexProvider, cacheTTL time.Duration) DataSourceIndexProvider { + if provider == nil || cacheTTL <= 0 { + return provider } return &cachedIndexProvider{ - provider: provider, - cacheTTL: 10 * time.Second, + newCachedProvider[*DatasourceIndex](provider.Index, defaultCacheSize, cacheTTL), + } +} + +// WrapLibraryElementProviderWithCache wraps a LibraryElementIndexProvider to cache library elements with a configurable TTL. +func WrapLibraryElementProviderWithCache(provider LibraryElementIndexProvider, cacheTTL time.Duration) LibraryElementIndexProvider { + if provider == nil || cacheTTL <= 0 { + return provider + } + return &cachedLibraryElementProvider{ + newCachedProvider[[]LibraryElementInfo](provider.GetLibraryElementInfo, defaultCacheSize, cacheTTL), } } @@ -216,60 +191,3 @@ func MigrateDatasourceNameToRef(nameOrRef interface{}, options map[string]bool, return nil } - -// cachedLibraryElementProvider wraps a LibraryElementIndexProvider with time-based caching. -// This prevents multiple DB queries during operations that may call GetLibraryElementInfo() -// multiple times (e.g., dashboard conversions with many library panel lookups). -// The cache expires after 10 seconds, allowing it to be used as a long-lived singleton -// while still refreshing periodically. -// -// Thread-safe: Uses sync.RWMutex to guarantee safe concurrent access. -type cachedLibraryElementProvider struct { - provider LibraryElementIndexProvider - mu sync.RWMutex - elements []LibraryElementInfo - cachedAt time.Time - cacheTTL time.Duration -} - -// GetLibraryElementInfo returns the cached library elements if they're still valid (< 10s old), otherwise rebuilds the cache. -// Uses RWMutex for efficient concurrent reads when cache is valid. -func (p *cachedLibraryElementProvider) GetLibraryElementInfo(ctx context.Context) []LibraryElementInfo { - // Fast path: check if cache is still valid using read lock - p.mu.RLock() - if p.elements != nil && time.Since(p.cachedAt) < p.cacheTTL { - elements := p.elements - p.mu.RUnlock() - return elements - } - p.mu.RUnlock() - - // Slow path: cache expired or not yet built, acquire write lock - p.mu.Lock() - defer p.mu.Unlock() - - // Double-check: another goroutine might have refreshed the cache - // while we were waiting for the write lock - if p.elements != nil && time.Since(p.cachedAt) < p.cacheTTL { - return p.elements - } - - // Rebuild the cache - p.elements = p.provider.GetLibraryElementInfo(ctx) - p.cachedAt = time.Now() - return p.elements -} - -// WrapLibraryElementProviderWithCache wraps a provider to cache library elements with a 10-second TTL. -// Useful for conversions or migrations that may call GetLibraryElementInfo() multiple times. -// The cache expires after 10 seconds, making it suitable for use as a long-lived singleton -// at the top level of dependency injection while still refreshing periodically. -func WrapLibraryElementProviderWithCache(provider LibraryElementIndexProvider) LibraryElementIndexProvider { - if provider == nil { - return nil - } - return &cachedLibraryElementProvider{ - provider: provider, - cacheTTL: 10 * time.Second, - } -} diff --git a/apps/dashboard/pkg/migration/schemaversion/migration_utils.go b/apps/dashboard/pkg/migration/schemaversion/migration_utils.go index 64dfc61589e..d964fcaf513 100644 --- a/apps/dashboard/pkg/migration/schemaversion/migration_utils.go +++ b/apps/dashboard/pkg/migration/schemaversion/migration_utils.go @@ -102,3 +102,71 @@ func IsArray(value interface{}) bool { _, ok := value.([]interface{}) return ok } + +// AngularPanelMigrations maps deprecated Angular panel types to their modern equivalents. +// Used by both v0→v1 and v1→v2 conversions to ensure consistent migration behavior. +var AngularPanelMigrations = map[string]string{ + "table-old": "table", + "singlestat": "stat", + "grafana-singlestat-panel": "stat", + "grafana-piechart-panel": "piechart", + "grafana-worldmap-panel": "geomap", + "natel-discrete-panel": "state-timeline", +} + +// GetAngularPanelMigration checks if a panel type is an Angular panel and returns the new type to migrate to. +// Returns the new panel type if migration is needed, empty string otherwise. +// This handles both simple mappings and special cases like graph panel. +func GetAngularPanelMigration(panelType string, panel map[string]interface{}) string { + // Handle graph panel specially - it can migrate to different panel types + // based on xaxis.mode + if panelType == "graph" || panelType == "graphite" { + return GetGraphMigrationTarget(panel) + } + + // Check simple Angular panel mappings + if newType, isAngular := AngularPanelMigrations[panelType]; isAngular { + return newType + } + + return "" +} + +// GetGraphMigrationTarget determines the target panel type for graph panel migration. +// Graph panels can migrate to timeseries, barchart, bargauge, or histogram depending on xaxis.mode. +func GetGraphMigrationTarget(panel map[string]interface{}) string { + // Default to timeseries + newType := "timeseries" + + // Check xaxis mode for special cases + if xaxis, ok := panel["xaxis"].(map[string]interface{}); ok { + if mode, ok := xaxis["mode"].(string); ok { + switch mode { + case "series": + // Check legend values for bargauge vs barchart + if legend, ok := panel["legend"].(map[string]interface{}); ok { + if values, ok := legend["values"].(bool); ok && values { + newType = "bargauge" + } else { + newType = "barchart" + } + } else { + newType = "barchart" + } + case "histogram": + newType = "histogram" + } + } + } + + return newType +} + +// IsAngularPanelType checks if a panel type is a known Angular panel type. +func IsAngularPanelType(panelType string) bool { + if panelType == "graph" || panelType == "graphite" { + return true + } + _, isAngular := AngularPanelMigrations[panelType] + return isAngular +} diff --git a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json index 863d7b2a102..a89d8744f39 100644 --- a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json +++ b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_new.v42.json @@ -75,10 +75,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -154,10 +154,10 @@ "effects": { "barGlow": false, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -233,10 +233,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -312,10 +312,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -391,10 +391,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -470,10 +470,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -549,10 +549,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -641,10 +641,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -720,10 +720,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -799,10 +799,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -878,10 +878,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -974,10 +974,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1053,10 +1053,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1132,10 +1132,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1211,10 +1211,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1290,10 +1290,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1386,10 +1386,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1469,10 +1469,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1552,10 +1552,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1603,7 +1603,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1644,11 +1643,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1671,7 +1670,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 98, "min": 5, "noise": 22, @@ -1689,7 +1687,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1730,11 +1727,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1757,7 +1754,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 98, "min": 5, "noise": 22, @@ -1788,7 +1784,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1830,11 +1825,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1857,7 +1852,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 8, "min": 1, "noise": 2, @@ -1875,7 +1869,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1917,12 +1910,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, - "sparkline": false, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -1945,7 +1937,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 12, "min": 1, "noise": 2, @@ -1963,7 +1954,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -2004,11 +1994,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2031,7 +2021,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 100, "min": 10, "noise": 22, @@ -2049,7 +2038,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -2090,11 +2078,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": [ @@ -2117,7 +2105,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 100, "min": 10, "noise": 22, @@ -2130,6 +2117,151 @@ ], "title": "Backend", "type": "radialbar" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 66 + }, + "id": 35, + "panels": [], + "title": "Empty data", + "type": "row" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 6, + "x": 0, + "y": 67 + }, + "id": 36, + "options": { + "barWidthFactor": 0.5, + "effects": { + "barGlow": false, + "centerGlow": false, + "gradient": true, + "rounded": false, + "spotlight": false + }, + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "segmentCount": 1, + "segmentSpacing": 0.3, + "shape": "gauge", + "showThresholdLabels": false, + "showThresholdMarkers": true, + "sparkline": true + }, + "pluginVersion": "13.0.0-pre", + "targets": [ + { + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 0 + } + ], + "title": "Numeric, no series", + "type": "gauge" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 6, + "x": 6, + "y": 67 + }, + "id": 37, + "options": { + "barWidthFactor": 0.5, + "effects": { + "barGlow": false, + "centerGlow": false, + "gradient": true, + "rounded": false, + "spotlight": false + }, + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "segmentCount": 1, + "segmentSpacing": 0.3, + "shape": "gauge", + "showThresholdLabels": false, + "showThresholdMarkers": true, + "sparkline": true + }, + "pluginVersion": "13.0.0-pre", + "targets": [ + { + "refId": "A", + "scenarioId": "logs" + } + ], + "title": "Non-numeric", + "type": "gauge" } ], "preload": false, diff --git a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json index d4dd7980100..4a5ac97a6b5 100644 --- a/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json +++ b/apps/dashboard/pkg/migration/testdata/dev-dashboards-output/panel-gauge/gauge_tests_old_to_new.v42.json @@ -955,10 +955,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": [ diff --git a/apps/iam/go.mod b/apps/iam/go.mod index 474779e0efe..c741eb97423 100644 --- a/apps/iam/go.mod +++ b/apps/iam/go.mod @@ -221,7 +221,7 @@ require ( github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/gorilla/mux v1.8.1 // indirect - github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba // indirect + github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 // indirect github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f // indirect github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 // indirect github.com/grafana/dataplane/sdata v0.0.9 // indirect diff --git a/apps/iam/go.sum b/apps/iam/go.sum index 0b22bce3774..4c8ec5e38b5 100644 --- a/apps/iam/go.sum +++ b/apps/iam/go.sum @@ -150,6 +150,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= +github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= github.com/FZambia/eagle v0.2.0 h1:1kQaZpJvbkvAXFRE/9K2ucBMuVqo+E29EMLYB74hIis= github.com/FZambia/eagle v0.2.0/go.mod h1:LKMYBwGYhao5sJI0TppvQ4SvvldFj9gITxrl8NvGwG0= @@ -377,10 +379,10 @@ github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyY github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/centrifugal/centrifuge v0.37.2 h1:rerQNvDfYN2FZEkVtb/hvGV7SIrJfEQrKF3MaE8GDlo= -github.com/centrifugal/centrifuge v0.37.2/go.mod h1:aj4iRJGhzi3SlL8iUtVezxway1Xf8g+hmNQkLLO7sS8= -github.com/centrifugal/protocol v0.16.2 h1:KoIHgDeX1fFxyxQoKW+6E8ZTCf5mwGm8JyGoJ5NBMbQ= -github.com/centrifugal/protocol v0.16.2/go.mod h1:Q7OpS/8HMXDnL7f9DpNx24IhG96MP88WPpVTTCdrokI= +github.com/centrifugal/centrifuge v0.38.0 h1:UJTowwc5lSwnpvd3vbrTseODbU7osSggN67RTrJ8EfQ= +github.com/centrifugal/centrifuge v0.38.0/go.mod h1:rcZLARnO5GXOeE9qG7iIPMvERxESespqkSX4cGLCAzo= +github.com/centrifugal/protocol v0.17.0 h1:hD0WczyiG7zrVJcgkQsd5/nhfFXt0Y04SJHV2Z7B1rg= +github.com/centrifugal/protocol v0.17.0/go.mod h1:9MdiYyjw5Bw1+d5Sp4Y0NK+qiuTNyd88nrHJsUUh8k4= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -817,8 +819,8 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba h1:psKWNETD5nGxmFAlqnWsXoRyUwSa2GHNEMSEDKGKfQ4= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 h1:ZzG/gCclEit9w0QUfQt9GURcOycAIGcsQAhY1u0AEX0= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f h1:Cbm6OKkOcJ+7CSZsGsEJzktC/SIa5bxVeYKQLuYK86o= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f/go.mod h1:axY0cdOg3q0TZHwpHnIz5x16xZ8ZBxJHShsSHHXcHQg= github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 h1:Muoy+FMGrHj3GdFbvsMzUT7eusgii9PKf9L1ZaXDDbY= @@ -1376,11 +1378,13 @@ github.com/puzpuzpuz/xsync/v2 v2.5.1 h1:mVGYAvzDSu52+zaGyNjC+24Xw2bQi3kTr4QJ6N9p github.com/puzpuzpuz/xsync/v2 v2.5.1/go.mod h1:gD2H2krq/w52MfPLE+Uy64TzJDVY7lP2znR9qmR35kU= github.com/puzpuzpuz/xsync/v4 v4.2.0 h1:dlxm77dZj2c3rxq0/XNvvUKISAmovoXF4a4qM6Wvkr0= github.com/puzpuzpuz/xsync/v4 v4.2.0/go.mod h1:VJDmTCJMBt8igNxnkQd86r+8KUeN1quSfNKu5bLYFQo= +github.com/quagmt/udecimal v1.9.0 h1:TLuZiFeg0HhS6X8VDa78Y6XTaitZZfh+z5q4SXMzpDQ= +github.com/quagmt/udecimal v1.9.0/go.mod h1:ScmJ/xTGZcEoYiyMMzgDLn79PEJHcMBiJ4NNRT3FirA= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/redis/go-redis/v9 v9.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE= github.com/redis/go-redis/v9 v9.14.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= -github.com/redis/rueidis v1.0.64 h1:XqgbueDuNV3qFdVdQwAHJl1uNt90zUuAJuzqjH4cw6Y= -github.com/redis/rueidis v1.0.64/go.mod h1:Lkhr2QTgcoYBhxARU7kJRO8SyVlgUuEkcJO1Y8MCluA= +github.com/redis/rueidis v1.0.68 h1:gept0E45JGxVigWb3zoWHvxEc4IOC7kc4V/4XvN8eG8= +github.com/redis/rueidis v1.0.68/go.mod h1:Lkhr2QTgcoYBhxARU7kJRO8SyVlgUuEkcJO1Y8MCluA= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= diff --git a/apps/iam/kinds/manifest.cue b/apps/iam/kinds/manifest.cue index c6f609cbe15..91f746c6a32 100644 --- a/apps/iam/kinds/manifest.cue +++ b/apps/iam/kinds/manifest.cue @@ -22,13 +22,40 @@ v0alpha1: { serviceaccountv0alpha1, externalGroupMappingv0alpha1 ] + routes: { namespaced: { + "/searchUsers": { + "GET": { + request: { + query: { + query?: string + limit?: int64 | 10 + offset?: int64 | 0 + page?: int64 | 1 + } + } + response: { + offset: int64 + totalHits: int64 + hits: [...#UserHit] + queryCost: float64 + maxScore: float64 + } + responseMetadata: { + typeMeta: false + objectMeta: false + } + } + } "/searchTeams": { "GET": { request: { query: { query?: string + limit?: int64 | 50 + offset?: int64 | 0 + page?: int64 | 1 } } response: { @@ -51,3 +78,15 @@ v0alpha1: { } } } + +#UserHit: { + name: string + title: string + login: string + email: string + role: string + lastSeenAt: int64 + lastSeenAtAge: string + provisioned: bool + score: float64 +} diff --git a/apps/iam/kinds/user.cue b/apps/iam/kinds/user.cue index a67c0949e1f..fc5bb8fb153 100644 --- a/apps/iam/kinds/user.cue +++ b/apps/iam/kinds/user.cue @@ -29,6 +29,9 @@ userv0alpha1: userKind & { // } schema: { spec: v0alpha1.UserSpec + status: { + lastSeenAt: int64 | 0 + } } // TODO: Uncomment when the custom routes implementation is done // routes: { diff --git a/apps/iam/pkg/apis/iam/v0alpha1/corerole_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/corerole_object_gen.go index 625cced10b9..9a99aadddee 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/corerole_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/corerole_object_gen.go @@ -23,6 +23,12 @@ type CoreRole struct { Spec CoreRoleSpec `json:"spec" yaml:"spec"` } +func NewCoreRole() *CoreRole { + return &CoreRole{ + Spec: *NewCoreRoleSpec(), + } +} + func (o *CoreRole) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/corerole_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/corerole_schema_gen.go index 637f78355f8..82c0a8102e0 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/corerole_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/corerole_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaCoreRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &CoreRole{}, &CoreRoleList{}, resource.WithKind("CoreRole"), + schemaCoreRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewCoreRole(), &CoreRoleList{}, resource.WithKind("CoreRole"), resource.WithPlural("coreroles"), resource.WithScope(resource.NamespacedScope)) kindCoreRole = resource.Kind{ Schema: schemaCoreRole, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_object_gen.go index db20616c355..bbc7c2f65c4 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_object_gen.go @@ -23,6 +23,12 @@ type ExternalGroupMapping struct { Spec ExternalGroupMappingSpec `json:"spec" yaml:"spec"` } +func NewExternalGroupMapping() *ExternalGroupMapping { + return &ExternalGroupMapping{ + Spec: *NewExternalGroupMappingSpec(), + } +} + func (o *ExternalGroupMapping) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_schema_gen.go index 91090a9b460..943c41d8e3e 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/externalgroupmapping_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaExternalGroupMapping = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &ExternalGroupMapping{}, &ExternalGroupMappingList{}, resource.WithKind("ExternalGroupMapping"), + schemaExternalGroupMapping = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewExternalGroupMapping(), &ExternalGroupMappingList{}, resource.WithKind("ExternalGroupMapping"), resource.WithPlural("externalgroupmappings"), resource.WithScope(resource.NamespacedScope)) kindExternalGroupMapping = resource.Kind{ Schema: schemaExternalGroupMapping, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/getsearchteams_request_params_types_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/getsearchteams_request_params_types_gen.go index ffa5067c41b..d06550cb417 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/getsearchteams_request_params_types_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/getsearchteams_request_params_types_gen.go @@ -3,7 +3,10 @@ package v0alpha1 type GetSearchTeamsRequestParams struct { - Query *string `json:"query,omitempty"` + Query *string `json:"query,omitempty"` + Limit int64 `json:"limit,omitempty"` + Offset int64 `json:"offset,omitempty"` + Page int64 `json:"page,omitempty"` } // NewGetSearchTeamsRequestParams creates a new GetSearchTeamsRequestParams object. diff --git a/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_object_gen.go new file mode 100644 index 00000000000..3a6c04a1fa0 --- /dev/null +++ b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_object_gen.go @@ -0,0 +1,33 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v0alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +type GetSearchUsersRequestParamsObject struct { + metav1.TypeMeta `json:",inline"` + GetSearchUsersRequestParams `json:",inline"` +} + +func NewGetSearchUsersRequestParamsObject() *GetSearchUsersRequestParamsObject { + return &GetSearchUsersRequestParamsObject{} +} + +func (o *GetSearchUsersRequestParamsObject) DeepCopyObject() runtime.Object { + dst := NewGetSearchUsersRequestParamsObject() + o.DeepCopyInto(dst) + return dst +} + +func (o *GetSearchUsersRequestParamsObject) DeepCopyInto(dst *GetSearchUsersRequestParamsObject) { + dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion + dst.TypeMeta.Kind = o.TypeMeta.Kind + dstGetSearchUsersRequestParams := GetSearchUsersRequestParams{} + _ = resource.CopyObjectInto(&dstGetSearchUsersRequestParams, &o.GetSearchUsersRequestParams) +} + +var _ runtime.Object = NewGetSearchUsersRequestParamsObject() diff --git a/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_types_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_types_gen.go new file mode 100644 index 00000000000..22b73ea80d8 --- /dev/null +++ b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_request_params_types_gen.go @@ -0,0 +1,15 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v0alpha1 + +type GetSearchUsersRequestParams struct { + Query *string `json:"query,omitempty"` + Limit int64 `json:"limit,omitempty"` + Offset int64 `json:"offset,omitempty"` + Page int64 `json:"page,omitempty"` +} + +// NewGetSearchUsersRequestParams creates a new GetSearchUsersRequestParams object. +func NewGetSearchUsersRequestParams() *GetSearchUsersRequestParams { + return &GetSearchUsersRequestParams{} +} diff --git a/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_response_types_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_response_types_gen.go new file mode 100644 index 00000000000..d56cbfa3a3c --- /dev/null +++ b/apps/iam/pkg/apis/iam/v0alpha1/getsearchusers_response_types_gen.go @@ -0,0 +1,37 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v0alpha1 + +// +k8s:openapi-gen=true +type UserHit struct { + Name string `json:"name"` + Title string `json:"title"` + Login string `json:"login"` + Email string `json:"email"` + Role string `json:"role"` + LastSeenAt int64 `json:"lastSeenAt"` + LastSeenAtAge string `json:"lastSeenAtAge"` + Provisioned bool `json:"provisioned"` + Score float64 `json:"score"` +} + +// NewUserHit creates a new UserHit object. +func NewUserHit() *UserHit { + return &UserHit{} +} + +// +k8s:openapi-gen=true +type GetSearchUsers struct { + Offset int64 `json:"offset"` + TotalHits int64 `json:"totalHits"` + Hits []UserHit `json:"hits"` + QueryCost float64 `json:"queryCost"` + MaxScore float64 `json:"maxScore"` +} + +// NewGetSearchUsers creates a new GetSearchUsers object. +func NewGetSearchUsers() *GetSearchUsers { + return &GetSearchUsers{ + Hits: []UserHit{}, + } +} diff --git a/apps/iam/pkg/apis/iam/v0alpha1/globalrole_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/globalrole_object_gen.go index 27165fe70bd..66ad21c83cf 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/globalrole_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/globalrole_object_gen.go @@ -23,6 +23,12 @@ type GlobalRole struct { Spec GlobalRoleSpec `json:"spec" yaml:"spec"` } +func NewGlobalRole() *GlobalRole { + return &GlobalRole{ + Spec: *NewGlobalRoleSpec(), + } +} + func (o *GlobalRole) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/globalrole_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/globalrole_schema_gen.go index ce3322f97c0..be220cb0e95 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/globalrole_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/globalrole_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaGlobalRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &GlobalRole{}, &GlobalRoleList{}, resource.WithKind("GlobalRole"), + schemaGlobalRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewGlobalRole(), &GlobalRoleList{}, resource.WithKind("GlobalRole"), resource.WithPlural("globalroles"), resource.WithScope(resource.NamespacedScope)) kindGlobalRole = resource.Kind{ Schema: schemaGlobalRole, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_object_gen.go index 3bd4609d25d..bb8b0644f62 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_object_gen.go @@ -23,6 +23,12 @@ type GlobalRoleBinding struct { Spec GlobalRoleBindingSpec `json:"spec" yaml:"spec"` } +func NewGlobalRoleBinding() *GlobalRoleBinding { + return &GlobalRoleBinding{ + Spec: *NewGlobalRoleBindingSpec(), + } +} + func (o *GlobalRoleBinding) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_schema_gen.go index 9b4e65aa5e6..2e39da946f9 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/globalrolebinding_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaGlobalRoleBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &GlobalRoleBinding{}, &GlobalRoleBindingList{}, resource.WithKind("GlobalRoleBinding"), + schemaGlobalRoleBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewGlobalRoleBinding(), &GlobalRoleBindingList{}, resource.WithKind("GlobalRoleBinding"), resource.WithPlural("globalrolebindings"), resource.WithScope(resource.NamespacedScope)) kindGlobalRoleBinding = resource.Kind{ Schema: schemaGlobalRoleBinding, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_object_gen.go index 996beb7e002..8cc4c28c209 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_object_gen.go @@ -23,6 +23,12 @@ type ResourcePermission struct { Spec ResourcePermissionSpec `json:"spec" yaml:"spec"` } +func NewResourcePermission() *ResourcePermission { + return &ResourcePermission{ + Spec: *NewResourcePermissionSpec(), + } +} + func (o *ResourcePermission) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_schema_gen.go index 257255a58fe..aa709f0d42a 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/resourcepermission_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaResourcePermission = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &ResourcePermission{}, &ResourcePermissionList{}, resource.WithKind("ResourcePermission"), + schemaResourcePermission = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewResourcePermission(), &ResourcePermissionList{}, resource.WithKind("ResourcePermission"), resource.WithPlural("resourcepermissions"), resource.WithScope(resource.NamespacedScope)) kindResourcePermission = resource.Kind{ Schema: schemaResourcePermission, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/role_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/role_object_gen.go index 20bb587157e..0673c1a17c5 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/role_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/role_object_gen.go @@ -23,6 +23,12 @@ type Role struct { Spec RoleSpec `json:"spec" yaml:"spec"` } +func NewRole() *Role { + return &Role{ + Spec: *NewRoleSpec(), + } +} + func (o *Role) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/role_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/role_schema_gen.go index 74cc8730026..3aacfa2e060 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/role_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/role_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &Role{}, &RoleList{}, resource.WithKind("Role"), + schemaRole = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewRole(), &RoleList{}, resource.WithKind("Role"), resource.WithPlural("roles"), resource.WithScope(resource.NamespacedScope)) kindRole = resource.Kind{ Schema: schemaRole, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_object_gen.go index dfd7741e05a..996fdc3df65 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_object_gen.go @@ -23,6 +23,12 @@ type RoleBinding struct { Spec RoleBindingSpec `json:"spec" yaml:"spec"` } +func NewRoleBinding() *RoleBinding { + return &RoleBinding{ + Spec: *NewRoleBindingSpec(), + } +} + func (o *RoleBinding) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_schema_gen.go index abb2b3eddf9..0cf1d4dee8b 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/rolebinding_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaRoleBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &RoleBinding{}, &RoleBindingList{}, resource.WithKind("RoleBinding"), + schemaRoleBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewRoleBinding(), &RoleBindingList{}, resource.WithKind("RoleBinding"), resource.WithPlural("rolebindings"), resource.WithScope(resource.NamespacedScope)) kindRoleBinding = resource.Kind{ Schema: schemaRoleBinding, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_object_gen.go index fe3cd7f3609..e2cfc9f33a7 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_object_gen.go @@ -23,6 +23,12 @@ type ServiceAccount struct { Spec ServiceAccountSpec `json:"spec" yaml:"spec"` } +func NewServiceAccount() *ServiceAccount { + return &ServiceAccount{ + Spec: *NewServiceAccountSpec(), + } +} + func (o *ServiceAccount) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_schema_gen.go index ea48c864739..71b171e0756 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/serviceaccount_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaServiceAccount = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &ServiceAccount{}, &ServiceAccountList{}, resource.WithKind("ServiceAccount"), + schemaServiceAccount = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewServiceAccount(), &ServiceAccountList{}, resource.WithKind("ServiceAccount"), resource.WithPlural("serviceaccounts"), resource.WithScope(resource.NamespacedScope)) kindServiceAccount = resource.Kind{ Schema: schemaServiceAccount, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/team_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/team_object_gen.go index 4030bebb9d1..85b57abf9d5 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/team_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/team_object_gen.go @@ -23,6 +23,12 @@ type Team struct { Spec TeamSpec `json:"spec" yaml:"spec"` } +func NewTeam() *Team { + return &Team{ + Spec: *NewTeamSpec(), + } +} + func (o *Team) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/team_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/team_schema_gen.go index 7a4875cf2d5..299d846d10e 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/team_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/team_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaTeam = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &Team{}, &TeamList{}, resource.WithKind("Team"), + schemaTeam = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewTeam(), &TeamList{}, resource.WithKind("Team"), resource.WithPlural("teams"), resource.WithScope(resource.NamespacedScope)) kindTeam = resource.Kind{ Schema: schemaTeam, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/teambinding_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/teambinding_object_gen.go index a958c55f5e7..0d388192448 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/teambinding_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/teambinding_object_gen.go @@ -23,6 +23,12 @@ type TeamBinding struct { Spec TeamBindingSpec `json:"spec" yaml:"spec"` } +func NewTeamBinding() *TeamBinding { + return &TeamBinding{ + Spec: *NewTeamBindingSpec(), + } +} + func (o *TeamBinding) GetSpec() any { return o.Spec } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/teambinding_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/teambinding_schema_gen.go index e3c2c11a8b5..d089b966e9b 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/teambinding_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/teambinding_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaTeamBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &TeamBinding{}, &TeamBindingList{}, resource.WithKind("TeamBinding"), + schemaTeamBinding = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewTeamBinding(), &TeamBindingList{}, resource.WithKind("TeamBinding"), resource.WithPlural("teambindings"), resource.WithScope(resource.NamespacedScope)) kindTeamBinding = resource.Kind{ Schema: schemaTeamBinding, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/user_client_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/user_client_gen.go index 665df84327e..bd7af9b3361 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/user_client_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/user_client_gen.go @@ -4,6 +4,7 @@ import ( "context" "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type UserClient struct { @@ -75,6 +76,24 @@ func (c *UserClient) Patch(ctx context.Context, identifier resource.Identifier, return c.client.Patch(ctx, identifier, req, opts) } +func (c *UserClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus UserStatus, opts resource.UpdateOptions) (*User, error) { + return c.client.Update(ctx, &User{ + TypeMeta: metav1.TypeMeta{ + Kind: UserKind().Kind(), + APIVersion: GroupVersion.Identifier(), + }, + ObjectMeta: metav1.ObjectMeta{ + ResourceVersion: opts.ResourceVersion, + Namespace: identifier.Namespace, + Name: identifier.Name, + }, + Status: newStatus, + }, resource.UpdateOptions{ + Subresource: "status", + ResourceVersion: opts.ResourceVersion, + }) +} + func (c *UserClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { return c.client.Delete(ctx, identifier, opts) } diff --git a/apps/iam/pkg/apis/iam/v0alpha1/user_object_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/user_object_gen.go index 373112a1d87..f4bc19dccbb 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/user_object_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/user_object_gen.go @@ -21,6 +21,15 @@ type User struct { // Spec is the spec of the User Spec UserSpec `json:"spec" yaml:"spec"` + + Status UserStatus `json:"status" yaml:"status"` +} + +func NewUser() *User { + return &User{ + Spec: *NewUserSpec(), + Status: *NewUserStatus(), + } } func (o *User) GetSpec() any { @@ -37,11 +46,15 @@ func (o *User) SetSpec(spec any) error { } func (o *User) GetSubresources() map[string]any { - return map[string]any{} + return map[string]any{ + "status": o.Status, + } } func (o *User) GetSubresource(name string) (any, bool) { switch name { + case "status": + return o.Status, true default: return nil, false } @@ -49,6 +62,13 @@ func (o *User) GetSubresource(name string) (any, bool) { func (o *User) SetSubresource(name string, value any) error { switch name { + case "status": + cast, ok := value.(UserStatus) + if !ok { + return fmt.Errorf("cannot set status type %#v, not of type UserStatus", value) + } + o.Status = cast + return nil default: return fmt.Errorf("subresource '%s' does not exist", name) } @@ -220,6 +240,7 @@ func (o *User) DeepCopyInto(dst *User) { dst.TypeMeta.Kind = o.TypeMeta.Kind o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) o.Spec.DeepCopyInto(&dst.Spec) + o.Status.DeepCopyInto(&dst.Status) } // Interface compliance compile-time check @@ -291,3 +312,15 @@ func (s *UserSpec) DeepCopy() *UserSpec { func (s *UserSpec) DeepCopyInto(dst *UserSpec) { resource.CopyObjectInto(dst, s) } + +// DeepCopy creates a full deep copy of UserStatus +func (s *UserStatus) DeepCopy() *UserStatus { + cpy := &UserStatus{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies UserStatus into another UserStatus object +func (s *UserStatus) DeepCopyInto(dst *UserStatus) { + resource.CopyObjectInto(dst, s) +} diff --git a/apps/iam/pkg/apis/iam/v0alpha1/user_schema_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/user_schema_gen.go index a44d9dfcf2d..ba48b19c015 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/user_schema_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/user_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaUser = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", &User{}, &UserList{}, resource.WithKind("User"), + schemaUser = resource.NewSimpleSchema("iam.grafana.app", "v0alpha1", NewUser(), &UserList{}, resource.WithKind("User"), resource.WithPlural("users"), resource.WithScope(resource.NamespacedScope)) kindUser = resource.Kind{ Schema: schemaUser, diff --git a/apps/iam/pkg/apis/iam/v0alpha1/user_status_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/user_status_gen.go index 34a138f59ce..dd0f3e46767 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/user_status_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/user_status_gen.go @@ -2,43 +2,12 @@ package v0alpha1 -// +k8s:openapi-gen=true -type UserstatusOperatorState struct { - // lastEvaluation is the ResourceVersion last evaluated - LastEvaluation string `json:"lastEvaluation"` - // state describes the state of the lastEvaluation. - // It is limited to three possible states for machine evaluation. - State UserStatusOperatorStateState `json:"state"` - // descriptiveState is an optional more descriptive state field which has no requirements on format - DescriptiveState *string `json:"descriptiveState,omitempty"` - // details contains any extra information that is operator-specific - Details map[string]interface{} `json:"details,omitempty"` -} - -// NewUserstatusOperatorState creates a new UserstatusOperatorState object. -func NewUserstatusOperatorState() *UserstatusOperatorState { - return &UserstatusOperatorState{} -} - // +k8s:openapi-gen=true type UserStatus struct { - // operatorStates is a map of operator ID to operator state evaluations. - // Any operator which consumes this kind SHOULD add its state evaluation information to this field. - OperatorStates map[string]UserstatusOperatorState `json:"operatorStates,omitempty"` - // additionalFields is reserved for future use - AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` + LastSeenAt int64 `json:"lastSeenAt"` } // NewUserStatus creates a new UserStatus object. func NewUserStatus() *UserStatus { return &UserStatus{} } - -// +k8s:openapi-gen=true -type UserStatusOperatorStateState string - -const ( - UserStatusOperatorStateStateSuccess UserStatusOperatorStateState = "success" - UserStatusOperatorStateStateInProgress UserStatusOperatorStateState = "in_progress" - UserStatusOperatorStateStateFailed UserStatusOperatorStateState = "failed" -) diff --git a/apps/iam/pkg/apis/iam/v0alpha1/zz_openapi_gen.go b/apps/iam/pkg/apis/iam/v0alpha1/zz_openapi_gen.go index a41d51e8d70..87128d27699 100644 --- a/apps/iam/pkg/apis/iam/v0alpha1/zz_openapi_gen.go +++ b/apps/iam/pkg/apis/iam/v0alpha1/zz_openapi_gen.go @@ -1,8 +1,3 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -// Code generated by grafana-app-sdk. DO NOT EDIT. - package v0alpha1 import ( @@ -26,6 +21,7 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetGroupsBody": schema_pkg_apis_iam_v0alpha1_GetGroupsBody(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetSearchTeams": schema_pkg_apis_iam_v0alpha1_GetSearchTeams(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetSearchTeamsBody": schema_pkg_apis_iam_v0alpha1_GetSearchTeamsBody(ref), + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetSearchUsers": schema_pkg_apis_iam_v0alpha1_GetSearchUsers(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GlobalRole": schema_pkg_apis_iam_v0alpha1_GlobalRole(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GlobalRoleBinding": schema_pkg_apis_iam_v0alpha1_GlobalRoleBinding(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GlobalRoleBindingList": schema_pkg_apis_iam_v0alpha1_GlobalRoleBindingList(ref), @@ -77,10 +73,10 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.TeamStatus": schema_pkg_apis_iam_v0alpha1_TeamStatus(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.TeamstatusOperatorState": schema_pkg_apis_iam_v0alpha1_TeamstatusOperatorState(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.User": schema_pkg_apis_iam_v0alpha1_User(ref), + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserHit": schema_pkg_apis_iam_v0alpha1_UserHit(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserList": schema_pkg_apis_iam_v0alpha1_UserList(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserSpec": schema_pkg_apis_iam_v0alpha1_UserSpec(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserStatus": schema_pkg_apis_iam_v0alpha1_UserStatus(ref), - "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserstatusOperatorState": schema_pkg_apis_iam_v0alpha1_UserstatusOperatorState(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.VersionsV0alpha1Kinds7RoutesGroupsGETResponseExternalGroupMapping": schema_pkg_apis_iam_v0alpha1_VersionsV0alpha1Kinds7RoutesGroupsGETResponseExternalGroupMapping(ref), "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.VersionsV0alpha1RoutesNamespacedSearchTeamsGETResponseTeamHit": schema_pkg_apis_iam_v0alpha1_VersionsV0alpha1RoutesNamespacedSearchTeamsGETResponseTeamHit(ref), } @@ -693,6 +689,62 @@ func schema_pkg_apis_iam_v0alpha1_GetSearchTeamsBody(ref common.ReferenceCallbac } } +func schema_pkg_apis_iam_v0alpha1_GetSearchUsers(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "offset": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"integer"}, + Format: "int64", + }, + }, + "totalHits": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"integer"}, + Format: "int64", + }, + }, + "hits": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserHit"), + }, + }, + }, + }, + }, + "queryCost": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"number"}, + Format: "double", + }, + }, + "maxScore": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"number"}, + Format: "double", + }, + }, + }, + Required: []string{"offset", "totalHits", "hits", "queryCost", "maxScore"}, + }, + }, + Dependencies: []string{ + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserHit"}, + } +} + func schema_pkg_apis_iam_v0alpha1_GlobalRole(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -2838,12 +2890,94 @@ func schema_pkg_apis_iam_v0alpha1_User(ref common.ReferenceCallback) common.Open Ref: ref("github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserSpec"), }, }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserStatus"), + }, + }, }, - Required: []string{"metadata", "spec"}, + Required: []string{"metadata", "spec", "status"}, }, }, Dependencies: []string{ - "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserSpec", "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_pkg_apis_iam_v0alpha1_UserHit(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "title": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "login": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "email": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "role": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "lastSeenAt": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"integer"}, + Format: "int64", + }, + }, + "lastSeenAtAge": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "provisioned": { + SchemaProps: spec.SchemaProps{ + Default: false, + Type: []string{"boolean"}, + Format: "", + }, + }, + "score": { + SchemaProps: spec.SchemaProps{ + Default: 0, + Type: []string{"number"}, + Format: "double", + }, + }, + }, + Required: []string{"name", "title", "login", "email", "role", "lastSeenAt", "lastSeenAtAge", "provisioned", "score"}, + }, + }, } } @@ -2970,90 +3104,15 @@ func schema_pkg_apis_iam_v0alpha1_UserStatus(ref common.ReferenceCallback) commo SchemaProps: spec.SchemaProps{ Type: []string{"object"}, Properties: map[string]spec.Schema{ - "operatorStates": { + "lastSeenAt": { SchemaProps: spec.SchemaProps{ - Description: "operatorStates is a map of operator ID to operator state evaluations. Any operator which consumes this kind SHOULD add its state evaluation information to this field.", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Default: map[string]interface{}{}, - Ref: ref("github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserstatusOperatorState"), - }, - }, - }, - }, - }, - "additionalFields": { - SchemaProps: spec.SchemaProps{ - Description: "additionalFields is reserved for future use", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Format: "", - }, - }, - }, + Default: 0, + Type: []string{"integer"}, + Format: "int64", }, }, }, - }, - }, - Dependencies: []string{ - "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserstatusOperatorState"}, - } -} - -func schema_pkg_apis_iam_v0alpha1_UserstatusOperatorState(ref common.ReferenceCallback) common.OpenAPIDefinition { - return common.OpenAPIDefinition{ - Schema: spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Properties: map[string]spec.Schema{ - "lastEvaluation": { - SchemaProps: spec.SchemaProps{ - Description: "lastEvaluation is the ResourceVersion last evaluated", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "state": { - SchemaProps: spec.SchemaProps{ - Description: "state describes the state of the lastEvaluation. It is limited to three possible states for machine evaluation.", - Default: "", - Type: []string{"string"}, - Format: "", - }, - }, - "descriptiveState": { - SchemaProps: spec.SchemaProps{ - Description: "descriptiveState is an optional more descriptive state field which has no requirements on format", - Type: []string{"string"}, - Format: "", - }, - }, - "details": { - SchemaProps: spec.SchemaProps{ - Description: "details contains any extra information that is operator-specific", - Type: []string{"object"}, - AdditionalProperties: &spec.SchemaOrBool{ - Allows: true, - Schema: &spec.Schema{ - SchemaProps: spec.SchemaProps{ - Type: []string{"object"}, - Format: "", - }, - }, - }, - }, - }, - }, - Required: []string{"lastEvaluation", "state"}, + Required: []string{"lastSeenAt"}, }, }, } diff --git a/apps/iam/pkg/apis/iam_manifest.go b/apps/iam/pkg/apis/iam_manifest.go index 5c27c228ed2..664c12226de 100644 --- a/apps/iam/pkg/apis/iam_manifest.go +++ b/apps/iam/pkg/apis/iam_manifest.go @@ -109,6 +109,13 @@ var appManifestData = app.ManifestData{ "items": { SchemaProps: spec.SchemaProps{ Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + + Ref: spec.MustCreateRef("#/components/schemas/getGroupsExternalGroupMapping"), + }}, + }, }, }, "kind": { @@ -166,6 +173,36 @@ var appManifestData = app.ManifestData{ Parameters: []*spec3.Parameter{ + { + ParameterProps: spec3.ParameterProps{ + Name: "limit", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + + { + ParameterProps: spec3.ParameterProps{ + Name: "offset", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + + { + ParameterProps: spec3.ParameterProps{ + Name: "page", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + { ParameterProps: spec3.ParameterProps{ Name: "query", @@ -200,6 +237,13 @@ var appManifestData = app.ManifestData{ "hits": { SchemaProps: spec.SchemaProps{ Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + + Ref: spec.MustCreateRef("#/components/schemas/getSearchTeamsTeamHit"), + }}, + }, }, }, "kind": { @@ -247,6 +291,118 @@ var appManifestData = app.ManifestData{ }, }, }, + "/searchUsers": { + Get: &spec3.Operation{ + OperationProps: spec3.OperationProps{ + + OperationId: "getSearchUsers", + + Parameters: []*spec3.Parameter{ + + { + ParameterProps: spec3.ParameterProps{ + Name: "limit", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + + { + ParameterProps: spec3.ParameterProps{ + Name: "offset", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + + { + ParameterProps: spec3.ParameterProps{ + Name: "page", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{}, + }, + }, + }, + + { + ParameterProps: spec3.ParameterProps{ + Name: "query", + In: "query", + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + }, + }, + }, + + Responses: &spec3.Responses{ + ResponsesProps: spec3.ResponsesProps{ + Default: &spec3.Response{ + ResponseProps: spec3.ResponseProps{ + Description: "Default OK response", + Content: map[string]*spec3.MediaType{ + "application/json": { + MediaTypeProps: spec3.MediaTypeProps{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "hits": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + + Ref: spec.MustCreateRef("#/components/schemas/getSearchUsersUserHit"), + }}, + }, + }, + }, + "maxScore": { + SchemaProps: spec.SchemaProps{ + Type: []string{"number"}, + }, + }, + "offset": { + SchemaProps: spec.SchemaProps{ + Type: []string{"integer"}, + }, + }, + "queryCost": { + SchemaProps: spec.SchemaProps{ + Type: []string{"number"}, + }, + }, + "totalHits": { + SchemaProps: spec.SchemaProps{ + Type: []string{"integer"}, + }, + }, + }, + Required: []string{ + "offset", + "totalHits", + "hits", + "queryCost", + "maxScore", + }, + }}, + }}, + }, + }, + }, + }}, + }, + }, + }, }, Cluster: map[string]spec3.PathProps{}, Schemas: map[string]spec.Schema{ @@ -289,6 +445,69 @@ var appManifestData = app.ManifestData{ }, }, }, + "getSearchUsersUserHit": { + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "email": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + "lastSeenAt": { + SchemaProps: spec.SchemaProps{ + Type: []string{"integer"}, + }, + }, + "lastSeenAtAge": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + "login": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + "provisioned": { + SchemaProps: spec.SchemaProps{ + Type: []string{"boolean"}, + }, + }, + "role": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + "score": { + SchemaProps: spec.SchemaProps{ + Type: []string{"number"}, + }, + }, + "title": { + SchemaProps: spec.SchemaProps{ + Type: []string{"string"}, + }, + }, + }, + Required: []string{ + "name", + "title", + "login", + "email", + "role", + "lastSeenAt", + "lastSeenAtAge", + "provisioned", + "score", + }, + }, + }, }, }, }, @@ -328,6 +547,7 @@ var customRouteToGoResponseType = map[string]any{ "v0alpha1|Team|groups|GET": v0alpha1.GetGroups{}, "v0alpha1||/searchTeams|GET": v0alpha1.GetSearchTeams{}, + "v0alpha1||/searchUsers|GET": v0alpha1.GetSearchUsers{}, } // ManifestCustomRouteResponsesAssociator returns the associated response go type for a given kind, version, custom route path, and method, if one exists. diff --git a/apps/iam/pkg/app/app.go b/apps/iam/pkg/app/app.go index 05216220d7e..ff2a0cc7feb 100644 --- a/apps/iam/pkg/app/app.go +++ b/apps/iam/pkg/app/app.go @@ -4,6 +4,8 @@ import ( "context" "fmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/grafana/grafana-app-sdk/app" "github.com/grafana/grafana-app-sdk/logging" "github.com/grafana/grafana-app-sdk/operator" @@ -12,7 +14,6 @@ import ( foldersKind "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" "github.com/grafana/grafana/apps/iam/pkg/reconcilers" "github.com/grafana/grafana/pkg/services/authz" - "github.com/prometheus/client_golang/prometheus" ) var appManifestData = app.ManifestData{ @@ -78,7 +79,7 @@ func New(cfg app.Config) (app.App, error) { folderReconciler, err := reconcilers.NewFolderReconciler(reconcilers.ReconcilerConfig{ ZanzanaCfg: appSpecificConfig.ZanzanaClientCfg, Metrics: metrics, - }) + }, appSpecificConfig.MetricsRegisterer) if err != nil { return nil, fmt.Errorf("unable to create FolderReconciler: %w", err) } diff --git a/apps/iam/pkg/reconcilers/folder_reconciler.go b/apps/iam/pkg/reconcilers/folder_reconciler.go index 066637ee1e6..66a6868722d 100644 --- a/apps/iam/pkg/reconcilers/folder_reconciler.go +++ b/apps/iam/pkg/reconcilers/folder_reconciler.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/prometheus/client_golang/prometheus" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" @@ -35,9 +36,9 @@ type FolderReconciler struct { metrics *ReconcilerMetrics } -func NewFolderReconciler(cfg ReconcilerConfig) (operator.Reconciler, error) { +func NewFolderReconciler(cfg ReconcilerConfig, reg prometheus.Registerer) (operator.Reconciler, error) { // Create Zanzana client - zanzanaClient, err := authz.NewRemoteZanzanaClient("*", cfg.ZanzanaCfg) + zanzanaClient, err := authz.NewRemoteZanzanaClient(cfg.ZanzanaCfg, reg) if err != nil { return nil, fmt.Errorf("unable to create zanzana client: %w", err) diff --git a/apps/logsdrilldown/definitions/logsdrilldown-manifest.json b/apps/logsdrilldown/definitions/logsdrilldown-manifest.json new file mode 100644 index 00000000000..da34c0c70f2 --- /dev/null +++ b/apps/logsdrilldown/definitions/logsdrilldown-manifest.json @@ -0,0 +1,319 @@ +{ + "apiVersion": "apps.grafana.com/v1alpha2", + "kind": "AppManifest", + "metadata": { + "name": "logsdrilldown" + }, + "spec": { + "appName": "logsdrilldown", + "group": "logsdrilldown.grafana.app", + "versions": [ + { + "name": "v1alpha1", + "served": true, + "kinds": [ + { + "kind": "LogsDrilldown", + "plural": "LogsDrilldowns", + "scope": "Namespaced", + "schemas": { + "LogsDrilldown": { + "properties": { + "spec": { + "$ref": "#/components/schemas/spec" + }, + "status": { + "$ref": "#/components/schemas/status" + } + }, + "required": ["spec"] + }, + "OperatorState": { + "additionalProperties": false, + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "details contains any extra information that is operator-specific", + "type": "object" + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "spec": { + "additionalProperties": false, + "properties": { + "defaultFields": { + "items": { + "type": "string" + }, + "type": "array" + }, + "interceptDismissed": { + "type": "boolean" + }, + "prettifyJSON": { + "type": "boolean" + }, + "wrapLogMessage": { + "type": "boolean" + } + }, + "required": ["defaultFields", "prettifyJSON", "wrapLogMessage", "interceptDismissed"], + "type": "object" + }, + "status": { + "additionalProperties": false, + "properties": { + "additionalFields": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "additionalFields is reserved for future use", + "type": "object" + }, + "operatorStates": { + "additionalProperties": { + "$ref": "#/components/schemas/OperatorState" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "conversion": false + }, + { + "kind": "LogsDrilldownDefaults", + "plural": "LogsDrilldownDefaults", + "scope": "Namespaced", + "schemas": { + "LogsDrilldownDefaults": { + "properties": { + "spec": { + "$ref": "#/components/schemas/spec" + }, + "status": { + "$ref": "#/components/schemas/status" + } + }, + "required": ["spec"] + }, + "OperatorState": { + "additionalProperties": false, + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "details contains any extra information that is operator-specific", + "type": "object" + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "spec": { + "additionalProperties": false, + "properties": { + "defaultFields": { + "items": { + "type": "string" + }, + "type": "array" + }, + "interceptDismissed": { + "type": "boolean" + }, + "prettifyJSON": { + "type": "boolean" + }, + "wrapLogMessage": { + "type": "boolean" + } + }, + "required": ["defaultFields", "prettifyJSON", "wrapLogMessage", "interceptDismissed"], + "type": "object" + }, + "status": { + "additionalProperties": false, + "properties": { + "additionalFields": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "additionalFields is reserved for future use", + "type": "object" + }, + "operatorStates": { + "additionalProperties": { + "$ref": "#/components/schemas/OperatorState" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "conversion": false + }, + { + "kind": "LogsDrilldownDefaultColumns", + "plural": "LogsDrilldownDefaultColumns", + "scope": "Namespaced", + "schemas": { + "LogsDefaultColumnsLabel": { + "additionalProperties": false, + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": ["key", "value"], + "type": "object" + }, + "LogsDefaultColumnsLabels": { + "items": { + "$ref": "#/components/schemas/LogsDefaultColumnsLabel" + }, + "type": "array" + }, + "LogsDefaultColumnsRecord": { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "type": "string" + }, + "type": "array" + }, + "labels": { + "$ref": "#/components/schemas/LogsDefaultColumnsLabels" + } + }, + "required": ["columns", "labels"], + "type": "object" + }, + "LogsDefaultColumnsRecords": { + "items": { + "$ref": "#/components/schemas/LogsDefaultColumnsRecord" + }, + "type": "array" + }, + "LogsDrilldownDefaultColumns": { + "properties": { + "spec": { + "$ref": "#/components/schemas/spec" + }, + "status": { + "$ref": "#/components/schemas/status" + } + }, + "required": ["spec"] + }, + "OperatorState": { + "additionalProperties": false, + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "details contains any extra information that is operator-specific", + "type": "object" + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "spec": { + "additionalProperties": false, + "properties": { + "records": { + "$ref": "#/components/schemas/LogsDefaultColumnsRecords" + } + }, + "required": ["records"], + "type": "object" + }, + "status": { + "additionalProperties": false, + "properties": { + "additionalFields": { + "additionalProperties": { + "additionalProperties": {}, + "type": "object" + }, + "description": "additionalFields is reserved for future use", + "type": "object" + }, + "operatorStates": { + "additionalProperties": { + "$ref": "#/components/schemas/OperatorState" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "conversion": false + } + ] + } + ], + "preferredVersion": "v1alpha1" + } +} diff --git a/apps/logsdrilldown/definitions/logsdrilldown.logsdrilldown.grafana.app.json b/apps/logsdrilldown/definitions/logsdrilldown.logsdrilldown.grafana.app.json new file mode 100644 index 00000000000..e0259f421ad --- /dev/null +++ b/apps/logsdrilldown/definitions/logsdrilldown.logsdrilldown.grafana.app.json @@ -0,0 +1,92 @@ +{ + "kind": "CustomResourceDefinition", + "apiVersion": "apiextensions.k8s.io/v1", + "metadata": { + "name": "logsdrilldowns.logsdrilldown.grafana.app" + }, + "spec": { + "group": "logsdrilldown.grafana.app", + "versions": [ + { + "name": "v1alpha1", + "served": true, + "storage": true, + "schema": { + "openAPIV3Schema": { + "properties": { + "spec": { + "properties": { + "defaultFields": { + "items": { + "type": "string" + }, + "type": "array" + }, + "interceptDismissed": { + "type": "boolean" + }, + "prettifyJSON": { + "type": "boolean" + }, + "wrapLogMessage": { + "type": "boolean" + } + }, + "required": ["defaultFields", "prettifyJSON", "wrapLogMessage", "interceptDismissed"], + "type": "object" + }, + "status": { + "properties": { + "additionalFields": { + "description": "additionalFields is reserved for future use", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "operatorStates": { + "additionalProperties": { + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "description": "details contains any extra information that is operator-specific", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "required": ["spec"], + "type": "object" + } + }, + "subresources": { + "status": {} + } + } + ], + "names": { + "kind": "LogsDrilldown", + "plural": "logsdrilldowns" + }, + "scope": "Namespaced" + } +} diff --git a/apps/logsdrilldown/definitions/logsdrilldowndefaultcolumns.logsdrilldown.grafana.app.json b/apps/logsdrilldown/definitions/logsdrilldowndefaultcolumns.logsdrilldown.grafana.app.json new file mode 100644 index 00000000000..28aa314311d --- /dev/null +++ b/apps/logsdrilldown/definitions/logsdrilldowndefaultcolumns.logsdrilldown.grafana.app.json @@ -0,0 +1,107 @@ +{ + "kind": "CustomResourceDefinition", + "apiVersion": "apiextensions.k8s.io/v1", + "metadata": { + "name": "logsdrilldowndefaultcolumns.logsdrilldown.grafana.app" + }, + "spec": { + "group": "logsdrilldown.grafana.app", + "versions": [ + { + "name": "v1alpha1", + "served": true, + "storage": true, + "schema": { + "openAPIV3Schema": { + "properties": { + "spec": { + "properties": { + "records": { + "items": { + "properties": { + "columns": { + "items": { + "type": "string" + }, + "type": "array" + }, + "labels": { + "items": { + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "required": ["key", "value"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["columns", "labels"], + "type": "object" + }, + "type": "array" + } + }, + "required": ["records"], + "type": "object" + }, + "status": { + "properties": { + "additionalFields": { + "description": "additionalFields is reserved for future use", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "operatorStates": { + "additionalProperties": { + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "description": "details contains any extra information that is operator-specific", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "required": ["spec"], + "type": "object" + } + }, + "subresources": { + "status": {} + } + } + ], + "names": { + "kind": "LogsDrilldownDefaultColumns", + "plural": "logsdrilldowndefaultcolumns" + }, + "scope": "Namespaced" + } +} diff --git a/apps/logsdrilldown/definitions/logsdrilldowndefaults.logsdrilldown.grafana.app.json b/apps/logsdrilldown/definitions/logsdrilldowndefaults.logsdrilldown.grafana.app.json new file mode 100644 index 00000000000..f2ab4b77e80 --- /dev/null +++ b/apps/logsdrilldown/definitions/logsdrilldowndefaults.logsdrilldown.grafana.app.json @@ -0,0 +1,92 @@ +{ + "kind": "CustomResourceDefinition", + "apiVersion": "apiextensions.k8s.io/v1", + "metadata": { + "name": "logsdrilldowndefaults.logsdrilldown.grafana.app" + }, + "spec": { + "group": "logsdrilldown.grafana.app", + "versions": [ + { + "name": "v1alpha1", + "served": true, + "storage": true, + "schema": { + "openAPIV3Schema": { + "properties": { + "spec": { + "properties": { + "defaultFields": { + "items": { + "type": "string" + }, + "type": "array" + }, + "interceptDismissed": { + "type": "boolean" + }, + "prettifyJSON": { + "type": "boolean" + }, + "wrapLogMessage": { + "type": "boolean" + } + }, + "required": ["defaultFields", "prettifyJSON", "wrapLogMessage", "interceptDismissed"], + "type": "object" + }, + "status": { + "properties": { + "additionalFields": { + "description": "additionalFields is reserved for future use", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "operatorStates": { + "additionalProperties": { + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "description": "details contains any extra information that is operator-specific", + "type": "object", + "x-kubernetes-preserve-unknown-fields": true + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "enum": ["success", "in_progress", "failed"], + "type": "string" + } + }, + "required": ["lastEvaluation", "state"], + "type": "object" + }, + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object" + } + }, + "type": "object" + } + }, + "required": ["spec"], + "type": "object" + } + }, + "subresources": { + "status": {} + } + } + ], + "names": { + "kind": "LogsDrilldownDefaults", + "plural": "logsdrilldowndefaults" + }, + "scope": "Namespaced" + } +} diff --git a/apps/logsdrilldown/kinds/logsdrilldown.cue b/apps/logsdrilldown/kinds/logsdrilldown.cue index 4a560ae3c6e..d2752103820 100644 --- a/apps/logsdrilldown/kinds/logsdrilldown.cue +++ b/apps/logsdrilldown/kinds/logsdrilldown.cue @@ -1,5 +1,9 @@ package kinds +import ( + "github.com/grafana/grafana/apps/logsdrilldown/kinds/v0alpha1" +) + LogsDrilldownSpecv1alpha1: { defaultFields: [...string] | *[] prettifyJSON: bool @@ -21,3 +25,12 @@ logsdrilldownDefaultsv1alpha1: { spec: LogsDrilldownSpecv1alpha1 } } + +// Default columns API +logsdrilldownDefaultColumnsv0alpha1: { + kind: "LogsDrilldownDefaultColumns" + pluralName: "LogsDrilldownDefaultColumns" + schema: { + spec: v0alpha1.LogsDefaultColumns + } +} diff --git a/apps/logsdrilldown/kinds/manifest.cue b/apps/logsdrilldown/kinds/manifest.cue index e2f2fb236b1..ab717de6a92 100644 --- a/apps/logsdrilldown/kinds/manifest.cue +++ b/apps/logsdrilldown/kinds/manifest.cue @@ -35,12 +35,12 @@ manifest: { // It includes kinds which the v1alpha1 API serves, and (future) custom routes served globally from the v1alpha1 version. v1alpha1: { // kinds is the list of kinds served by this version - kinds: [logsdrilldownv1alpha1, logsdrilldownDefaultsv1alpha1] + kinds: [logsdrilldownv1alpha1, logsdrilldownDefaultsv1alpha1, logsdrilldownDefaultColumnsv0alpha1] // [OPTIONAL] // served indicates whether this particular version is served by the API server. // served should be set to false before a version is removed from the manifest entirely. // served defaults to true if not present. - served: true + served: true // [OPTIONAL] // Codegen is a trait that tells the grafana-app-sdk, or other code generation tooling, how to process this kind. // If not present, default values within the codegen trait are used. @@ -64,4 +64,4 @@ v1alpha1: { enabled: true } } -} \ No newline at end of file +} diff --git a/apps/logsdrilldown/kinds/v0alpha1/defaultcolumns.cue b/apps/logsdrilldown/kinds/v0alpha1/defaultcolumns.cue new file mode 100644 index 00000000000..123d5129c15 --- /dev/null +++ b/apps/logsdrilldown/kinds/v0alpha1/defaultcolumns.cue @@ -0,0 +1,19 @@ +package v0alpha1 + +#LogsDefaultColumnsLabel: { + key: string + value: string +} + +#LogsDefaultColumnsLabels: [...#LogsDefaultColumnsLabel] + +#LogsDefaultColumnsRecord: { + columns: [...string] + labels: #LogsDefaultColumnsLabels +} + +#LogsDefaultColumnsRecords: [...#LogsDefaultColumnsRecord] + +LogsDefaultColumns: { + records: #LogsDefaultColumnsRecords +} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go index 4ede8bb4ee6..50bdc230cd1 100644 --- a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go @@ -25,6 +25,13 @@ type LogsDrilldown struct { Status LogsDrilldownStatus `json:"status" yaml:"status"` } +func NewLogsDrilldown() *LogsDrilldown { + return &LogsDrilldown{ + Spec: *NewLogsDrilldownSpec(), + Status: *NewLogsDrilldownStatus(), + } +} + func (o *LogsDrilldown) GetSpec() any { return o.Spec } diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go index e6864c965a7..8e88e870346 100644 --- a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaLogsDrilldown = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", &LogsDrilldown{}, &LogsDrilldownList{}, resource.WithKind("LogsDrilldown"), + schemaLogsDrilldown = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", NewLogsDrilldown(), &LogsDrilldownList{}, resource.WithKind("LogsDrilldown"), resource.WithPlural("logsdrilldowns"), resource.WithScope(resource.NamespacedScope)) kindLogsDrilldown = resource.Kind{ Schema: schemaLogsDrilldown, diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go new file mode 100644 index 00000000000..b5d573bc1dc --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "context" + + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type LogsDrilldownDefaultColumnsClient struct { + client *resource.TypedClient[*LogsDrilldownDefaultColumns, *LogsDrilldownDefaultColumnsList] +} + +func NewLogsDrilldownDefaultColumnsClient(client resource.Client) *LogsDrilldownDefaultColumnsClient { + return &LogsDrilldownDefaultColumnsClient{ + client: resource.NewTypedClient[*LogsDrilldownDefaultColumns, *LogsDrilldownDefaultColumnsList](client, LogsDrilldownDefaultColumnsKind()), + } +} + +func NewLogsDrilldownDefaultColumnsClientFromGenerator(generator resource.ClientGenerator) (*LogsDrilldownDefaultColumnsClient, error) { + c, err := generator.ClientFor(LogsDrilldownDefaultColumnsKind()) + if err != nil { + return nil, err + } + return NewLogsDrilldownDefaultColumnsClient(c), nil +} + +func (c *LogsDrilldownDefaultColumnsClient) Get(ctx context.Context, identifier resource.Identifier) (*LogsDrilldownDefaultColumns, error) { + return c.client.Get(ctx, identifier) +} + +func (c *LogsDrilldownDefaultColumnsClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultColumnsList, error) { + return c.client.List(ctx, namespace, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultColumnsList, error) { + resp, err := c.client.List(ctx, namespace, resource.ListOptions{ + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + for resp.GetContinue() != "" { + page, err := c.client.List(ctx, namespace, resource.ListOptions{ + Continue: resp.GetContinue(), + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + resp.SetContinue(page.GetContinue()) + resp.SetResourceVersion(page.GetResourceVersion()) + resp.SetItems(append(resp.GetItems(), page.GetItems()...)) + } + return resp, nil +} + +func (c *LogsDrilldownDefaultColumnsClient) Create(ctx context.Context, obj *LogsDrilldownDefaultColumns, opts resource.CreateOptions) (*LogsDrilldownDefaultColumns, error) { + // Make sure apiVersion and kind are set + obj.APIVersion = GroupVersion.Identifier() + obj.Kind = LogsDrilldownDefaultColumnsKind().Kind() + return c.client.Create(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) Update(ctx context.Context, obj *LogsDrilldownDefaultColumns, opts resource.UpdateOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Update(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Patch(ctx, identifier, req, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus LogsDrilldownDefaultColumnsStatus, opts resource.UpdateOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Update(ctx, &LogsDrilldownDefaultColumns{ + TypeMeta: metav1.TypeMeta{ + Kind: LogsDrilldownDefaultColumnsKind().Kind(), + APIVersion: GroupVersion.Identifier(), + }, + ObjectMeta: metav1.ObjectMeta{ + ResourceVersion: opts.ResourceVersion, + Namespace: identifier.Namespace, + Name: identifier.Name, + }, + Status: newStatus, + }, resource.UpdateOptions{ + Subresource: "status", + ResourceVersion: opts.ResourceVersion, + }) +} + +func (c *LogsDrilldownDefaultColumnsClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { + return c.client.Delete(ctx, identifier, opts) +} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go new file mode 100644 index 00000000000..311d2f02683 --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go @@ -0,0 +1,28 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "encoding/json" + "io" + + "github.com/grafana/grafana-app-sdk/resource" +) + +// LogsDrilldownDefaultColumnsJSONCodec is an implementation of resource.Codec for kubernetes JSON encoding +type LogsDrilldownDefaultColumnsJSONCodec struct{} + +// Read reads JSON-encoded bytes from `reader` and unmarshals them into `into` +func (*LogsDrilldownDefaultColumnsJSONCodec) Read(reader io.Reader, into resource.Object) error { + return json.NewDecoder(reader).Decode(into) +} + +// Write writes JSON-encoded bytes into `writer` marshaled from `from` +func (*LogsDrilldownDefaultColumnsJSONCodec) Write(writer io.Writer, from resource.Object) error { + return json.NewEncoder(writer).Encode(from) +} + +// Interface compliance checks +var _ resource.Codec = &LogsDrilldownDefaultColumnsJSONCodec{} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go new file mode 100644 index 00000000000..a4bb052fe25 --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go @@ -0,0 +1,31 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +import ( + time "time" +) + +// metadata contains embedded CommonMetadata and can be extended with custom string fields +// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here +// without external reference as using the CommonMetadata reference breaks thema codegen. +type LogsDrilldownDefaultColumnsMetadata struct { + UpdateTimestamp time.Time `json:"updateTimestamp"` + CreatedBy string `json:"createdBy"` + Uid string `json:"uid"` + CreationTimestamp time.Time `json:"creationTimestamp"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` + Finalizers []string `json:"finalizers"` + ResourceVersion string `json:"resourceVersion"` + Generation int64 `json:"generation"` + UpdatedBy string `json:"updatedBy"` + Labels map[string]string `json:"labels"` +} + +// NewLogsDrilldownDefaultColumnsMetadata creates a new LogsDrilldownDefaultColumnsMetadata object. +func NewLogsDrilldownDefaultColumnsMetadata() *LogsDrilldownDefaultColumnsMetadata { + return &LogsDrilldownDefaultColumnsMetadata{ + Finalizers: []string{}, + Labels: map[string]string{}, + } +} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go new file mode 100644 index 00000000000..4340a27714e --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go @@ -0,0 +1,326 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "fmt" + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "time" +) + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumns struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ObjectMeta `json:"metadata" yaml:"metadata"` + + // Spec is the spec of the LogsDrilldownDefaultColumns + Spec LogsDrilldownDefaultColumnsSpec `json:"spec" yaml:"spec"` + + Status LogsDrilldownDefaultColumnsStatus `json:"status" yaml:"status"` +} + +func NewLogsDrilldownDefaultColumns() *LogsDrilldownDefaultColumns { + return &LogsDrilldownDefaultColumns{ + Spec: *NewLogsDrilldownDefaultColumnsSpec(), + Status: *NewLogsDrilldownDefaultColumnsStatus(), + } +} + +func (o *LogsDrilldownDefaultColumns) GetSpec() any { + return o.Spec +} + +func (o *LogsDrilldownDefaultColumns) SetSpec(spec any) error { + cast, ok := spec.(LogsDrilldownDefaultColumnsSpec) + if !ok { + return fmt.Errorf("cannot set spec type %#v, not of type Spec", spec) + } + o.Spec = cast + return nil +} + +func (o *LogsDrilldownDefaultColumns) GetSubresources() map[string]any { + return map[string]any{ + "status": o.Status, + } +} + +func (o *LogsDrilldownDefaultColumns) GetSubresource(name string) (any, bool) { + switch name { + case "status": + return o.Status, true + default: + return nil, false + } +} + +func (o *LogsDrilldownDefaultColumns) SetSubresource(name string, value any) error { + switch name { + case "status": + cast, ok := value.(LogsDrilldownDefaultColumnsStatus) + if !ok { + return fmt.Errorf("cannot set status type %#v, not of type LogsDrilldownDefaultColumnsStatus", value) + } + o.Status = cast + return nil + default: + return fmt.Errorf("subresource '%s' does not exist", name) + } +} + +func (o *LogsDrilldownDefaultColumns) GetStaticMetadata() resource.StaticMetadata { + gvk := o.GroupVersionKind() + return resource.StaticMetadata{ + Name: o.ObjectMeta.Name, + Namespace: o.ObjectMeta.Namespace, + Group: gvk.Group, + Version: gvk.Version, + Kind: gvk.Kind, + } +} + +func (o *LogsDrilldownDefaultColumns) SetStaticMetadata(metadata resource.StaticMetadata) { + o.Name = metadata.Name + o.Namespace = metadata.Namespace + o.SetGroupVersionKind(schema.GroupVersionKind{ + Group: metadata.Group, + Version: metadata.Version, + Kind: metadata.Kind, + }) +} + +func (o *LogsDrilldownDefaultColumns) GetCommonMetadata() resource.CommonMetadata { + dt := o.DeletionTimestamp + var deletionTimestamp *time.Time + if dt != nil { + deletionTimestamp = &dt.Time + } + // Legacy ExtraFields support + extraFields := make(map[string]any) + if o.Annotations != nil { + extraFields["annotations"] = o.Annotations + } + if o.ManagedFields != nil { + extraFields["managedFields"] = o.ManagedFields + } + if o.OwnerReferences != nil { + extraFields["ownerReferences"] = o.OwnerReferences + } + return resource.CommonMetadata{ + UID: string(o.UID), + ResourceVersion: o.ResourceVersion, + Generation: o.Generation, + Labels: o.Labels, + CreationTimestamp: o.CreationTimestamp.Time, + DeletionTimestamp: deletionTimestamp, + Finalizers: o.Finalizers, + UpdateTimestamp: o.GetUpdateTimestamp(), + CreatedBy: o.GetCreatedBy(), + UpdatedBy: o.GetUpdatedBy(), + ExtraFields: extraFields, + } +} + +func (o *LogsDrilldownDefaultColumns) SetCommonMetadata(metadata resource.CommonMetadata) { + o.UID = types.UID(metadata.UID) + o.ResourceVersion = metadata.ResourceVersion + o.Generation = metadata.Generation + o.Labels = metadata.Labels + o.CreationTimestamp = metav1.NewTime(metadata.CreationTimestamp) + if metadata.DeletionTimestamp != nil { + dt := metav1.NewTime(*metadata.DeletionTimestamp) + o.DeletionTimestamp = &dt + } else { + o.DeletionTimestamp = nil + } + o.Finalizers = metadata.Finalizers + if o.Annotations == nil { + o.Annotations = make(map[string]string) + } + if !metadata.UpdateTimestamp.IsZero() { + o.SetUpdateTimestamp(metadata.UpdateTimestamp) + } + if metadata.CreatedBy != "" { + o.SetCreatedBy(metadata.CreatedBy) + } + if metadata.UpdatedBy != "" { + o.SetUpdatedBy(metadata.UpdatedBy) + } + // Legacy support for setting Annotations, ManagedFields, and OwnerReferences via ExtraFields + if metadata.ExtraFields != nil { + if annotations, ok := metadata.ExtraFields["annotations"]; ok { + if cast, ok := annotations.(map[string]string); ok { + o.Annotations = cast + } + } + if managedFields, ok := metadata.ExtraFields["managedFields"]; ok { + if cast, ok := managedFields.([]metav1.ManagedFieldsEntry); ok { + o.ManagedFields = cast + } + } + if ownerReferences, ok := metadata.ExtraFields["ownerReferences"]; ok { + if cast, ok := ownerReferences.([]metav1.OwnerReference); ok { + o.OwnerReferences = cast + } + } + } +} + +func (o *LogsDrilldownDefaultColumns) GetCreatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/createdBy"] +} + +func (o *LogsDrilldownDefaultColumns) SetCreatedBy(createdBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/createdBy"] = createdBy +} + +func (o *LogsDrilldownDefaultColumns) GetUpdateTimestamp() time.Time { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + parsed, _ := time.Parse(time.RFC3339, o.ObjectMeta.Annotations["grafana.com/updateTimestamp"]) + return parsed +} + +func (o *LogsDrilldownDefaultColumns) SetUpdateTimestamp(updateTimestamp time.Time) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updateTimestamp"] = updateTimestamp.Format(time.RFC3339) +} + +func (o *LogsDrilldownDefaultColumns) GetUpdatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/updatedBy"] +} + +func (o *LogsDrilldownDefaultColumns) SetUpdatedBy(updatedBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updatedBy"] = updatedBy +} + +func (o *LogsDrilldownDefaultColumns) Copy() resource.Object { + return resource.CopyObject(o) +} + +func (o *LogsDrilldownDefaultColumns) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaultColumns) DeepCopy() *LogsDrilldownDefaultColumns { + cpy := &LogsDrilldownDefaultColumns{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaultColumns) DeepCopyInto(dst *LogsDrilldownDefaultColumns) { + dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion + dst.TypeMeta.Kind = o.TypeMeta.Kind + o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) + o.Spec.DeepCopyInto(&dst.Spec) + o.Status.DeepCopyInto(&dst.Status) +} + +// Interface compliance compile-time check +var _ resource.Object = &LogsDrilldownDefaultColumns{} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsList struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ListMeta `json:"metadata" yaml:"metadata"` + Items []LogsDrilldownDefaultColumns `json:"items" yaml:"items"` +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaultColumnsList) Copy() resource.ListObject { + cpy := &LogsDrilldownDefaultColumnsList{ + TypeMeta: o.TypeMeta, + Items: make([]LogsDrilldownDefaultColumns, len(o.Items)), + } + o.ListMeta.DeepCopyInto(&cpy.ListMeta) + for i := 0; i < len(o.Items); i++ { + if item, ok := o.Items[i].Copy().(*LogsDrilldownDefaultColumns); ok { + cpy.Items[i] = *item + } + } + return cpy +} + +func (o *LogsDrilldownDefaultColumnsList) GetItems() []resource.Object { + items := make([]resource.Object, len(o.Items)) + for i := 0; i < len(o.Items); i++ { + items[i] = &o.Items[i] + } + return items +} + +func (o *LogsDrilldownDefaultColumnsList) SetItems(items []resource.Object) { + o.Items = make([]LogsDrilldownDefaultColumns, len(items)) + for i := 0; i < len(items); i++ { + o.Items[i] = *items[i].(*LogsDrilldownDefaultColumns) + } +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopy() *LogsDrilldownDefaultColumnsList { + cpy := &LogsDrilldownDefaultColumnsList{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopyInto(dst *LogsDrilldownDefaultColumnsList) { + resource.CopyObjectInto(dst, o) +} + +// Interface compliance compile-time check +var _ resource.ListObject = &LogsDrilldownDefaultColumnsList{} + +// Copy methods for all subresource types + +// DeepCopy creates a full deep copy of Spec +func (s *LogsDrilldownDefaultColumnsSpec) DeepCopy() *LogsDrilldownDefaultColumnsSpec { + cpy := &LogsDrilldownDefaultColumnsSpec{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Spec into another Spec object +func (s *LogsDrilldownDefaultColumnsSpec) DeepCopyInto(dst *LogsDrilldownDefaultColumnsSpec) { + resource.CopyObjectInto(dst, s) +} + +// DeepCopy creates a full deep copy of LogsDrilldownDefaultColumnsStatus +func (s *LogsDrilldownDefaultColumnsStatus) DeepCopy() *LogsDrilldownDefaultColumnsStatus { + cpy := &LogsDrilldownDefaultColumnsStatus{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies LogsDrilldownDefaultColumnsStatus into another LogsDrilldownDefaultColumnsStatus object +func (s *LogsDrilldownDefaultColumnsStatus) DeepCopyInto(dst *LogsDrilldownDefaultColumnsStatus) { + resource.CopyObjectInto(dst, s) +} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go new file mode 100644 index 00000000000..cc5363e16bb --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go @@ -0,0 +1,34 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" +) + +// schema is unexported to prevent accidental overwrites +var ( + schemaLogsDrilldownDefaultColumns = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", NewLogsDrilldownDefaultColumns(), &LogsDrilldownDefaultColumnsList{}, resource.WithKind("LogsDrilldownDefaultColumns"), + resource.WithPlural("logsdrilldowndefaultcolumns"), resource.WithScope(resource.NamespacedScope)) + kindLogsDrilldownDefaultColumns = resource.Kind{ + Schema: schemaLogsDrilldownDefaultColumns, + Codecs: map[resource.KindEncoding]resource.Codec{ + resource.KindEncodingJSON: &LogsDrilldownDefaultColumnsJSONCodec{}, + }, + } +) + +// Kind returns a resource.Kind for this Schema with a JSON codec +func LogsDrilldownDefaultColumnsKind() resource.Kind { + return kindLogsDrilldownDefaultColumns +} + +// Schema returns a resource.SimpleSchema representation of LogsDrilldownDefaultColumns +func LogsDrilldownDefaultColumnsSchema() *resource.SimpleSchema { + return schemaLogsDrilldownDefaultColumns +} + +// Interface compliance checks +var _ resource.Schema = kindLogsDrilldownDefaultColumns diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go new file mode 100644 index 00000000000..ce12ebb0761 --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go @@ -0,0 +1,43 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords []LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord struct { + Columns []string `json:"columns"` + Labels LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels `json:"labels"` +} + +// NewLogsDrilldownDefaultColumnsLogsDefaultColumnsRecord creates a new LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord object. +func NewLogsDrilldownDefaultColumnsLogsDefaultColumnsRecord() *LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord { + return &LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord{ + Columns: []string{}, + } +} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels []LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// NewLogsDrilldownDefaultColumnsLogsDefaultColumnsLabel creates a new LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel object. +func NewLogsDrilldownDefaultColumnsLogsDefaultColumnsLabel() *LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel { + return &LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel{} +} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsSpec struct { + Records LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords `json:"records"` +} + +// NewLogsDrilldownDefaultColumnsSpec creates a new LogsDrilldownDefaultColumnsSpec object. +func NewLogsDrilldownDefaultColumnsSpec() *LogsDrilldownDefaultColumnsSpec { + return &LogsDrilldownDefaultColumnsSpec{} +} diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go new file mode 100644 index 00000000000..c2183832095 --- /dev/null +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go @@ -0,0 +1,44 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsstatusOperatorState struct { + // lastEvaluation is the ResourceVersion last evaluated + LastEvaluation string `json:"lastEvaluation"` + // state describes the state of the lastEvaluation. + // It is limited to three possible states for machine evaluation. + State LogsDrilldownDefaultColumnsStatusOperatorStateState `json:"state"` + // descriptiveState is an optional more descriptive state field which has no requirements on format + DescriptiveState *string `json:"descriptiveState,omitempty"` + // details contains any extra information that is operator-specific + Details map[string]interface{} `json:"details,omitempty"` +} + +// NewLogsDrilldownDefaultColumnsstatusOperatorState creates a new LogsDrilldownDefaultColumnsstatusOperatorState object. +func NewLogsDrilldownDefaultColumnsstatusOperatorState() *LogsDrilldownDefaultColumnsstatusOperatorState { + return &LogsDrilldownDefaultColumnsstatusOperatorState{} +} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsStatus struct { + // operatorStates is a map of operator ID to operator state evaluations. + // Any operator which consumes this kind SHOULD add its state evaluation information to this field. + OperatorStates map[string]LogsDrilldownDefaultColumnsstatusOperatorState `json:"operatorStates,omitempty"` + // additionalFields is reserved for future use + AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` +} + +// NewLogsDrilldownDefaultColumnsStatus creates a new LogsDrilldownDefaultColumnsStatus object. +func NewLogsDrilldownDefaultColumnsStatus() *LogsDrilldownDefaultColumnsStatus { + return &LogsDrilldownDefaultColumnsStatus{} +} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsStatusOperatorStateState string + +const ( + LogsDrilldownDefaultColumnsStatusOperatorStateStateSuccess LogsDrilldownDefaultColumnsStatusOperatorStateState = "success" + LogsDrilldownDefaultColumnsStatusOperatorStateStateInProgress LogsDrilldownDefaultColumnsStatusOperatorStateState = "in_progress" + LogsDrilldownDefaultColumnsStatusOperatorStateStateFailed LogsDrilldownDefaultColumnsStatusOperatorStateState = "failed" +) diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_object_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_object_gen.go index 8dfb90a1bfb..ff5ce10adce 100644 --- a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_object_gen.go +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_object_gen.go @@ -25,6 +25,13 @@ type LogsDrilldownDefaults struct { Status LogsDrilldownDefaultsStatus `json:"status" yaml:"status"` } +func NewLogsDrilldownDefaults() *LogsDrilldownDefaults { + return &LogsDrilldownDefaults{ + Spec: *NewLogsDrilldownDefaultsSpec(), + Status: *NewLogsDrilldownDefaultsStatus(), + } +} + func (o *LogsDrilldownDefaults) GetSpec() any { return o.Spec } diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_schema_gen.go b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_schema_gen.go index 20e952ce021..f488c319db2 100644 --- a/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_schema_gen.go +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown/v1alpha1/logsdrilldowndefaults_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaLogsDrilldownDefaults = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", &LogsDrilldownDefaults{}, &LogsDrilldownDefaultsList{}, resource.WithKind("LogsDrilldownDefaults"), + schemaLogsDrilldownDefaults = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", NewLogsDrilldownDefaults(), &LogsDrilldownDefaultsList{}, resource.WithKind("LogsDrilldownDefaults"), resource.WithPlural("logsdrilldowndefaults"), resource.WithScope(resource.NamespacedScope)) kindLogsDrilldownDefaults = resource.Kind{ Schema: schemaLogsDrilldownDefaults, diff --git a/apps/logsdrilldown/pkg/apis/logsdrilldown_manifest.go b/apps/logsdrilldown/pkg/apis/logsdrilldown_manifest.go index ef0d5801511..2350b924dda 100644 --- a/apps/logsdrilldown/pkg/apis/logsdrilldown_manifest.go +++ b/apps/logsdrilldown/pkg/apis/logsdrilldown_manifest.go @@ -20,12 +20,15 @@ import ( ) var ( - rawSchemaLogsDrilldownv1alpha1 = []byte(`{"LogsDrilldown":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) - versionSchemaLogsDrilldownv1alpha1 app.VersionSchema - _ = json.Unmarshal(rawSchemaLogsDrilldownv1alpha1, &versionSchemaLogsDrilldownv1alpha1) - rawSchemaLogsDrilldownDefaultsv1alpha1 = []byte(`{"LogsDrilldownDefaults":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) - versionSchemaLogsDrilldownDefaultsv1alpha1 app.VersionSchema - _ = json.Unmarshal(rawSchemaLogsDrilldownDefaultsv1alpha1, &versionSchemaLogsDrilldownDefaultsv1alpha1) + rawSchemaLogsDrilldownv1alpha1 = []byte(`{"LogsDrilldown":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownv1alpha1, &versionSchemaLogsDrilldownv1alpha1) + rawSchemaLogsDrilldownDefaultsv1alpha1 = []byte(`{"LogsDrilldownDefaults":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownDefaultsv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownDefaultsv1alpha1, &versionSchemaLogsDrilldownDefaultsv1alpha1) + rawSchemaLogsDrilldownDefaultColumnsv1alpha1 = []byte(`{"LogsDefaultColumnsLabel":{"additionalProperties":false,"properties":{"key":{"type":"string"},"value":{"type":"string"}},"required":["key","value"],"type":"object"},"LogsDefaultColumnsLabels":{"items":{"$ref":"#/components/schemas/LogsDefaultColumnsLabel"},"type":"array"},"LogsDefaultColumnsRecord":{"additionalProperties":false,"properties":{"columns":{"items":{"type":"string"},"type":"array"},"labels":{"$ref":"#/components/schemas/LogsDefaultColumnsLabels"}},"required":["columns","labels"],"type":"object"},"LogsDefaultColumnsRecords":{"items":{"$ref":"#/components/schemas/LogsDefaultColumnsRecord"},"type":"array"},"LogsDrilldownDefaultColumns":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"records":{"$ref":"#/components/schemas/LogsDefaultColumnsRecords"}},"required":["records"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownDefaultColumnsv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownDefaultColumnsv1alpha1, &versionSchemaLogsDrilldownDefaultColumnsv1alpha1) ) var appManifestData = app.ManifestData{ @@ -52,6 +55,14 @@ var appManifestData = app.ManifestData{ Conversion: false, Schema: &versionSchemaLogsDrilldownDefaultsv1alpha1, }, + + { + Kind: "LogsDrilldownDefaultColumns", + Plural: "LogsDrilldownDefaultColumns", + Scope: "Namespaced", + Conversion: false, + Schema: &versionSchemaLogsDrilldownDefaultColumnsv1alpha1, + }, }, Routes: app.ManifestVersionRoutes{ Namespaced: map[string]spec3.PathProps{}, @@ -71,8 +82,9 @@ func RemoteManifest() app.Manifest { } var kindVersionToGoType = map[string]resource.Kind{ - "LogsDrilldown/v1alpha1": v1alpha1.LogsDrilldownKind(), - "LogsDrilldownDefaults/v1alpha1": v1alpha1.LogsDrilldownDefaultsKind(), + "LogsDrilldown/v1alpha1": v1alpha1.LogsDrilldownKind(), + "LogsDrilldownDefaults/v1alpha1": v1alpha1.LogsDrilldownDefaultsKind(), + "LogsDrilldownDefaultColumns/v1alpha1": v1alpha1.LogsDrilldownDefaultColumnsKind(), } // ManifestGoTypeAssociator returns the associated resource.Kind instance for a given Kind and Version, if one exists. diff --git a/apps/logsdrilldown/pkg/app/app.go b/apps/logsdrilldown/pkg/app/app.go index 7fda1ecb99f..23260270207 100644 --- a/apps/logsdrilldown/pkg/app/app.go +++ b/apps/logsdrilldown/pkg/app/app.go @@ -31,6 +31,9 @@ func New(cfg app.Config) (app.App, error) { { Kind: logsdrilldownv1alpha1.LogsDrilldownDefaultsKind(), }, + { + Kind: logsdrilldownv1alpha1.LogsDrilldownDefaultColumnsKind(), + }, }, } diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/constants.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/constants.go new file mode 100644 index 00000000000..082bec7c874 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/constants.go @@ -0,0 +1,18 @@ +package v1alpha1 + +import "k8s.io/apimachinery/pkg/runtime/schema" + +const ( + // APIGroup is the API group used by all kinds in this package + APIGroup = "logsdrilldown.grafana.app" + // APIVersion is the API version used by all kinds in this package + APIVersion = "v1alpha1" +) + +var ( + // GroupVersion is a schema.GroupVersion consisting of the Group and Version constants for this package + GroupVersion = schema.GroupVersion{ + Group: APIGroup, + Version: APIVersion, + } +) diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_client_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_client_gen.go new file mode 100644 index 00000000000..c133b65f45b --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_client_gen.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "context" + + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type LogsDrilldownClient struct { + client *resource.TypedClient[*LogsDrilldown, *LogsDrilldownList] +} + +func NewLogsDrilldownClient(client resource.Client) *LogsDrilldownClient { + return &LogsDrilldownClient{ + client: resource.NewTypedClient[*LogsDrilldown, *LogsDrilldownList](client, Kind()), + } +} + +func NewLogsDrilldownClientFromGenerator(generator resource.ClientGenerator) (*LogsDrilldownClient, error) { + c, err := generator.ClientFor(Kind()) + if err != nil { + return nil, err + } + return NewLogsDrilldownClient(c), nil +} + +func (c *LogsDrilldownClient) Get(ctx context.Context, identifier resource.Identifier) (*LogsDrilldown, error) { + return c.client.Get(ctx, identifier) +} + +func (c *LogsDrilldownClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownList, error) { + return c.client.List(ctx, namespace, opts) +} + +func (c *LogsDrilldownClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownList, error) { + resp, err := c.client.List(ctx, namespace, resource.ListOptions{ + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + for resp.GetContinue() != "" { + page, err := c.client.List(ctx, namespace, resource.ListOptions{ + Continue: resp.GetContinue(), + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + resp.SetContinue(page.GetContinue()) + resp.SetResourceVersion(page.GetResourceVersion()) + resp.SetItems(append(resp.GetItems(), page.GetItems()...)) + } + return resp, nil +} + +func (c *LogsDrilldownClient) Create(ctx context.Context, obj *LogsDrilldown, opts resource.CreateOptions) (*LogsDrilldown, error) { + // Make sure apiVersion and kind are set + obj.APIVersion = GroupVersion.Identifier() + obj.Kind = Kind().Kind() + return c.client.Create(ctx, obj, opts) +} + +func (c *LogsDrilldownClient) Update(ctx context.Context, obj *LogsDrilldown, opts resource.UpdateOptions) (*LogsDrilldown, error) { + return c.client.Update(ctx, obj, opts) +} + +func (c *LogsDrilldownClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*LogsDrilldown, error) { + return c.client.Patch(ctx, identifier, req, opts) +} + +func (c *LogsDrilldownClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus Status, opts resource.UpdateOptions) (*LogsDrilldown, error) { + return c.client.Update(ctx, &LogsDrilldown{ + TypeMeta: metav1.TypeMeta{ + Kind: Kind().Kind(), + APIVersion: GroupVersion.Identifier(), + }, + ObjectMeta: metav1.ObjectMeta{ + ResourceVersion: opts.ResourceVersion, + Namespace: identifier.Namespace, + Name: identifier.Name, + }, + Status: newStatus, + }, resource.UpdateOptions{ + Subresource: "status", + ResourceVersion: opts.ResourceVersion, + }) +} + +func (c *LogsDrilldownClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { + return c.client.Delete(ctx, identifier, opts) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_codec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_codec_gen.go new file mode 100644 index 00000000000..bb458caeb88 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_codec_gen.go @@ -0,0 +1,28 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "encoding/json" + "io" + + "github.com/grafana/grafana-app-sdk/resource" +) + +// JSONCodec is an implementation of resource.Codec for kubernetes JSON encoding +type JSONCodec struct{} + +// Read reads JSON-encoded bytes from `reader` and unmarshals them into `into` +func (*JSONCodec) Read(reader io.Reader, into resource.Object) error { + return json.NewDecoder(reader).Decode(into) +} + +// Write writes JSON-encoded bytes into `writer` marshaled from `from` +func (*JSONCodec) Write(writer io.Writer, from resource.Object) error { + return json.NewEncoder(writer).Encode(from) +} + +// Interface compliance checks +var _ resource.Codec = &JSONCodec{} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_metadata_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_metadata_gen.go new file mode 100644 index 00000000000..cb7233b22ab --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_metadata_gen.go @@ -0,0 +1,31 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +import ( + time "time" +) + +// metadata contains embedded CommonMetadata and can be extended with custom string fields +// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here +// without external reference as using the CommonMetadata reference breaks thema codegen. +type Metadata struct { + UpdateTimestamp time.Time `json:"updateTimestamp"` + CreatedBy string `json:"createdBy"` + Uid string `json:"uid"` + CreationTimestamp time.Time `json:"creationTimestamp"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` + Finalizers []string `json:"finalizers"` + ResourceVersion string `json:"resourceVersion"` + Generation int64 `json:"generation"` + UpdatedBy string `json:"updatedBy"` + Labels map[string]string `json:"labels"` +} + +// NewMetadata creates a new Metadata object. +func NewMetadata() *Metadata { + return &Metadata{ + Finalizers: []string{}, + Labels: map[string]string{}, + } +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go new file mode 100644 index 00000000000..5d40a873e6b --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_object_gen.go @@ -0,0 +1,319 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "fmt" + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "time" +) + +// +k8s:openapi-gen=true +type LogsDrilldown struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ObjectMeta `json:"metadata" yaml:"metadata"` + + // Spec is the spec of the LogsDrilldown + Spec Spec `json:"spec" yaml:"spec"` + + Status Status `json:"status" yaml:"status"` +} + +func (o *LogsDrilldown) GetSpec() any { + return o.Spec +} + +func (o *LogsDrilldown) SetSpec(spec any) error { + cast, ok := spec.(Spec) + if !ok { + return fmt.Errorf("cannot set spec type %#v, not of type Spec", spec) + } + o.Spec = cast + return nil +} + +func (o *LogsDrilldown) GetSubresources() map[string]any { + return map[string]any{ + "status": o.Status, + } +} + +func (o *LogsDrilldown) GetSubresource(name string) (any, bool) { + switch name { + case "status": + return o.Status, true + default: + return nil, false + } +} + +func (o *LogsDrilldown) SetSubresource(name string, value any) error { + switch name { + case "status": + cast, ok := value.(Status) + if !ok { + return fmt.Errorf("cannot set status type %#v, not of type Status", value) + } + o.Status = cast + return nil + default: + return fmt.Errorf("subresource '%s' does not exist", name) + } +} + +func (o *LogsDrilldown) GetStaticMetadata() resource.StaticMetadata { + gvk := o.GroupVersionKind() + return resource.StaticMetadata{ + Name: o.ObjectMeta.Name, + Namespace: o.ObjectMeta.Namespace, + Group: gvk.Group, + Version: gvk.Version, + Kind: gvk.Kind, + } +} + +func (o *LogsDrilldown) SetStaticMetadata(metadata resource.StaticMetadata) { + o.Name = metadata.Name + o.Namespace = metadata.Namespace + o.SetGroupVersionKind(schema.GroupVersionKind{ + Group: metadata.Group, + Version: metadata.Version, + Kind: metadata.Kind, + }) +} + +func (o *LogsDrilldown) GetCommonMetadata() resource.CommonMetadata { + dt := o.DeletionTimestamp + var deletionTimestamp *time.Time + if dt != nil { + deletionTimestamp = &dt.Time + } + // Legacy ExtraFields support + extraFields := make(map[string]any) + if o.Annotations != nil { + extraFields["annotations"] = o.Annotations + } + if o.ManagedFields != nil { + extraFields["managedFields"] = o.ManagedFields + } + if o.OwnerReferences != nil { + extraFields["ownerReferences"] = o.OwnerReferences + } + return resource.CommonMetadata{ + UID: string(o.UID), + ResourceVersion: o.ResourceVersion, + Generation: o.Generation, + Labels: o.Labels, + CreationTimestamp: o.CreationTimestamp.Time, + DeletionTimestamp: deletionTimestamp, + Finalizers: o.Finalizers, + UpdateTimestamp: o.GetUpdateTimestamp(), + CreatedBy: o.GetCreatedBy(), + UpdatedBy: o.GetUpdatedBy(), + ExtraFields: extraFields, + } +} + +func (o *LogsDrilldown) SetCommonMetadata(metadata resource.CommonMetadata) { + o.UID = types.UID(metadata.UID) + o.ResourceVersion = metadata.ResourceVersion + o.Generation = metadata.Generation + o.Labels = metadata.Labels + o.CreationTimestamp = metav1.NewTime(metadata.CreationTimestamp) + if metadata.DeletionTimestamp != nil { + dt := metav1.NewTime(*metadata.DeletionTimestamp) + o.DeletionTimestamp = &dt + } else { + o.DeletionTimestamp = nil + } + o.Finalizers = metadata.Finalizers + if o.Annotations == nil { + o.Annotations = make(map[string]string) + } + if !metadata.UpdateTimestamp.IsZero() { + o.SetUpdateTimestamp(metadata.UpdateTimestamp) + } + if metadata.CreatedBy != "" { + o.SetCreatedBy(metadata.CreatedBy) + } + if metadata.UpdatedBy != "" { + o.SetUpdatedBy(metadata.UpdatedBy) + } + // Legacy support for setting Annotations, ManagedFields, and OwnerReferences via ExtraFields + if metadata.ExtraFields != nil { + if annotations, ok := metadata.ExtraFields["annotations"]; ok { + if cast, ok := annotations.(map[string]string); ok { + o.Annotations = cast + } + } + if managedFields, ok := metadata.ExtraFields["managedFields"]; ok { + if cast, ok := managedFields.([]metav1.ManagedFieldsEntry); ok { + o.ManagedFields = cast + } + } + if ownerReferences, ok := metadata.ExtraFields["ownerReferences"]; ok { + if cast, ok := ownerReferences.([]metav1.OwnerReference); ok { + o.OwnerReferences = cast + } + } + } +} + +func (o *LogsDrilldown) GetCreatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/createdBy"] +} + +func (o *LogsDrilldown) SetCreatedBy(createdBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/createdBy"] = createdBy +} + +func (o *LogsDrilldown) GetUpdateTimestamp() time.Time { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + parsed, _ := time.Parse(time.RFC3339, o.ObjectMeta.Annotations["grafana.com/updateTimestamp"]) + return parsed +} + +func (o *LogsDrilldown) SetUpdateTimestamp(updateTimestamp time.Time) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updateTimestamp"] = updateTimestamp.Format(time.RFC3339) +} + +func (o *LogsDrilldown) GetUpdatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/updatedBy"] +} + +func (o *LogsDrilldown) SetUpdatedBy(updatedBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updatedBy"] = updatedBy +} + +func (o *LogsDrilldown) Copy() resource.Object { + return resource.CopyObject(o) +} + +func (o *LogsDrilldown) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldown) DeepCopy() *LogsDrilldown { + cpy := &LogsDrilldown{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldown) DeepCopyInto(dst *LogsDrilldown) { + dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion + dst.TypeMeta.Kind = o.TypeMeta.Kind + o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) + o.Spec.DeepCopyInto(&dst.Spec) + o.Status.DeepCopyInto(&dst.Status) +} + +// Interface compliance compile-time check +var _ resource.Object = &LogsDrilldown{} + +// +k8s:openapi-gen=true +type LogsDrilldownList struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ListMeta `json:"metadata" yaml:"metadata"` + Items []LogsDrilldown `json:"items" yaml:"items"` +} + +func (o *LogsDrilldownList) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownList) Copy() resource.ListObject { + cpy := &LogsDrilldownList{ + TypeMeta: o.TypeMeta, + Items: make([]LogsDrilldown, len(o.Items)), + } + o.ListMeta.DeepCopyInto(&cpy.ListMeta) + for i := 0; i < len(o.Items); i++ { + if item, ok := o.Items[i].Copy().(*LogsDrilldown); ok { + cpy.Items[i] = *item + } + } + return cpy +} + +func (o *LogsDrilldownList) GetItems() []resource.Object { + items := make([]resource.Object, len(o.Items)) + for i := 0; i < len(o.Items); i++ { + items[i] = &o.Items[i] + } + return items +} + +func (o *LogsDrilldownList) SetItems(items []resource.Object) { + o.Items = make([]LogsDrilldown, len(items)) + for i := 0; i < len(items); i++ { + o.Items[i] = *items[i].(*LogsDrilldown) + } +} + +func (o *LogsDrilldownList) DeepCopy() *LogsDrilldownList { + cpy := &LogsDrilldownList{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownList) DeepCopyInto(dst *LogsDrilldownList) { + resource.CopyObjectInto(dst, o) +} + +// Interface compliance compile-time check +var _ resource.ListObject = &LogsDrilldownList{} + +// Copy methods for all subresource types + +// DeepCopy creates a full deep copy of Spec +func (s *Spec) DeepCopy() *Spec { + cpy := &Spec{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Spec into another Spec object +func (s *Spec) DeepCopyInto(dst *Spec) { + resource.CopyObjectInto(dst, s) +} + +// DeepCopy creates a full deep copy of Status +func (s *Status) DeepCopy() *Status { + cpy := &Status{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Status into another Status object +func (s *Status) DeepCopyInto(dst *Status) { + resource.CopyObjectInto(dst, s) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go new file mode 100644 index 00000000000..942794416e8 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_schema_gen.go @@ -0,0 +1,34 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" +) + +// schema is unexported to prevent accidental overwrites +var ( + schemaLogsDrilldown = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", &LogsDrilldown{}, &LogsDrilldownList{}, resource.WithKind("LogsDrilldown"), + resource.WithPlural("logsdrilldowns"), resource.WithScope(resource.NamespacedScope)) + kindLogsDrilldown = resource.Kind{ + Schema: schemaLogsDrilldown, + Codecs: map[resource.KindEncoding]resource.Codec{ + resource.KindEncodingJSON: &JSONCodec{}, + }, + } +) + +// Kind returns a resource.Kind for this Schema with a JSON codec +func Kind() resource.Kind { + return kindLogsDrilldown +} + +// Schema returns a resource.SimpleSchema representation of LogsDrilldown +func Schema() *resource.SimpleSchema { + return schemaLogsDrilldown +} + +// Interface compliance checks +var _ resource.Schema = kindLogsDrilldown diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_spec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_spec_gen.go new file mode 100644 index 00000000000..faff5c108dd --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_spec_gen.go @@ -0,0 +1,18 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type Spec struct { + DefaultFields []string `json:"defaultFields"` + PrettifyJSON bool `json:"prettifyJSON"` + WrapLogMessage bool `json:"wrapLogMessage"` + InterceptDismissed bool `json:"interceptDismissed"` +} + +// NewSpec creates a new Spec object. +func NewSpec() *Spec { + return &Spec{ + DefaultFields: []string{}, + } +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_status_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_status_gen.go new file mode 100644 index 00000000000..9b227b00f44 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1/logsdrilldown_status_gen.go @@ -0,0 +1,44 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type StatusOperatorState struct { + // lastEvaluation is the ResourceVersion last evaluated + LastEvaluation string `json:"lastEvaluation"` + // state describes the state of the lastEvaluation. + // It is limited to three possible states for machine evaluation. + State StatusOperatorStateState `json:"state"` + // descriptiveState is an optional more descriptive state field which has no requirements on format + DescriptiveState *string `json:"descriptiveState,omitempty"` + // details contains any extra information that is operator-specific + Details map[string]interface{} `json:"details,omitempty"` +} + +// NewStatusOperatorState creates a new StatusOperatorState object. +func NewStatusOperatorState() *StatusOperatorState { + return &StatusOperatorState{} +} + +// +k8s:openapi-gen=true +type Status struct { + // operatorStates is a map of operator ID to operator state evaluations. + // Any operator which consumes this kind SHOULD add its state evaluation information to this field. + OperatorStates map[string]StatusOperatorState `json:"operatorStates,omitempty"` + // additionalFields is reserved for future use + AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` +} + +// NewStatus creates a new Status object. +func NewStatus() *Status { + return &Status{} +} + +// +k8s:openapi-gen=true +type StatusOperatorStateState string + +const ( + StatusOperatorStateStateSuccess StatusOperatorStateState = "success" + StatusOperatorStateStateInProgress StatusOperatorStateState = "in_progress" + StatusOperatorStateStateFailed StatusOperatorStateState = "failed" +) diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/constants.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/constants.go new file mode 100644 index 00000000000..082bec7c874 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/constants.go @@ -0,0 +1,18 @@ +package v1alpha1 + +import "k8s.io/apimachinery/pkg/runtime/schema" + +const ( + // APIGroup is the API group used by all kinds in this package + APIGroup = "logsdrilldown.grafana.app" + // APIVersion is the API version used by all kinds in this package + APIVersion = "v1alpha1" +) + +var ( + // GroupVersion is a schema.GroupVersion consisting of the Group and Version constants for this package + GroupVersion = schema.GroupVersion{ + Group: APIGroup, + Version: APIVersion, + } +) diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go new file mode 100644 index 00000000000..b66471eb4ba --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_client_gen.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "context" + + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type LogsDrilldownDefaultColumnsClient struct { + client *resource.TypedClient[*LogsDrilldownDefaultColumns, *LogsDrilldownDefaultColumnsList] +} + +func NewLogsDrilldownDefaultColumnsClient(client resource.Client) *LogsDrilldownDefaultColumnsClient { + return &LogsDrilldownDefaultColumnsClient{ + client: resource.NewTypedClient[*LogsDrilldownDefaultColumns, *LogsDrilldownDefaultColumnsList](client, Kind()), + } +} + +func NewLogsDrilldownDefaultColumnsClientFromGenerator(generator resource.ClientGenerator) (*LogsDrilldownDefaultColumnsClient, error) { + c, err := generator.ClientFor(Kind()) + if err != nil { + return nil, err + } + return NewLogsDrilldownDefaultColumnsClient(c), nil +} + +func (c *LogsDrilldownDefaultColumnsClient) Get(ctx context.Context, identifier resource.Identifier) (*LogsDrilldownDefaultColumns, error) { + return c.client.Get(ctx, identifier) +} + +func (c *LogsDrilldownDefaultColumnsClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultColumnsList, error) { + return c.client.List(ctx, namespace, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultColumnsList, error) { + resp, err := c.client.List(ctx, namespace, resource.ListOptions{ + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + for resp.GetContinue() != "" { + page, err := c.client.List(ctx, namespace, resource.ListOptions{ + Continue: resp.GetContinue(), + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + resp.SetContinue(page.GetContinue()) + resp.SetResourceVersion(page.GetResourceVersion()) + resp.SetItems(append(resp.GetItems(), page.GetItems()...)) + } + return resp, nil +} + +func (c *LogsDrilldownDefaultColumnsClient) Create(ctx context.Context, obj *LogsDrilldownDefaultColumns, opts resource.CreateOptions) (*LogsDrilldownDefaultColumns, error) { + // Make sure apiVersion and kind are set + obj.APIVersion = GroupVersion.Identifier() + obj.Kind = Kind().Kind() + return c.client.Create(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) Update(ctx context.Context, obj *LogsDrilldownDefaultColumns, opts resource.UpdateOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Update(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Patch(ctx, identifier, req, opts) +} + +func (c *LogsDrilldownDefaultColumnsClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus Status, opts resource.UpdateOptions) (*LogsDrilldownDefaultColumns, error) { + return c.client.Update(ctx, &LogsDrilldownDefaultColumns{ + TypeMeta: metav1.TypeMeta{ + Kind: Kind().Kind(), + APIVersion: GroupVersion.Identifier(), + }, + ObjectMeta: metav1.ObjectMeta{ + ResourceVersion: opts.ResourceVersion, + Namespace: identifier.Namespace, + Name: identifier.Name, + }, + Status: newStatus, + }, resource.UpdateOptions{ + Subresource: "status", + ResourceVersion: opts.ResourceVersion, + }) +} + +func (c *LogsDrilldownDefaultColumnsClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { + return c.client.Delete(ctx, identifier, opts) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go new file mode 100644 index 00000000000..bb458caeb88 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_codec_gen.go @@ -0,0 +1,28 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "encoding/json" + "io" + + "github.com/grafana/grafana-app-sdk/resource" +) + +// JSONCodec is an implementation of resource.Codec for kubernetes JSON encoding +type JSONCodec struct{} + +// Read reads JSON-encoded bytes from `reader` and unmarshals them into `into` +func (*JSONCodec) Read(reader io.Reader, into resource.Object) error { + return json.NewDecoder(reader).Decode(into) +} + +// Write writes JSON-encoded bytes into `writer` marshaled from `from` +func (*JSONCodec) Write(writer io.Writer, from resource.Object) error { + return json.NewEncoder(writer).Encode(from) +} + +// Interface compliance checks +var _ resource.Codec = &JSONCodec{} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go new file mode 100644 index 00000000000..cb7233b22ab --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_metadata_gen.go @@ -0,0 +1,31 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +import ( + time "time" +) + +// metadata contains embedded CommonMetadata and can be extended with custom string fields +// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here +// without external reference as using the CommonMetadata reference breaks thema codegen. +type Metadata struct { + UpdateTimestamp time.Time `json:"updateTimestamp"` + CreatedBy string `json:"createdBy"` + Uid string `json:"uid"` + CreationTimestamp time.Time `json:"creationTimestamp"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` + Finalizers []string `json:"finalizers"` + ResourceVersion string `json:"resourceVersion"` + Generation int64 `json:"generation"` + UpdatedBy string `json:"updatedBy"` + Labels map[string]string `json:"labels"` +} + +// NewMetadata creates a new Metadata object. +func NewMetadata() *Metadata { + return &Metadata{ + Finalizers: []string{}, + Labels: map[string]string{}, + } +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go new file mode 100644 index 00000000000..3173c28330e --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.go @@ -0,0 +1,319 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "fmt" + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "time" +) + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumns struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ObjectMeta `json:"metadata" yaml:"metadata"` + + // Spec is the spec of the LogsDrilldownDefaultColumns + Spec Spec `json:"spec" yaml:"spec"` + + Status Status `json:"status" yaml:"status"` +} + +func (o *LogsDrilldownDefaultColumns) GetSpec() any { + return o.Spec +} + +func (o *LogsDrilldownDefaultColumns) SetSpec(spec any) error { + cast, ok := spec.(Spec) + if !ok { + return fmt.Errorf("cannot set spec type %#v, not of type Spec", spec) + } + o.Spec = cast + return nil +} + +func (o *LogsDrilldownDefaultColumns) GetSubresources() map[string]any { + return map[string]any{ + "status": o.Status, + } +} + +func (o *LogsDrilldownDefaultColumns) GetSubresource(name string) (any, bool) { + switch name { + case "status": + return o.Status, true + default: + return nil, false + } +} + +func (o *LogsDrilldownDefaultColumns) SetSubresource(name string, value any) error { + switch name { + case "status": + cast, ok := value.(Status) + if !ok { + return fmt.Errorf("cannot set status type %#v, not of type Status", value) + } + o.Status = cast + return nil + default: + return fmt.Errorf("subresource '%s' does not exist", name) + } +} + +func (o *LogsDrilldownDefaultColumns) GetStaticMetadata() resource.StaticMetadata { + gvk := o.GroupVersionKind() + return resource.StaticMetadata{ + Name: o.ObjectMeta.Name, + Namespace: o.ObjectMeta.Namespace, + Group: gvk.Group, + Version: gvk.Version, + Kind: gvk.Kind, + } +} + +func (o *LogsDrilldownDefaultColumns) SetStaticMetadata(metadata resource.StaticMetadata) { + o.Name = metadata.Name + o.Namespace = metadata.Namespace + o.SetGroupVersionKind(schema.GroupVersionKind{ + Group: metadata.Group, + Version: metadata.Version, + Kind: metadata.Kind, + }) +} + +func (o *LogsDrilldownDefaultColumns) GetCommonMetadata() resource.CommonMetadata { + dt := o.DeletionTimestamp + var deletionTimestamp *time.Time + if dt != nil { + deletionTimestamp = &dt.Time + } + // Legacy ExtraFields support + extraFields := make(map[string]any) + if o.Annotations != nil { + extraFields["annotations"] = o.Annotations + } + if o.ManagedFields != nil { + extraFields["managedFields"] = o.ManagedFields + } + if o.OwnerReferences != nil { + extraFields["ownerReferences"] = o.OwnerReferences + } + return resource.CommonMetadata{ + UID: string(o.UID), + ResourceVersion: o.ResourceVersion, + Generation: o.Generation, + Labels: o.Labels, + CreationTimestamp: o.CreationTimestamp.Time, + DeletionTimestamp: deletionTimestamp, + Finalizers: o.Finalizers, + UpdateTimestamp: o.GetUpdateTimestamp(), + CreatedBy: o.GetCreatedBy(), + UpdatedBy: o.GetUpdatedBy(), + ExtraFields: extraFields, + } +} + +func (o *LogsDrilldownDefaultColumns) SetCommonMetadata(metadata resource.CommonMetadata) { + o.UID = types.UID(metadata.UID) + o.ResourceVersion = metadata.ResourceVersion + o.Generation = metadata.Generation + o.Labels = metadata.Labels + o.CreationTimestamp = metav1.NewTime(metadata.CreationTimestamp) + if metadata.DeletionTimestamp != nil { + dt := metav1.NewTime(*metadata.DeletionTimestamp) + o.DeletionTimestamp = &dt + } else { + o.DeletionTimestamp = nil + } + o.Finalizers = metadata.Finalizers + if o.Annotations == nil { + o.Annotations = make(map[string]string) + } + if !metadata.UpdateTimestamp.IsZero() { + o.SetUpdateTimestamp(metadata.UpdateTimestamp) + } + if metadata.CreatedBy != "" { + o.SetCreatedBy(metadata.CreatedBy) + } + if metadata.UpdatedBy != "" { + o.SetUpdatedBy(metadata.UpdatedBy) + } + // Legacy support for setting Annotations, ManagedFields, and OwnerReferences via ExtraFields + if metadata.ExtraFields != nil { + if annotations, ok := metadata.ExtraFields["annotations"]; ok { + if cast, ok := annotations.(map[string]string); ok { + o.Annotations = cast + } + } + if managedFields, ok := metadata.ExtraFields["managedFields"]; ok { + if cast, ok := managedFields.([]metav1.ManagedFieldsEntry); ok { + o.ManagedFields = cast + } + } + if ownerReferences, ok := metadata.ExtraFields["ownerReferences"]; ok { + if cast, ok := ownerReferences.([]metav1.OwnerReference); ok { + o.OwnerReferences = cast + } + } + } +} + +func (o *LogsDrilldownDefaultColumns) GetCreatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/createdBy"] +} + +func (o *LogsDrilldownDefaultColumns) SetCreatedBy(createdBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/createdBy"] = createdBy +} + +func (o *LogsDrilldownDefaultColumns) GetUpdateTimestamp() time.Time { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + parsed, _ := time.Parse(time.RFC3339, o.ObjectMeta.Annotations["grafana.com/updateTimestamp"]) + return parsed +} + +func (o *LogsDrilldownDefaultColumns) SetUpdateTimestamp(updateTimestamp time.Time) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updateTimestamp"] = updateTimestamp.Format(time.RFC3339) +} + +func (o *LogsDrilldownDefaultColumns) GetUpdatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/updatedBy"] +} + +func (o *LogsDrilldownDefaultColumns) SetUpdatedBy(updatedBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updatedBy"] = updatedBy +} + +func (o *LogsDrilldownDefaultColumns) Copy() resource.Object { + return resource.CopyObject(o) +} + +func (o *LogsDrilldownDefaultColumns) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaultColumns) DeepCopy() *LogsDrilldownDefaultColumns { + cpy := &LogsDrilldownDefaultColumns{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaultColumns) DeepCopyInto(dst *LogsDrilldownDefaultColumns) { + dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion + dst.TypeMeta.Kind = o.TypeMeta.Kind + o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) + o.Spec.DeepCopyInto(&dst.Spec) + o.Status.DeepCopyInto(&dst.Status) +} + +// Interface compliance compile-time check +var _ resource.Object = &LogsDrilldownDefaultColumns{} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultColumnsList struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ListMeta `json:"metadata" yaml:"metadata"` + Items []LogsDrilldownDefaultColumns `json:"items" yaml:"items"` +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaultColumnsList) Copy() resource.ListObject { + cpy := &LogsDrilldownDefaultColumnsList{ + TypeMeta: o.TypeMeta, + Items: make([]LogsDrilldownDefaultColumns, len(o.Items)), + } + o.ListMeta.DeepCopyInto(&cpy.ListMeta) + for i := 0; i < len(o.Items); i++ { + if item, ok := o.Items[i].Copy().(*LogsDrilldownDefaultColumns); ok { + cpy.Items[i] = *item + } + } + return cpy +} + +func (o *LogsDrilldownDefaultColumnsList) GetItems() []resource.Object { + items := make([]resource.Object, len(o.Items)) + for i := 0; i < len(o.Items); i++ { + items[i] = &o.Items[i] + } + return items +} + +func (o *LogsDrilldownDefaultColumnsList) SetItems(items []resource.Object) { + o.Items = make([]LogsDrilldownDefaultColumns, len(items)) + for i := 0; i < len(items); i++ { + o.Items[i] = *items[i].(*LogsDrilldownDefaultColumns) + } +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopy() *LogsDrilldownDefaultColumnsList { + cpy := &LogsDrilldownDefaultColumnsList{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaultColumnsList) DeepCopyInto(dst *LogsDrilldownDefaultColumnsList) { + resource.CopyObjectInto(dst, o) +} + +// Interface compliance compile-time check +var _ resource.ListObject = &LogsDrilldownDefaultColumnsList{} + +// Copy methods for all subresource types + +// DeepCopy creates a full deep copy of Spec +func (s *Spec) DeepCopy() *Spec { + cpy := &Spec{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Spec into another Spec object +func (s *Spec) DeepCopyInto(dst *Spec) { + resource.CopyObjectInto(dst, s) +} + +// DeepCopy creates a full deep copy of Status +func (s *Status) DeepCopy() *Status { + cpy := &Status{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Status into another Status object +func (s *Status) DeepCopyInto(dst *Status) { + resource.CopyObjectInto(dst, s) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go new file mode 100644 index 00000000000..b50be391fc7 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_schema_gen.go @@ -0,0 +1,34 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" +) + +// schema is unexported to prevent accidental overwrites +var ( + schemaLogsDrilldownDefaultColumns = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", &LogsDrilldownDefaultColumns{}, &LogsDrilldownDefaultColumnsList{}, resource.WithKind("LogsDrilldownDefaultColumns"), + resource.WithPlural("logsdrilldowndefaultcolumns"), resource.WithScope(resource.NamespacedScope)) + kindLogsDrilldownDefaultColumns = resource.Kind{ + Schema: schemaLogsDrilldownDefaultColumns, + Codecs: map[resource.KindEncoding]resource.Codec{ + resource.KindEncodingJSON: &JSONCodec{}, + }, + } +) + +// Kind returns a resource.Kind for this Schema with a JSON codec +func Kind() resource.Kind { + return kindLogsDrilldownDefaultColumns +} + +// Schema returns a resource.SimpleSchema representation of LogsDrilldownDefaultColumns +func Schema() *resource.SimpleSchema { + return schemaLogsDrilldownDefaultColumns +} + +// Interface compliance checks +var _ resource.Schema = kindLogsDrilldownDefaultColumns diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go new file mode 100644 index 00000000000..d9cd977aeb9 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_spec_gen.go @@ -0,0 +1,43 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type LogsDefaultColumnsRecords []LogsDefaultColumnsRecord + +// +k8s:openapi-gen=true +type LogsDefaultColumnsRecord struct { + Columns []string `json:"columns"` + Labels LogsDefaultColumnsLabels `json:"labels"` +} + +// NewLogsDefaultColumnsRecord creates a new LogsDefaultColumnsRecord object. +func NewLogsDefaultColumnsRecord() *LogsDefaultColumnsRecord { + return &LogsDefaultColumnsRecord{ + Columns: []string{}, + } +} + +// +k8s:openapi-gen=true +type LogsDefaultColumnsLabels []LogsDefaultColumnsLabel + +// +k8s:openapi-gen=true +type LogsDefaultColumnsLabel struct { + Key string `json:"key"` + Value string `json:"value"` +} + +// NewLogsDefaultColumnsLabel creates a new LogsDefaultColumnsLabel object. +func NewLogsDefaultColumnsLabel() *LogsDefaultColumnsLabel { + return &LogsDefaultColumnsLabel{} +} + +// +k8s:openapi-gen=true +type Spec struct { + Records LogsDefaultColumnsRecords `json:"records"` +} + +// NewSpec creates a new Spec object. +func NewSpec() *Spec { + return &Spec{} +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go new file mode 100644 index 00000000000..9b227b00f44 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_status_gen.go @@ -0,0 +1,44 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type StatusOperatorState struct { + // lastEvaluation is the ResourceVersion last evaluated + LastEvaluation string `json:"lastEvaluation"` + // state describes the state of the lastEvaluation. + // It is limited to three possible states for machine evaluation. + State StatusOperatorStateState `json:"state"` + // descriptiveState is an optional more descriptive state field which has no requirements on format + DescriptiveState *string `json:"descriptiveState,omitempty"` + // details contains any extra information that is operator-specific + Details map[string]interface{} `json:"details,omitempty"` +} + +// NewStatusOperatorState creates a new StatusOperatorState object. +func NewStatusOperatorState() *StatusOperatorState { + return &StatusOperatorState{} +} + +// +k8s:openapi-gen=true +type Status struct { + // operatorStates is a map of operator ID to operator state evaluations. + // Any operator which consumes this kind SHOULD add its state evaluation information to this field. + OperatorStates map[string]StatusOperatorState `json:"operatorStates,omitempty"` + // additionalFields is reserved for future use + AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` +} + +// NewStatus creates a new Status object. +func NewStatus() *Status { + return &Status{} +} + +// +k8s:openapi-gen=true +type StatusOperatorStateState string + +const ( + StatusOperatorStateStateSuccess StatusOperatorStateState = "success" + StatusOperatorStateStateInProgress StatusOperatorStateState = "in_progress" + StatusOperatorStateStateFailed StatusOperatorStateState = "failed" +) diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/constants.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/constants.go new file mode 100644 index 00000000000..082bec7c874 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/constants.go @@ -0,0 +1,18 @@ +package v1alpha1 + +import "k8s.io/apimachinery/pkg/runtime/schema" + +const ( + // APIGroup is the API group used by all kinds in this package + APIGroup = "logsdrilldown.grafana.app" + // APIVersion is the API version used by all kinds in this package + APIVersion = "v1alpha1" +) + +var ( + // GroupVersion is a schema.GroupVersion consisting of the Group and Version constants for this package + GroupVersion = schema.GroupVersion{ + Group: APIGroup, + Version: APIVersion, + } +) diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_client_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_client_gen.go new file mode 100644 index 00000000000..cc06a10b1e7 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_client_gen.go @@ -0,0 +1,99 @@ +package v1alpha1 + +import ( + "context" + + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +type LogsDrilldownDefaultsClient struct { + client *resource.TypedClient[*LogsDrilldownDefaults, *LogsDrilldownDefaultsList] +} + +func NewLogsDrilldownDefaultsClient(client resource.Client) *LogsDrilldownDefaultsClient { + return &LogsDrilldownDefaultsClient{ + client: resource.NewTypedClient[*LogsDrilldownDefaults, *LogsDrilldownDefaultsList](client, Kind()), + } +} + +func NewLogsDrilldownDefaultsClientFromGenerator(generator resource.ClientGenerator) (*LogsDrilldownDefaultsClient, error) { + c, err := generator.ClientFor(Kind()) + if err != nil { + return nil, err + } + return NewLogsDrilldownDefaultsClient(c), nil +} + +func (c *LogsDrilldownDefaultsClient) Get(ctx context.Context, identifier resource.Identifier) (*LogsDrilldownDefaults, error) { + return c.client.Get(ctx, identifier) +} + +func (c *LogsDrilldownDefaultsClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultsList, error) { + return c.client.List(ctx, namespace, opts) +} + +func (c *LogsDrilldownDefaultsClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*LogsDrilldownDefaultsList, error) { + resp, err := c.client.List(ctx, namespace, resource.ListOptions{ + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + for resp.GetContinue() != "" { + page, err := c.client.List(ctx, namespace, resource.ListOptions{ + Continue: resp.GetContinue(), + ResourceVersion: opts.ResourceVersion, + Limit: opts.Limit, + LabelFilters: opts.LabelFilters, + FieldSelectors: opts.FieldSelectors, + }) + if err != nil { + return nil, err + } + resp.SetContinue(page.GetContinue()) + resp.SetResourceVersion(page.GetResourceVersion()) + resp.SetItems(append(resp.GetItems(), page.GetItems()...)) + } + return resp, nil +} + +func (c *LogsDrilldownDefaultsClient) Create(ctx context.Context, obj *LogsDrilldownDefaults, opts resource.CreateOptions) (*LogsDrilldownDefaults, error) { + // Make sure apiVersion and kind are set + obj.APIVersion = GroupVersion.Identifier() + obj.Kind = Kind().Kind() + return c.client.Create(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultsClient) Update(ctx context.Context, obj *LogsDrilldownDefaults, opts resource.UpdateOptions) (*LogsDrilldownDefaults, error) { + return c.client.Update(ctx, obj, opts) +} + +func (c *LogsDrilldownDefaultsClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*LogsDrilldownDefaults, error) { + return c.client.Patch(ctx, identifier, req, opts) +} + +func (c *LogsDrilldownDefaultsClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus Status, opts resource.UpdateOptions) (*LogsDrilldownDefaults, error) { + return c.client.Update(ctx, &LogsDrilldownDefaults{ + TypeMeta: metav1.TypeMeta{ + Kind: Kind().Kind(), + APIVersion: GroupVersion.Identifier(), + }, + ObjectMeta: metav1.ObjectMeta{ + ResourceVersion: opts.ResourceVersion, + Namespace: identifier.Namespace, + Name: identifier.Name, + }, + Status: newStatus, + }, resource.UpdateOptions{ + Subresource: "status", + ResourceVersion: opts.ResourceVersion, + }) +} + +func (c *LogsDrilldownDefaultsClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { + return c.client.Delete(ctx, identifier, opts) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_codec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_codec_gen.go new file mode 100644 index 00000000000..bb458caeb88 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_codec_gen.go @@ -0,0 +1,28 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "encoding/json" + "io" + + "github.com/grafana/grafana-app-sdk/resource" +) + +// JSONCodec is an implementation of resource.Codec for kubernetes JSON encoding +type JSONCodec struct{} + +// Read reads JSON-encoded bytes from `reader` and unmarshals them into `into` +func (*JSONCodec) Read(reader io.Reader, into resource.Object) error { + return json.NewDecoder(reader).Decode(into) +} + +// Write writes JSON-encoded bytes into `writer` marshaled from `from` +func (*JSONCodec) Write(writer io.Writer, from resource.Object) error { + return json.NewEncoder(writer).Encode(from) +} + +// Interface compliance checks +var _ resource.Codec = &JSONCodec{} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_metadata_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_metadata_gen.go new file mode 100644 index 00000000000..cb7233b22ab --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_metadata_gen.go @@ -0,0 +1,31 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +import ( + time "time" +) + +// metadata contains embedded CommonMetadata and can be extended with custom string fields +// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here +// without external reference as using the CommonMetadata reference breaks thema codegen. +type Metadata struct { + UpdateTimestamp time.Time `json:"updateTimestamp"` + CreatedBy string `json:"createdBy"` + Uid string `json:"uid"` + CreationTimestamp time.Time `json:"creationTimestamp"` + DeletionTimestamp *time.Time `json:"deletionTimestamp,omitempty"` + Finalizers []string `json:"finalizers"` + ResourceVersion string `json:"resourceVersion"` + Generation int64 `json:"generation"` + UpdatedBy string `json:"updatedBy"` + Labels map[string]string `json:"labels"` +} + +// NewMetadata creates a new Metadata object. +func NewMetadata() *Metadata { + return &Metadata{ + Finalizers: []string{}, + Labels: map[string]string{}, + } +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_object_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_object_gen.go new file mode 100644 index 00000000000..d9354522dd7 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_object_gen.go @@ -0,0 +1,319 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "fmt" + "github.com/grafana/grafana-app-sdk/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "time" +) + +// +k8s:openapi-gen=true +type LogsDrilldownDefaults struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ObjectMeta `json:"metadata" yaml:"metadata"` + + // Spec is the spec of the LogsDrilldownDefaults + Spec Spec `json:"spec" yaml:"spec"` + + Status Status `json:"status" yaml:"status"` +} + +func (o *LogsDrilldownDefaults) GetSpec() any { + return o.Spec +} + +func (o *LogsDrilldownDefaults) SetSpec(spec any) error { + cast, ok := spec.(Spec) + if !ok { + return fmt.Errorf("cannot set spec type %#v, not of type Spec", spec) + } + o.Spec = cast + return nil +} + +func (o *LogsDrilldownDefaults) GetSubresources() map[string]any { + return map[string]any{ + "status": o.Status, + } +} + +func (o *LogsDrilldownDefaults) GetSubresource(name string) (any, bool) { + switch name { + case "status": + return o.Status, true + default: + return nil, false + } +} + +func (o *LogsDrilldownDefaults) SetSubresource(name string, value any) error { + switch name { + case "status": + cast, ok := value.(Status) + if !ok { + return fmt.Errorf("cannot set status type %#v, not of type Status", value) + } + o.Status = cast + return nil + default: + return fmt.Errorf("subresource '%s' does not exist", name) + } +} + +func (o *LogsDrilldownDefaults) GetStaticMetadata() resource.StaticMetadata { + gvk := o.GroupVersionKind() + return resource.StaticMetadata{ + Name: o.ObjectMeta.Name, + Namespace: o.ObjectMeta.Namespace, + Group: gvk.Group, + Version: gvk.Version, + Kind: gvk.Kind, + } +} + +func (o *LogsDrilldownDefaults) SetStaticMetadata(metadata resource.StaticMetadata) { + o.Name = metadata.Name + o.Namespace = metadata.Namespace + o.SetGroupVersionKind(schema.GroupVersionKind{ + Group: metadata.Group, + Version: metadata.Version, + Kind: metadata.Kind, + }) +} + +func (o *LogsDrilldownDefaults) GetCommonMetadata() resource.CommonMetadata { + dt := o.DeletionTimestamp + var deletionTimestamp *time.Time + if dt != nil { + deletionTimestamp = &dt.Time + } + // Legacy ExtraFields support + extraFields := make(map[string]any) + if o.Annotations != nil { + extraFields["annotations"] = o.Annotations + } + if o.ManagedFields != nil { + extraFields["managedFields"] = o.ManagedFields + } + if o.OwnerReferences != nil { + extraFields["ownerReferences"] = o.OwnerReferences + } + return resource.CommonMetadata{ + UID: string(o.UID), + ResourceVersion: o.ResourceVersion, + Generation: o.Generation, + Labels: o.Labels, + CreationTimestamp: o.CreationTimestamp.Time, + DeletionTimestamp: deletionTimestamp, + Finalizers: o.Finalizers, + UpdateTimestamp: o.GetUpdateTimestamp(), + CreatedBy: o.GetCreatedBy(), + UpdatedBy: o.GetUpdatedBy(), + ExtraFields: extraFields, + } +} + +func (o *LogsDrilldownDefaults) SetCommonMetadata(metadata resource.CommonMetadata) { + o.UID = types.UID(metadata.UID) + o.ResourceVersion = metadata.ResourceVersion + o.Generation = metadata.Generation + o.Labels = metadata.Labels + o.CreationTimestamp = metav1.NewTime(metadata.CreationTimestamp) + if metadata.DeletionTimestamp != nil { + dt := metav1.NewTime(*metadata.DeletionTimestamp) + o.DeletionTimestamp = &dt + } else { + o.DeletionTimestamp = nil + } + o.Finalizers = metadata.Finalizers + if o.Annotations == nil { + o.Annotations = make(map[string]string) + } + if !metadata.UpdateTimestamp.IsZero() { + o.SetUpdateTimestamp(metadata.UpdateTimestamp) + } + if metadata.CreatedBy != "" { + o.SetCreatedBy(metadata.CreatedBy) + } + if metadata.UpdatedBy != "" { + o.SetUpdatedBy(metadata.UpdatedBy) + } + // Legacy support for setting Annotations, ManagedFields, and OwnerReferences via ExtraFields + if metadata.ExtraFields != nil { + if annotations, ok := metadata.ExtraFields["annotations"]; ok { + if cast, ok := annotations.(map[string]string); ok { + o.Annotations = cast + } + } + if managedFields, ok := metadata.ExtraFields["managedFields"]; ok { + if cast, ok := managedFields.([]metav1.ManagedFieldsEntry); ok { + o.ManagedFields = cast + } + } + if ownerReferences, ok := metadata.ExtraFields["ownerReferences"]; ok { + if cast, ok := ownerReferences.([]metav1.OwnerReference); ok { + o.OwnerReferences = cast + } + } + } +} + +func (o *LogsDrilldownDefaults) GetCreatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/createdBy"] +} + +func (o *LogsDrilldownDefaults) SetCreatedBy(createdBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/createdBy"] = createdBy +} + +func (o *LogsDrilldownDefaults) GetUpdateTimestamp() time.Time { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + parsed, _ := time.Parse(time.RFC3339, o.ObjectMeta.Annotations["grafana.com/updateTimestamp"]) + return parsed +} + +func (o *LogsDrilldownDefaults) SetUpdateTimestamp(updateTimestamp time.Time) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updateTimestamp"] = updateTimestamp.Format(time.RFC3339) +} + +func (o *LogsDrilldownDefaults) GetUpdatedBy() string { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + return o.ObjectMeta.Annotations["grafana.com/updatedBy"] +} + +func (o *LogsDrilldownDefaults) SetUpdatedBy(updatedBy string) { + if o.ObjectMeta.Annotations == nil { + o.ObjectMeta.Annotations = make(map[string]string) + } + + o.ObjectMeta.Annotations["grafana.com/updatedBy"] = updatedBy +} + +func (o *LogsDrilldownDefaults) Copy() resource.Object { + return resource.CopyObject(o) +} + +func (o *LogsDrilldownDefaults) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaults) DeepCopy() *LogsDrilldownDefaults { + cpy := &LogsDrilldownDefaults{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaults) DeepCopyInto(dst *LogsDrilldownDefaults) { + dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion + dst.TypeMeta.Kind = o.TypeMeta.Kind + o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) + o.Spec.DeepCopyInto(&dst.Spec) + o.Status.DeepCopyInto(&dst.Status) +} + +// Interface compliance compile-time check +var _ resource.Object = &LogsDrilldownDefaults{} + +// +k8s:openapi-gen=true +type LogsDrilldownDefaultsList struct { + metav1.TypeMeta `json:",inline" yaml:",inline"` + metav1.ListMeta `json:"metadata" yaml:"metadata"` + Items []LogsDrilldownDefaults `json:"items" yaml:"items"` +} + +func (o *LogsDrilldownDefaultsList) DeepCopyObject() runtime.Object { + return o.Copy() +} + +func (o *LogsDrilldownDefaultsList) Copy() resource.ListObject { + cpy := &LogsDrilldownDefaultsList{ + TypeMeta: o.TypeMeta, + Items: make([]LogsDrilldownDefaults, len(o.Items)), + } + o.ListMeta.DeepCopyInto(&cpy.ListMeta) + for i := 0; i < len(o.Items); i++ { + if item, ok := o.Items[i].Copy().(*LogsDrilldownDefaults); ok { + cpy.Items[i] = *item + } + } + return cpy +} + +func (o *LogsDrilldownDefaultsList) GetItems() []resource.Object { + items := make([]resource.Object, len(o.Items)) + for i := 0; i < len(o.Items); i++ { + items[i] = &o.Items[i] + } + return items +} + +func (o *LogsDrilldownDefaultsList) SetItems(items []resource.Object) { + o.Items = make([]LogsDrilldownDefaults, len(items)) + for i := 0; i < len(items); i++ { + o.Items[i] = *items[i].(*LogsDrilldownDefaults) + } +} + +func (o *LogsDrilldownDefaultsList) DeepCopy() *LogsDrilldownDefaultsList { + cpy := &LogsDrilldownDefaultsList{} + o.DeepCopyInto(cpy) + return cpy +} + +func (o *LogsDrilldownDefaultsList) DeepCopyInto(dst *LogsDrilldownDefaultsList) { + resource.CopyObjectInto(dst, o) +} + +// Interface compliance compile-time check +var _ resource.ListObject = &LogsDrilldownDefaultsList{} + +// Copy methods for all subresource types + +// DeepCopy creates a full deep copy of Spec +func (s *Spec) DeepCopy() *Spec { + cpy := &Spec{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Spec into another Spec object +func (s *Spec) DeepCopyInto(dst *Spec) { + resource.CopyObjectInto(dst, s) +} + +// DeepCopy creates a full deep copy of Status +func (s *Status) DeepCopy() *Status { + cpy := &Status{} + s.DeepCopyInto(cpy) + return cpy +} + +// DeepCopyInto deep copies Status into another Status object +func (s *Status) DeepCopyInto(dst *Status) { + resource.CopyObjectInto(dst, s) +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_schema_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_schema_gen.go new file mode 100644 index 00000000000..bda3e49377d --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_schema_gen.go @@ -0,0 +1,34 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v1alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" +) + +// schema is unexported to prevent accidental overwrites +var ( + schemaLogsDrilldownDefaults = resource.NewSimpleSchema("logsdrilldown.grafana.app", "v1alpha1", &LogsDrilldownDefaults{}, &LogsDrilldownDefaultsList{}, resource.WithKind("LogsDrilldownDefaults"), + resource.WithPlural("logsdrilldowndefaults"), resource.WithScope(resource.NamespacedScope)) + kindLogsDrilldownDefaults = resource.Kind{ + Schema: schemaLogsDrilldownDefaults, + Codecs: map[resource.KindEncoding]resource.Codec{ + resource.KindEncodingJSON: &JSONCodec{}, + }, + } +) + +// Kind returns a resource.Kind for this Schema with a JSON codec +func Kind() resource.Kind { + return kindLogsDrilldownDefaults +} + +// Schema returns a resource.SimpleSchema representation of LogsDrilldownDefaults +func Schema() *resource.SimpleSchema { + return schemaLogsDrilldownDefaults +} + +// Interface compliance checks +var _ resource.Schema = kindLogsDrilldownDefaults diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_spec_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_spec_gen.go new file mode 100644 index 00000000000..faff5c108dd --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_spec_gen.go @@ -0,0 +1,18 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type Spec struct { + DefaultFields []string `json:"defaultFields"` + PrettifyJSON bool `json:"prettifyJSON"` + WrapLogMessage bool `json:"wrapLogMessage"` + InterceptDismissed bool `json:"interceptDismissed"` +} + +// NewSpec creates a new Spec object. +func NewSpec() *Spec { + return &Spec{ + DefaultFields: []string{}, + } +} diff --git a/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_status_gen.go b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_status_gen.go new file mode 100644 index 00000000000..9b227b00f44 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1/logsdrilldowndefaults_status_gen.go @@ -0,0 +1,44 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v1alpha1 + +// +k8s:openapi-gen=true +type StatusOperatorState struct { + // lastEvaluation is the ResourceVersion last evaluated + LastEvaluation string `json:"lastEvaluation"` + // state describes the state of the lastEvaluation. + // It is limited to three possible states for machine evaluation. + State StatusOperatorStateState `json:"state"` + // descriptiveState is an optional more descriptive state field which has no requirements on format + DescriptiveState *string `json:"descriptiveState,omitempty"` + // details contains any extra information that is operator-specific + Details map[string]interface{} `json:"details,omitempty"` +} + +// NewStatusOperatorState creates a new StatusOperatorState object. +func NewStatusOperatorState() *StatusOperatorState { + return &StatusOperatorState{} +} + +// +k8s:openapi-gen=true +type Status struct { + // operatorStates is a map of operator ID to operator state evaluations. + // Any operator which consumes this kind SHOULD add its state evaluation information to this field. + OperatorStates map[string]StatusOperatorState `json:"operatorStates,omitempty"` + // additionalFields is reserved for future use + AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` +} + +// NewStatus creates a new Status object. +func NewStatus() *Status { + return &Status{} +} + +// +k8s:openapi-gen=true +type StatusOperatorStateState string + +const ( + StatusOperatorStateStateSuccess StatusOperatorStateState = "success" + StatusOperatorStateStateInProgress StatusOperatorStateState = "in_progress" + StatusOperatorStateStateFailed StatusOperatorStateState = "failed" +) diff --git a/apps/logsdrilldown/pkg/generated/manifestdata/logsdrilldown_manifest.go b/apps/logsdrilldown/pkg/generated/manifestdata/logsdrilldown_manifest.go new file mode 100644 index 00000000000..9deb5d5d3a1 --- /dev/null +++ b/apps/logsdrilldown/pkg/generated/manifestdata/logsdrilldown_manifest.go @@ -0,0 +1,150 @@ +// +// This file is generated by grafana-app-sdk +// DO NOT EDIT +// + +package manifestdata + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/grafana/grafana-app-sdk/app" + "github.com/grafana/grafana-app-sdk/resource" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/kube-openapi/pkg/spec3" + "k8s.io/kube-openapi/pkg/validation/spec" + + logsdrilldownv1alpha1 "github.com/grafana/grafana/apps/logsdrilldown/pkg/generated/logsdrilldown/v1alpha1" + logsdrilldowndefaultcolumnsv1alpha1 "github.com/grafana/grafana/apps/logsdrilldown/pkg/generated/logsdrilldowndefaultcolumns/v1alpha1" + logsdrilldowndefaultsv1alpha1 "github.com/grafana/grafana/apps/logsdrilldown/pkg/generated/logsdrilldowndefaults/v1alpha1" +) + +var ( + rawSchemaLogsDrilldownv1alpha1 = []byte(`{"LogsDrilldown":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownv1alpha1, &versionSchemaLogsDrilldownv1alpha1) + rawSchemaLogsDrilldownDefaultsv1alpha1 = []byte(`{"LogsDrilldownDefaults":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"defaultFields":{"items":{"type":"string"},"type":"array"},"interceptDismissed":{"type":"boolean"},"prettifyJSON":{"type":"boolean"},"wrapLogMessage":{"type":"boolean"}},"required":["defaultFields","prettifyJSON","wrapLogMessage","interceptDismissed"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownDefaultsv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownDefaultsv1alpha1, &versionSchemaLogsDrilldownDefaultsv1alpha1) + rawSchemaLogsDrilldownDefaultColumnsv1alpha1 = []byte(`{"LogsDefaultColumnsLabel":{"additionalProperties":false,"properties":{"key":{"type":"string"},"value":{"type":"string"}},"required":["key","value"],"type":"object"},"LogsDefaultColumnsLabels":{"items":{"$ref":"#/components/schemas/LogsDefaultColumnsLabel"},"type":"array"},"LogsDefaultColumnsRecord":{"additionalProperties":false,"properties":{"columns":{"items":{"type":"string"},"type":"array"},"labels":{"$ref":"#/components/schemas/LogsDefaultColumnsLabels"}},"required":["columns","labels"],"type":"object"},"LogsDefaultColumnsRecords":{"items":{"$ref":"#/components/schemas/LogsDefaultColumnsRecord"},"type":"array"},"LogsDrilldownDefaultColumns":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"spec":{"additionalProperties":false,"properties":{"records":{"$ref":"#/components/schemas/LogsDefaultColumnsRecords"}},"required":["records"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaLogsDrilldownDefaultColumnsv1alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaLogsDrilldownDefaultColumnsv1alpha1, &versionSchemaLogsDrilldownDefaultColumnsv1alpha1) +) + +var appManifestData = app.ManifestData{ + AppName: "logsdrilldown", + Group: "logsdrilldown.grafana.app", + PreferredVersion: "v1alpha1", + Versions: []app.ManifestVersion{ + { + Name: "v1alpha1", + Served: true, + Kinds: []app.ManifestVersionKind{ + { + Kind: "LogsDrilldown", + Plural: "LogsDrilldowns", + Scope: "Namespaced", + Conversion: false, + Schema: &versionSchemaLogsDrilldownv1alpha1, + }, + + { + Kind: "LogsDrilldownDefaults", + Plural: "LogsDrilldownDefaults", + Scope: "Namespaced", + Conversion: false, + Schema: &versionSchemaLogsDrilldownDefaultsv1alpha1, + }, + + { + Kind: "LogsDrilldownDefaultColumns", + Plural: "LogsDrilldownDefaultColumns", + Scope: "Namespaced", + Conversion: false, + Schema: &versionSchemaLogsDrilldownDefaultColumnsv1alpha1, + }, + }, + Routes: app.ManifestVersionRoutes{ + Namespaced: map[string]spec3.PathProps{}, + Cluster: map[string]spec3.PathProps{}, + Schemas: map[string]spec.Schema{}, + }, + }, + }, +} + +func LocalManifest() app.Manifest { + return app.NewEmbeddedManifest(appManifestData) +} + +func RemoteManifest() app.Manifest { + return app.NewAPIServerManifest("logsdrilldown") +} + +var kindVersionToGoType = map[string]resource.Kind{ + "LogsDrilldown/v1alpha1": logsdrilldownv1alpha1.Kind(), + "LogsDrilldownDefaults/v1alpha1": logsdrilldowndefaultsv1alpha1.Kind(), + "LogsDrilldownDefaultColumns/v1alpha1": logsdrilldowndefaultcolumnsv1alpha1.Kind(), +} + +// ManifestGoTypeAssociator returns the associated resource.Kind instance for a given Kind and Version, if one exists. +// If there is no association for the provided Kind and Version, exists will return false. +func ManifestGoTypeAssociator(kind, version string) (goType resource.Kind, exists bool) { + goType, exists = kindVersionToGoType[fmt.Sprintf("%s/%s", kind, version)] + return goType, exists +} + +var customRouteToGoResponseType = map[string]any{} + +// ManifestCustomRouteResponsesAssociator returns the associated response go type for a given kind, version, custom route path, and method, if one exists. +// kind may be empty for custom routes which are not kind subroutes. Leading slashes are removed from subroute paths. +// If there is no association for the provided kind, version, custom route path, and method, exists will return false. +// Resource routes (those without a kind) should prefix their route with "/" if the route is namespaced (otherwise the route is assumed to be cluster-scope) +func ManifestCustomRouteResponsesAssociator(kind, version, path, verb string) (goType any, exists bool) { + if len(path) > 0 && path[0] == '/' { + path = path[1:] + } + goType, exists = customRouteToGoResponseType[fmt.Sprintf("%s|%s|%s|%s", version, kind, path, strings.ToUpper(verb))] + return goType, exists +} + +var customRouteToGoParamsType = map[string]runtime.Object{} + +func ManifestCustomRouteQueryAssociator(kind, version, path, verb string) (goType runtime.Object, exists bool) { + if len(path) > 0 && path[0] == '/' { + path = path[1:] + } + goType, exists = customRouteToGoParamsType[fmt.Sprintf("%s|%s|%s|%s", version, kind, path, strings.ToUpper(verb))] + return goType, exists +} + +var customRouteToGoRequestBodyType = map[string]any{} + +func ManifestCustomRouteRequestBodyAssociator(kind, version, path, verb string) (goType any, exists bool) { + if len(path) > 0 && path[0] == '/' { + path = path[1:] + } + goType, exists = customRouteToGoRequestBodyType[fmt.Sprintf("%s|%s|%s|%s", version, kind, path, strings.ToUpper(verb))] + return goType, exists +} + +type GoTypeAssociator struct{} + +func NewGoTypeAssociator() *GoTypeAssociator { + return &GoTypeAssociator{} +} + +func (g *GoTypeAssociator) KindToGoType(kind, version string) (goType resource.Kind, exists bool) { + return ManifestGoTypeAssociator(kind, version) +} +func (g *GoTypeAssociator) CustomRouteReturnGoType(kind, version, path, verb string) (goType any, exists bool) { + return ManifestCustomRouteResponsesAssociator(kind, version, path, verb) +} +func (g *GoTypeAssociator) CustomRouteQueryGoType(kind, version, path, verb string) (goType runtime.Object, exists bool) { + return ManifestCustomRouteQueryAssociator(kind, version, path, verb) +} +func (g *GoTypeAssociator) CustomRouteRequestBodyGoType(kind, version, path, verb string) (goType any, exists bool) { + return ManifestCustomRouteRequestBodyAssociator(kind, version, path, verb) +} diff --git a/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.ts b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.ts new file mode 100644 index 00000000000..f7ba7b0f223 --- /dev/null +++ b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/logsdrilldowndefaultcolumns_object_gen.ts @@ -0,0 +1,49 @@ +/* + * This file was generated by grafana-app-sdk. DO NOT EDIT. + */ +import { Spec } from './types.spec.gen'; +import { Status } from './types.status.gen'; + +export interface Metadata { + name: string; + namespace: string; + generateName?: string; + selfLink?: string; + uid?: string; + resourceVersion?: string; + generation?: number; + creationTimestamp?: string; + deletionTimestamp?: string; + deletionGracePeriodSeconds?: number; + labels?: Record; + annotations?: Record; + ownerReferences?: OwnerReference[]; + finalizers?: string[]; + managedFields?: ManagedFieldsEntry[]; +} + +export interface OwnerReference { + apiVersion: string; + kind: string; + name: string; + uid: string; + controller?: boolean; + blockOwnerDeletion?: boolean; +} + +export interface ManagedFieldsEntry { + manager?: string; + operation?: string; + apiVersion?: string; + time?: string; + fieldsType?: string; + subresource?: string; +} + +export interface LogsDrilldownDefaultColumns { + kind: string; + apiVersion: string; + metadata: Metadata; + spec: Spec; + status: Status; +} diff --git a/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.metadata.gen.ts b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.metadata.gen.ts new file mode 100644 index 00000000000..4377f3c1d08 --- /dev/null +++ b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.metadata.gen.ts @@ -0,0 +1,30 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +// metadata contains embedded CommonMetadata and can be extended with custom string fields +// TODO: use CommonMetadata instead of redefining here; currently needs to be defined here +// without external reference as using the CommonMetadata reference breaks thema codegen. +export interface Metadata { + updateTimestamp: string; + createdBy: string; + uid: string; + creationTimestamp: string; + deletionTimestamp?: string; + finalizers: string[]; + resourceVersion: string; + generation: number; + updatedBy: string; + labels: Record; +} + +export const defaultMetadata = (): Metadata => ({ + updateTimestamp: "", + createdBy: "", + uid: "", + creationTimestamp: "", + finalizers: [], + resourceVersion: "", + generation: 0, + updatedBy: "", + labels: {}, +}); + diff --git a/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.spec.gen.ts b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.spec.gen.ts new file mode 100644 index 00000000000..fde99894776 --- /dev/null +++ b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.spec.gen.ts @@ -0,0 +1,38 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +export type LogsDefaultColumnsRecords = LogsDefaultColumnsRecord[]; + +export const defaultLogsDefaultColumnsRecords = (): LogsDefaultColumnsRecords => ([]); + +export interface LogsDefaultColumnsRecord { + columns: string[]; + labels: LogsDefaultColumnsLabels; +} + +export const defaultLogsDefaultColumnsRecord = (): LogsDefaultColumnsRecord => ({ + columns: [], + labels: defaultLogsDefaultColumnsLabels(), +}); + +export type LogsDefaultColumnsLabels = LogsDefaultColumnsLabel[]; + +export const defaultLogsDefaultColumnsLabels = (): LogsDefaultColumnsLabels => ([]); + +export interface LogsDefaultColumnsLabel { + key: string; + value: string; +} + +export const defaultLogsDefaultColumnsLabel = (): LogsDefaultColumnsLabel => ({ + key: "", + value: "", +}); + +export interface Spec { + records: LogsDefaultColumnsRecords; +} + +export const defaultSpec = (): Spec => ({ + records: defaultLogsDefaultColumnsRecords(), +}); + diff --git a/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.status.gen.ts b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.status.gen.ts new file mode 100644 index 00000000000..01be8df7961 --- /dev/null +++ b/apps/logsdrilldown/plugin/src/generated/logsdrilldowndefaultcolumns/v1alpha1/types.status.gen.ts @@ -0,0 +1,30 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +export interface OperatorState { + // lastEvaluation is the ResourceVersion last evaluated + lastEvaluation: string; + // state describes the state of the lastEvaluation. + // It is limited to three possible states for machine evaluation. + state: "success" | "in_progress" | "failed"; + // descriptiveState is an optional more descriptive state field which has no requirements on format + descriptiveState?: string; + // details contains any extra information that is operator-specific + details?: Record; +} + +export const defaultOperatorState = (): OperatorState => ({ + lastEvaluation: "", + state: "success", +}); + +export interface Status { + // operatorStates is a map of operator ID to operator state evaluations. + // Any operator which consumes this kind SHOULD add its state evaluation information to this field. + operatorStates?: Record; + // additionalFields is reserved for future use + additionalFields?: Record; +} + +export const defaultStatus = (): Status => ({ +}); + diff --git a/apps/plugins/go.mod b/apps/plugins/go.mod index 669c7c46844..5341081d027 100644 --- a/apps/plugins/go.mod +++ b/apps/plugins/go.mod @@ -10,11 +10,9 @@ replace github.com/grafana/grafana/pkg/apiserver => ../../pkg/apiserver require ( github.com/emicklei/go-restful/v3 v3.13.0 - github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 github.com/grafana/grafana v0.0.0-00010101000000-000000000000 github.com/grafana/grafana-app-sdk v0.48.5 github.com/grafana/grafana-app-sdk/logging v0.48.3 - github.com/grafana/grafana/pkg/apimachinery v0.0.0 github.com/stretchr/testify v1.11.1 k8s.io/apimachinery v0.34.2 k8s.io/apiserver v0.34.2 @@ -76,13 +74,15 @@ require ( github.com/google/gnostic-models v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba // indirect + github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 // indirect github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f // indirect + github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 // indirect github.com/grafana/dataplane/sdata v0.0.9 // indirect github.com/grafana/dskit v0.0.0-20250908063411-6b6da59b5cc4 // indirect github.com/grafana/grafana-aws-sdk v1.3.0 // indirect github.com/grafana/grafana-azure-sdk-go/v2 v2.3.1 // indirect github.com/grafana/grafana-plugin-sdk-go v0.284.0 // indirect + github.com/grafana/grafana/pkg/apimachinery 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.9 // indirect diff --git a/apps/plugins/go.sum b/apps/plugins/go.sum index 1d7387b28b3..7d58d87be04 100644 --- a/apps/plugins/go.sum +++ b/apps/plugins/go.sum @@ -174,8 +174,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba h1:psKWNETD5nGxmFAlqnWsXoRyUwSa2GHNEMSEDKGKfQ4= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 h1:ZzG/gCclEit9w0QUfQt9GURcOycAIGcsQAhY1u0AEX0= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f h1:Cbm6OKkOcJ+7CSZsGsEJzktC/SIa5bxVeYKQLuYK86o= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f/go.mod h1:axY0cdOg3q0TZHwpHnIz5x16xZ8ZBxJHShsSHHXcHQg= github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 h1:Muoy+FMGrHj3GdFbvsMzUT7eusgii9PKf9L1ZaXDDbY= diff --git a/apps/plugins/kinds/manifest.cue b/apps/plugins/kinds/manifest.cue index f9a08562cb0..f624dc117bc 100644 --- a/apps/plugins/kinds/manifest.cue +++ b/apps/plugins/kinds/manifest.cue @@ -16,6 +16,6 @@ v0alpha1Version: { } kinds: [ pluginV0Alpha1, - pluginMetaV0Alpha1, + metaV0Alpha1, ] } diff --git a/apps/plugins/kinds/pluginmeta.cue b/apps/plugins/kinds/meta.cue similarity index 98% rename from apps/plugins/kinds/pluginmeta.cue rename to apps/plugins/kinds/meta.cue index 03b1ff10ff2..34a7b9aaf12 100644 --- a/apps/plugins/kinds/pluginmeta.cue +++ b/apps/plugins/kinds/meta.cue @@ -1,8 +1,7 @@ package plugins -pluginMetaV0Alpha1: { - kind: "PluginMeta" - plural: "pluginsmeta" +metaV0Alpha1: { + kind: "Meta" scope: "Namespaced" schema: { spec: { diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_client_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_client_gen.go similarity index 50% rename from apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_client_gen.go rename to apps/plugins/pkg/apis/plugins/v0alpha1/meta_client_gen.go index e7788e27a33..4acc2b635e8 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_client_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_client_gen.go @@ -7,33 +7,33 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -type PluginMetaClient struct { - client *resource.TypedClient[*PluginMeta, *PluginMetaList] +type MetaClient struct { + client *resource.TypedClient[*Meta, *MetaList] } -func NewPluginMetaClient(client resource.Client) *PluginMetaClient { - return &PluginMetaClient{ - client: resource.NewTypedClient[*PluginMeta, *PluginMetaList](client, PluginMetaKind()), +func NewMetaClient(client resource.Client) *MetaClient { + return &MetaClient{ + client: resource.NewTypedClient[*Meta, *MetaList](client, MetaKind()), } } -func NewPluginMetaClientFromGenerator(generator resource.ClientGenerator) (*PluginMetaClient, error) { - c, err := generator.ClientFor(PluginMetaKind()) +func NewMetaClientFromGenerator(generator resource.ClientGenerator) (*MetaClient, error) { + c, err := generator.ClientFor(MetaKind()) if err != nil { return nil, err } - return NewPluginMetaClient(c), nil + return NewMetaClient(c), nil } -func (c *PluginMetaClient) Get(ctx context.Context, identifier resource.Identifier) (*PluginMeta, error) { +func (c *MetaClient) Get(ctx context.Context, identifier resource.Identifier) (*Meta, error) { return c.client.Get(ctx, identifier) } -func (c *PluginMetaClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*PluginMetaList, error) { +func (c *MetaClient) List(ctx context.Context, namespace string, opts resource.ListOptions) (*MetaList, error) { return c.client.List(ctx, namespace, opts) } -func (c *PluginMetaClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*PluginMetaList, error) { +func (c *MetaClient) ListAll(ctx context.Context, namespace string, opts resource.ListOptions) (*MetaList, error) { resp, err := c.client.List(ctx, namespace, resource.ListOptions{ ResourceVersion: opts.ResourceVersion, Limit: opts.Limit, @@ -61,25 +61,25 @@ func (c *PluginMetaClient) ListAll(ctx context.Context, namespace string, opts r return resp, nil } -func (c *PluginMetaClient) Create(ctx context.Context, obj *PluginMeta, opts resource.CreateOptions) (*PluginMeta, error) { +func (c *MetaClient) Create(ctx context.Context, obj *Meta, opts resource.CreateOptions) (*Meta, error) { // Make sure apiVersion and kind are set obj.APIVersion = GroupVersion.Identifier() - obj.Kind = PluginMetaKind().Kind() + obj.Kind = MetaKind().Kind() return c.client.Create(ctx, obj, opts) } -func (c *PluginMetaClient) Update(ctx context.Context, obj *PluginMeta, opts resource.UpdateOptions) (*PluginMeta, error) { +func (c *MetaClient) Update(ctx context.Context, obj *Meta, opts resource.UpdateOptions) (*Meta, error) { return c.client.Update(ctx, obj, opts) } -func (c *PluginMetaClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*PluginMeta, error) { +func (c *MetaClient) Patch(ctx context.Context, identifier resource.Identifier, req resource.PatchRequest, opts resource.PatchOptions) (*Meta, error) { return c.client.Patch(ctx, identifier, req, opts) } -func (c *PluginMetaClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus PluginMetaStatus, opts resource.UpdateOptions) (*PluginMeta, error) { - return c.client.Update(ctx, &PluginMeta{ +func (c *MetaClient) UpdateStatus(ctx context.Context, identifier resource.Identifier, newStatus MetaStatus, opts resource.UpdateOptions) (*Meta, error) { + return c.client.Update(ctx, &Meta{ TypeMeta: metav1.TypeMeta{ - Kind: PluginMetaKind().Kind(), + Kind: MetaKind().Kind(), APIVersion: GroupVersion.Identifier(), }, ObjectMeta: metav1.ObjectMeta{ @@ -94,6 +94,6 @@ func (c *PluginMetaClient) UpdateStatus(ctx context.Context, identifier resource }) } -func (c *PluginMetaClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { +func (c *MetaClient) Delete(ctx context.Context, identifier resource.Identifier, opts resource.DeleteOptions) error { return c.client.Delete(ctx, identifier, opts) } diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_codec_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_codec_gen.go similarity index 56% rename from apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_codec_gen.go rename to apps/plugins/pkg/apis/plugins/v0alpha1/meta_codec_gen.go index 77fb6f918a2..c152eb63e79 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_codec_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_codec_gen.go @@ -11,18 +11,18 @@ import ( "github.com/grafana/grafana-app-sdk/resource" ) -// PluginMetaJSONCodec is an implementation of resource.Codec for kubernetes JSON encoding -type PluginMetaJSONCodec struct{} +// MetaJSONCodec is an implementation of resource.Codec for kubernetes JSON encoding +type MetaJSONCodec struct{} // Read reads JSON-encoded bytes from `reader` and unmarshals them into `into` -func (*PluginMetaJSONCodec) Read(reader io.Reader, into resource.Object) error { +func (*MetaJSONCodec) Read(reader io.Reader, into resource.Object) error { return json.NewDecoder(reader).Decode(into) } // Write writes JSON-encoded bytes into `writer` marshaled from `from` -func (*PluginMetaJSONCodec) Write(writer io.Writer, from resource.Object) error { +func (*MetaJSONCodec) Write(writer io.Writer, from resource.Object) error { return json.NewEncoder(writer).Encode(from) } // Interface compliance checks -var _ resource.Codec = &PluginMetaJSONCodec{} +var _ resource.Codec = &MetaJSONCodec{} diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_metadata_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_metadata_gen.go similarity index 85% rename from apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_metadata_gen.go rename to apps/plugins/pkg/apis/plugins/v0alpha1/meta_metadata_gen.go index 7d3b3c9c6b8..9de0658352f 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_metadata_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_metadata_gen.go @@ -9,7 +9,7 @@ import ( // metadata contains embedded CommonMetadata and can be extended with custom string fields // TODO: use CommonMetadata instead of redefining here; currently needs to be defined here // without external reference as using the CommonMetadata reference breaks thema codegen. -type PluginMetaMetadata struct { +type MetaMetadata struct { UpdateTimestamp time.Time `json:"updateTimestamp"` CreatedBy string `json:"createdBy"` Uid string `json:"uid"` @@ -22,9 +22,9 @@ type PluginMetaMetadata struct { Labels map[string]string `json:"labels"` } -// NewPluginMetaMetadata creates a new PluginMetaMetadata object. -func NewPluginMetaMetadata() *PluginMetaMetadata { - return &PluginMetaMetadata{ +// NewMetaMetadata creates a new MetaMetadata object. +func NewMetaMetadata() *MetaMetadata { + return &MetaMetadata{ Finalizers: []string{}, Labels: map[string]string{}, } diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_object_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_object_gen.go similarity index 68% rename from apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_object_gen.go rename to apps/plugins/pkg/apis/plugins/v0alpha1/meta_object_gen.go index dac431ebf12..e42a1ad5d80 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_object_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_object_gen.go @@ -15,22 +15,29 @@ import ( ) // +k8s:openapi-gen=true -type PluginMeta struct { +type Meta struct { metav1.TypeMeta `json:",inline" yaml:",inline"` metav1.ObjectMeta `json:"metadata" yaml:"metadata"` - // Spec is the spec of the PluginMeta - Spec PluginMetaSpec `json:"spec" yaml:"spec"` + // Spec is the spec of the Meta + Spec MetaSpec `json:"spec" yaml:"spec"` - Status PluginMetaStatus `json:"status" yaml:"status"` + Status MetaStatus `json:"status" yaml:"status"` } -func (o *PluginMeta) GetSpec() any { +func NewMeta() *Meta { + return &Meta{ + Spec: *NewMetaSpec(), + Status: *NewMetaStatus(), + } +} + +func (o *Meta) GetSpec() any { return o.Spec } -func (o *PluginMeta) SetSpec(spec any) error { - cast, ok := spec.(PluginMetaSpec) +func (o *Meta) SetSpec(spec any) error { + cast, ok := spec.(MetaSpec) if !ok { return fmt.Errorf("cannot set spec type %#v, not of type Spec", spec) } @@ -38,13 +45,13 @@ func (o *PluginMeta) SetSpec(spec any) error { return nil } -func (o *PluginMeta) GetSubresources() map[string]any { +func (o *Meta) GetSubresources() map[string]any { return map[string]any{ "status": o.Status, } } -func (o *PluginMeta) GetSubresource(name string) (any, bool) { +func (o *Meta) GetSubresource(name string) (any, bool) { switch name { case "status": return o.Status, true @@ -53,12 +60,12 @@ func (o *PluginMeta) GetSubresource(name string) (any, bool) { } } -func (o *PluginMeta) SetSubresource(name string, value any) error { +func (o *Meta) SetSubresource(name string, value any) error { switch name { case "status": - cast, ok := value.(PluginMetaStatus) + cast, ok := value.(MetaStatus) if !ok { - return fmt.Errorf("cannot set status type %#v, not of type PluginMetaStatus", value) + return fmt.Errorf("cannot set status type %#v, not of type MetaStatus", value) } o.Status = cast return nil @@ -67,7 +74,7 @@ func (o *PluginMeta) SetSubresource(name string, value any) error { } } -func (o *PluginMeta) GetStaticMetadata() resource.StaticMetadata { +func (o *Meta) GetStaticMetadata() resource.StaticMetadata { gvk := o.GroupVersionKind() return resource.StaticMetadata{ Name: o.ObjectMeta.Name, @@ -78,7 +85,7 @@ func (o *PluginMeta) GetStaticMetadata() resource.StaticMetadata { } } -func (o *PluginMeta) SetStaticMetadata(metadata resource.StaticMetadata) { +func (o *Meta) SetStaticMetadata(metadata resource.StaticMetadata) { o.Name = metadata.Name o.Namespace = metadata.Namespace o.SetGroupVersionKind(schema.GroupVersionKind{ @@ -88,7 +95,7 @@ func (o *PluginMeta) SetStaticMetadata(metadata resource.StaticMetadata) { }) } -func (o *PluginMeta) GetCommonMetadata() resource.CommonMetadata { +func (o *Meta) GetCommonMetadata() resource.CommonMetadata { dt := o.DeletionTimestamp var deletionTimestamp *time.Time if dt != nil { @@ -120,7 +127,7 @@ func (o *PluginMeta) GetCommonMetadata() resource.CommonMetadata { } } -func (o *PluginMeta) SetCommonMetadata(metadata resource.CommonMetadata) { +func (o *Meta) SetCommonMetadata(metadata resource.CommonMetadata) { o.UID = types.UID(metadata.UID) o.ResourceVersion = metadata.ResourceVersion o.Generation = metadata.Generation @@ -165,7 +172,7 @@ func (o *PluginMeta) SetCommonMetadata(metadata resource.CommonMetadata) { } } -func (o *PluginMeta) GetCreatedBy() string { +func (o *Meta) GetCreatedBy() string { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -173,7 +180,7 @@ func (o *PluginMeta) GetCreatedBy() string { return o.ObjectMeta.Annotations["grafana.com/createdBy"] } -func (o *PluginMeta) SetCreatedBy(createdBy string) { +func (o *Meta) SetCreatedBy(createdBy string) { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -181,7 +188,7 @@ func (o *PluginMeta) SetCreatedBy(createdBy string) { o.ObjectMeta.Annotations["grafana.com/createdBy"] = createdBy } -func (o *PluginMeta) GetUpdateTimestamp() time.Time { +func (o *Meta) GetUpdateTimestamp() time.Time { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -190,7 +197,7 @@ func (o *PluginMeta) GetUpdateTimestamp() time.Time { return parsed } -func (o *PluginMeta) SetUpdateTimestamp(updateTimestamp time.Time) { +func (o *Meta) SetUpdateTimestamp(updateTimestamp time.Time) { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -198,7 +205,7 @@ func (o *PluginMeta) SetUpdateTimestamp(updateTimestamp time.Time) { o.ObjectMeta.Annotations["grafana.com/updateTimestamp"] = updateTimestamp.Format(time.RFC3339) } -func (o *PluginMeta) GetUpdatedBy() string { +func (o *Meta) GetUpdatedBy() string { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -206,7 +213,7 @@ func (o *PluginMeta) GetUpdatedBy() string { return o.ObjectMeta.Annotations["grafana.com/updatedBy"] } -func (o *PluginMeta) SetUpdatedBy(updatedBy string) { +func (o *Meta) SetUpdatedBy(updatedBy string) { if o.ObjectMeta.Annotations == nil { o.ObjectMeta.Annotations = make(map[string]string) } @@ -214,21 +221,21 @@ func (o *PluginMeta) SetUpdatedBy(updatedBy string) { o.ObjectMeta.Annotations["grafana.com/updatedBy"] = updatedBy } -func (o *PluginMeta) Copy() resource.Object { +func (o *Meta) Copy() resource.Object { return resource.CopyObject(o) } -func (o *PluginMeta) DeepCopyObject() runtime.Object { +func (o *Meta) DeepCopyObject() runtime.Object { return o.Copy() } -func (o *PluginMeta) DeepCopy() *PluginMeta { - cpy := &PluginMeta{} +func (o *Meta) DeepCopy() *Meta { + cpy := &Meta{} o.DeepCopyInto(cpy) return cpy } -func (o *PluginMeta) DeepCopyInto(dst *PluginMeta) { +func (o *Meta) DeepCopyInto(dst *Meta) { dst.TypeMeta.APIVersion = o.TypeMeta.APIVersion dst.TypeMeta.Kind = o.TypeMeta.Kind o.ObjectMeta.DeepCopyInto(&dst.ObjectMeta) @@ -237,34 +244,34 @@ func (o *PluginMeta) DeepCopyInto(dst *PluginMeta) { } // Interface compliance compile-time check -var _ resource.Object = &PluginMeta{} +var _ resource.Object = &Meta{} // +k8s:openapi-gen=true -type PluginMetaList struct { +type MetaList struct { metav1.TypeMeta `json:",inline" yaml:",inline"` metav1.ListMeta `json:"metadata" yaml:"metadata"` - Items []PluginMeta `json:"items" yaml:"items"` + Items []Meta `json:"items" yaml:"items"` } -func (o *PluginMetaList) DeepCopyObject() runtime.Object { +func (o *MetaList) DeepCopyObject() runtime.Object { return o.Copy() } -func (o *PluginMetaList) Copy() resource.ListObject { - cpy := &PluginMetaList{ +func (o *MetaList) Copy() resource.ListObject { + cpy := &MetaList{ TypeMeta: o.TypeMeta, - Items: make([]PluginMeta, len(o.Items)), + Items: make([]Meta, len(o.Items)), } o.ListMeta.DeepCopyInto(&cpy.ListMeta) for i := 0; i < len(o.Items); i++ { - if item, ok := o.Items[i].Copy().(*PluginMeta); ok { + if item, ok := o.Items[i].Copy().(*Meta); ok { cpy.Items[i] = *item } } return cpy } -func (o *PluginMetaList) GetItems() []resource.Object { +func (o *MetaList) GetItems() []resource.Object { items := make([]resource.Object, len(o.Items)) for i := 0; i < len(o.Items); i++ { items[i] = &o.Items[i] @@ -272,48 +279,48 @@ func (o *PluginMetaList) GetItems() []resource.Object { return items } -func (o *PluginMetaList) SetItems(items []resource.Object) { - o.Items = make([]PluginMeta, len(items)) +func (o *MetaList) SetItems(items []resource.Object) { + o.Items = make([]Meta, len(items)) for i := 0; i < len(items); i++ { - o.Items[i] = *items[i].(*PluginMeta) + o.Items[i] = *items[i].(*Meta) } } -func (o *PluginMetaList) DeepCopy() *PluginMetaList { - cpy := &PluginMetaList{} +func (o *MetaList) DeepCopy() *MetaList { + cpy := &MetaList{} o.DeepCopyInto(cpy) return cpy } -func (o *PluginMetaList) DeepCopyInto(dst *PluginMetaList) { +func (o *MetaList) DeepCopyInto(dst *MetaList) { resource.CopyObjectInto(dst, o) } // Interface compliance compile-time check -var _ resource.ListObject = &PluginMetaList{} +var _ resource.ListObject = &MetaList{} // Copy methods for all subresource types // DeepCopy creates a full deep copy of Spec -func (s *PluginMetaSpec) DeepCopy() *PluginMetaSpec { - cpy := &PluginMetaSpec{} +func (s *MetaSpec) DeepCopy() *MetaSpec { + cpy := &MetaSpec{} s.DeepCopyInto(cpy) return cpy } // DeepCopyInto deep copies Spec into another Spec object -func (s *PluginMetaSpec) DeepCopyInto(dst *PluginMetaSpec) { +func (s *MetaSpec) DeepCopyInto(dst *MetaSpec) { resource.CopyObjectInto(dst, s) } -// DeepCopy creates a full deep copy of PluginMetaStatus -func (s *PluginMetaStatus) DeepCopy() *PluginMetaStatus { - cpy := &PluginMetaStatus{} +// DeepCopy creates a full deep copy of MetaStatus +func (s *MetaStatus) DeepCopy() *MetaStatus { + cpy := &MetaStatus{} s.DeepCopyInto(cpy) return cpy } -// DeepCopyInto deep copies PluginMetaStatus into another PluginMetaStatus object -func (s *PluginMetaStatus) DeepCopyInto(dst *PluginMetaStatus) { +// DeepCopyInto deep copies MetaStatus into another MetaStatus object +func (s *MetaStatus) DeepCopyInto(dst *MetaStatus) { resource.CopyObjectInto(dst, s) } diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/meta_schema_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_schema_gen.go new file mode 100644 index 00000000000..38b45140ff6 --- /dev/null +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_schema_gen.go @@ -0,0 +1,34 @@ +// +// Code generated by grafana-app-sdk. DO NOT EDIT. +// + +package v0alpha1 + +import ( + "github.com/grafana/grafana-app-sdk/resource" +) + +// schema is unexported to prevent accidental overwrites +var ( + schemaMeta = resource.NewSimpleSchema("plugins.grafana.app", "v0alpha1", NewMeta(), &MetaList{}, resource.WithKind("Meta"), + resource.WithPlural("metas"), resource.WithScope(resource.NamespacedScope)) + kindMeta = resource.Kind{ + Schema: schemaMeta, + Codecs: map[resource.KindEncoding]resource.Codec{ + resource.KindEncodingJSON: &MetaJSONCodec{}, + }, + } +) + +// Kind returns a resource.Kind for this Schema with a JSON codec +func MetaKind() resource.Kind { + return kindMeta +} + +// Schema returns a resource.SimpleSchema representation of Meta +func MetaSchema() *resource.SimpleSchema { + return schemaMeta +} + +// Interface compliance checks +var _ resource.Schema = kindMeta diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/meta_spec_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_spec_gen.go new file mode 100644 index 00000000000..9598da22ef7 --- /dev/null +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_spec_gen.go @@ -0,0 +1,474 @@ +// Code generated - EDITING IS FUTILE. DO NOT EDIT. + +package v0alpha1 + +// JSON configuration schema for Grafana plugins +// Converted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json +// +k8s:openapi-gen=true +type MetaJSONData struct { + // Unique name of the plugin + Id string `json:"id"` + // Plugin type + Type MetaJSONDataType `json:"type"` + // Human-readable name of the plugin + Name string `json:"name"` + // Metadata for the plugin + Info MetaInfo `json:"info"` + // Dependency information + Dependencies MetaDependencies `json:"dependencies"` + // Optional fields + Alerting *bool `json:"alerting,omitempty"` + Annotations *bool `json:"annotations,omitempty"` + AutoEnabled *bool `json:"autoEnabled,omitempty"` + Backend *bool `json:"backend,omitempty"` + BuildMode *string `json:"buildMode,omitempty"` + BuiltIn *bool `json:"builtIn,omitempty"` + Category *MetaJSONDataCategory `json:"category,omitempty"` + EnterpriseFeatures *MetaEnterpriseFeatures `json:"enterpriseFeatures,omitempty"` + Executable *string `json:"executable,omitempty"` + HideFromList *bool `json:"hideFromList,omitempty"` + // +listType=atomic + Includes []MetaInclude `json:"includes,omitempty"` + Logs *bool `json:"logs,omitempty"` + Metrics *bool `json:"metrics,omitempty"` + MultiValueFilterOperators *bool `json:"multiValueFilterOperators,omitempty"` + PascalName *string `json:"pascalName,omitempty"` + Preload *bool `json:"preload,omitempty"` + QueryOptions *MetaQueryOptions `json:"queryOptions,omitempty"` + // +listType=atomic + Routes []MetaRoute `json:"routes,omitempty"` + SkipDataQuery *bool `json:"skipDataQuery,omitempty"` + State *MetaJSONDataState `json:"state,omitempty"` + Streaming *bool `json:"streaming,omitempty"` + Suggestions *bool `json:"suggestions,omitempty"` + Tracing *bool `json:"tracing,omitempty"` + Iam *MetaIAM `json:"iam,omitempty"` + // +listType=atomic + Roles []MetaRole `json:"roles,omitempty"` + Extensions *MetaExtensions `json:"extensions,omitempty"` +} + +// NewMetaJSONData creates a new MetaJSONData object. +func NewMetaJSONData() *MetaJSONData { + return &MetaJSONData{ + Info: *NewMetaInfo(), + Dependencies: *NewMetaDependencies(), + } +} + +// +k8s:openapi-gen=true +type MetaInfo struct { + // Required fields + // +listType=set + Keywords []string `json:"keywords"` + Logos MetaV0alpha1InfoLogos `json:"logos"` + Updated string `json:"updated"` + Version string `json:"version"` + // Optional fields + Author *MetaV0alpha1InfoAuthor `json:"author,omitempty"` + Description *string `json:"description,omitempty"` + // +listType=atomic + Links []MetaV0alpha1InfoLinks `json:"links,omitempty"` + // +listType=atomic + Screenshots []MetaV0alpha1InfoScreenshots `json:"screenshots,omitempty"` +} + +// NewMetaInfo creates a new MetaInfo object. +func NewMetaInfo() *MetaInfo { + return &MetaInfo{ + Keywords: []string{}, + Logos: *NewMetaV0alpha1InfoLogos(), + } +} + +// +k8s:openapi-gen=true +type MetaDependencies struct { + // Required field + GrafanaDependency string `json:"grafanaDependency"` + // Optional fields + GrafanaVersion *string `json:"grafanaVersion,omitempty"` + // +listType=set + // +listMapKey=id + Plugins []MetaV0alpha1DependenciesPlugins `json:"plugins,omitempty"` + Extensions *MetaV0alpha1DependenciesExtensions `json:"extensions,omitempty"` +} + +// NewMetaDependencies creates a new MetaDependencies object. +func NewMetaDependencies() *MetaDependencies { + return &MetaDependencies{} +} + +// +k8s:openapi-gen=true +type MetaEnterpriseFeatures struct { + // Allow additional properties + HealthDiagnosticsErrors *bool `json:"healthDiagnosticsErrors,omitempty"` +} + +// NewMetaEnterpriseFeatures creates a new MetaEnterpriseFeatures object. +func NewMetaEnterpriseFeatures() *MetaEnterpriseFeatures { + return &MetaEnterpriseFeatures{ + HealthDiagnosticsErrors: (func(input bool) *bool { return &input })(false), + } +} + +// +k8s:openapi-gen=true +type MetaInclude struct { + Uid *string `json:"uid,omitempty"` + Type *MetaIncludeType `json:"type,omitempty"` + Name *string `json:"name,omitempty"` + Component *string `json:"component,omitempty"` + Role *MetaIncludeRole `json:"role,omitempty"` + Action *string `json:"action,omitempty"` + Path *string `json:"path,omitempty"` + AddToNav *bool `json:"addToNav,omitempty"` + DefaultNav *bool `json:"defaultNav,omitempty"` + Icon *string `json:"icon,omitempty"` +} + +// NewMetaInclude creates a new MetaInclude object. +func NewMetaInclude() *MetaInclude { + return &MetaInclude{} +} + +// +k8s:openapi-gen=true +type MetaQueryOptions struct { + MaxDataPoints *bool `json:"maxDataPoints,omitempty"` + MinInterval *bool `json:"minInterval,omitempty"` + CacheTimeout *bool `json:"cacheTimeout,omitempty"` +} + +// NewMetaQueryOptions creates a new MetaQueryOptions object. +func NewMetaQueryOptions() *MetaQueryOptions { + return &MetaQueryOptions{} +} + +// +k8s:openapi-gen=true +type MetaRoute struct { + Path *string `json:"path,omitempty"` + Method *string `json:"method,omitempty"` + Url *string `json:"url,omitempty"` + ReqSignedIn *bool `json:"reqSignedIn,omitempty"` + ReqRole *string `json:"reqRole,omitempty"` + ReqAction *string `json:"reqAction,omitempty"` + // +listType=atomic + Headers []string `json:"headers,omitempty"` + Body map[string]interface{} `json:"body,omitempty"` + TokenAuth *MetaV0alpha1RouteTokenAuth `json:"tokenAuth,omitempty"` + JwtTokenAuth *MetaV0alpha1RouteJwtTokenAuth `json:"jwtTokenAuth,omitempty"` + // +listType=atomic + UrlParams []MetaV0alpha1RouteUrlParams `json:"urlParams,omitempty"` +} + +// NewMetaRoute creates a new MetaRoute object. +func NewMetaRoute() *MetaRoute { + return &MetaRoute{} +} + +// +k8s:openapi-gen=true +type MetaIAM struct { + // +listType=atomic + Permissions []MetaV0alpha1IAMPermissions `json:"permissions,omitempty"` +} + +// NewMetaIAM creates a new MetaIAM object. +func NewMetaIAM() *MetaIAM { + return &MetaIAM{} +} + +// +k8s:openapi-gen=true +type MetaRole struct { + Role *MetaV0alpha1RoleRole `json:"role,omitempty"` + // +listType=set + Grants []string `json:"grants,omitempty"` +} + +// NewMetaRole creates a new MetaRole object. +func NewMetaRole() *MetaRole { + return &MetaRole{} +} + +// +k8s:openapi-gen=true +type MetaExtensions struct { + // +listType=atomic + AddedComponents []MetaV0alpha1ExtensionsAddedComponents `json:"addedComponents,omitempty"` + // +listType=atomic + AddedLinks []MetaV0alpha1ExtensionsAddedLinks `json:"addedLinks,omitempty"` + // +listType=set + // +listMapKey=id + ExposedComponents []MetaV0alpha1ExtensionsExposedComponents `json:"exposedComponents,omitempty"` + // +listType=set + // +listMapKey=id + ExtensionPoints []MetaV0alpha1ExtensionsExtensionPoints `json:"extensionPoints,omitempty"` +} + +// NewMetaExtensions creates a new MetaExtensions object. +func NewMetaExtensions() *MetaExtensions { + return &MetaExtensions{} +} + +// +k8s:openapi-gen=true +type MetaSpec struct { + PluginJSON MetaJSONData `json:"pluginJSON"` +} + +// NewMetaSpec creates a new MetaSpec object. +func NewMetaSpec() *MetaSpec { + return &MetaSpec{ + PluginJSON: *NewMetaJSONData(), + } +} + +// +k8s:openapi-gen=true +type MetaV0alpha1InfoLogos struct { + Small string `json:"small"` + Large string `json:"large"` +} + +// NewMetaV0alpha1InfoLogos creates a new MetaV0alpha1InfoLogos object. +func NewMetaV0alpha1InfoLogos() *MetaV0alpha1InfoLogos { + return &MetaV0alpha1InfoLogos{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1InfoAuthor struct { + Name *string `json:"name,omitempty"` + Email *string `json:"email,omitempty"` + Url *string `json:"url,omitempty"` +} + +// NewMetaV0alpha1InfoAuthor creates a new MetaV0alpha1InfoAuthor object. +func NewMetaV0alpha1InfoAuthor() *MetaV0alpha1InfoAuthor { + return &MetaV0alpha1InfoAuthor{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1InfoLinks struct { + Name *string `json:"name,omitempty"` + Url *string `json:"url,omitempty"` +} + +// NewMetaV0alpha1InfoLinks creates a new MetaV0alpha1InfoLinks object. +func NewMetaV0alpha1InfoLinks() *MetaV0alpha1InfoLinks { + return &MetaV0alpha1InfoLinks{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1InfoScreenshots struct { + Name *string `json:"name,omitempty"` + Path *string `json:"path,omitempty"` +} + +// NewMetaV0alpha1InfoScreenshots creates a new MetaV0alpha1InfoScreenshots object. +func NewMetaV0alpha1InfoScreenshots() *MetaV0alpha1InfoScreenshots { + return &MetaV0alpha1InfoScreenshots{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1DependenciesPlugins struct { + Id string `json:"id"` + Type MetaV0alpha1DependenciesPluginsType `json:"type"` + Name string `json:"name"` +} + +// NewMetaV0alpha1DependenciesPlugins creates a new MetaV0alpha1DependenciesPlugins object. +func NewMetaV0alpha1DependenciesPlugins() *MetaV0alpha1DependenciesPlugins { + return &MetaV0alpha1DependenciesPlugins{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1DependenciesExtensions struct { + // +listType=set + ExposedComponents []string `json:"exposedComponents,omitempty"` +} + +// NewMetaV0alpha1DependenciesExtensions creates a new MetaV0alpha1DependenciesExtensions object. +func NewMetaV0alpha1DependenciesExtensions() *MetaV0alpha1DependenciesExtensions { + return &MetaV0alpha1DependenciesExtensions{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1RouteTokenAuth struct { + Url *string `json:"url,omitempty"` + // +listType=set + Scopes []string `json:"scopes,omitempty"` + Params map[string]interface{} `json:"params,omitempty"` +} + +// NewMetaV0alpha1RouteTokenAuth creates a new MetaV0alpha1RouteTokenAuth object. +func NewMetaV0alpha1RouteTokenAuth() *MetaV0alpha1RouteTokenAuth { + return &MetaV0alpha1RouteTokenAuth{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1RouteJwtTokenAuth struct { + Url *string `json:"url,omitempty"` + // +listType=set + Scopes []string `json:"scopes,omitempty"` + Params map[string]interface{} `json:"params,omitempty"` +} + +// NewMetaV0alpha1RouteJwtTokenAuth creates a new MetaV0alpha1RouteJwtTokenAuth object. +func NewMetaV0alpha1RouteJwtTokenAuth() *MetaV0alpha1RouteJwtTokenAuth { + return &MetaV0alpha1RouteJwtTokenAuth{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1RouteUrlParams struct { + Name *string `json:"name,omitempty"` + Content *string `json:"content,omitempty"` +} + +// NewMetaV0alpha1RouteUrlParams creates a new MetaV0alpha1RouteUrlParams object. +func NewMetaV0alpha1RouteUrlParams() *MetaV0alpha1RouteUrlParams { + return &MetaV0alpha1RouteUrlParams{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1IAMPermissions struct { + Action *string `json:"action,omitempty"` + Scope *string `json:"scope,omitempty"` +} + +// NewMetaV0alpha1IAMPermissions creates a new MetaV0alpha1IAMPermissions object. +func NewMetaV0alpha1IAMPermissions() *MetaV0alpha1IAMPermissions { + return &MetaV0alpha1IAMPermissions{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1RoleRolePermissions struct { + Action *string `json:"action,omitempty"` + Scope *string `json:"scope,omitempty"` +} + +// NewMetaV0alpha1RoleRolePermissions creates a new MetaV0alpha1RoleRolePermissions object. +func NewMetaV0alpha1RoleRolePermissions() *MetaV0alpha1RoleRolePermissions { + return &MetaV0alpha1RoleRolePermissions{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1RoleRole struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + // +listType=atomic + Permissions []MetaV0alpha1RoleRolePermissions `json:"permissions,omitempty"` +} + +// NewMetaV0alpha1RoleRole creates a new MetaV0alpha1RoleRole object. +func NewMetaV0alpha1RoleRole() *MetaV0alpha1RoleRole { + return &MetaV0alpha1RoleRole{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1ExtensionsAddedComponents struct { + // +listType=set + Targets []string `json:"targets"` + Title string `json:"title"` + Description *string `json:"description,omitempty"` +} + +// NewMetaV0alpha1ExtensionsAddedComponents creates a new MetaV0alpha1ExtensionsAddedComponents object. +func NewMetaV0alpha1ExtensionsAddedComponents() *MetaV0alpha1ExtensionsAddedComponents { + return &MetaV0alpha1ExtensionsAddedComponents{ + Targets: []string{}, + } +} + +// +k8s:openapi-gen=true +type MetaV0alpha1ExtensionsAddedLinks struct { + // +listType=set + Targets []string `json:"targets"` + Title string `json:"title"` + Description *string `json:"description,omitempty"` +} + +// NewMetaV0alpha1ExtensionsAddedLinks creates a new MetaV0alpha1ExtensionsAddedLinks object. +func NewMetaV0alpha1ExtensionsAddedLinks() *MetaV0alpha1ExtensionsAddedLinks { + return &MetaV0alpha1ExtensionsAddedLinks{ + Targets: []string{}, + } +} + +// +k8s:openapi-gen=true +type MetaV0alpha1ExtensionsExposedComponents struct { + Id string `json:"id"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` +} + +// NewMetaV0alpha1ExtensionsExposedComponents creates a new MetaV0alpha1ExtensionsExposedComponents object. +func NewMetaV0alpha1ExtensionsExposedComponents() *MetaV0alpha1ExtensionsExposedComponents { + return &MetaV0alpha1ExtensionsExposedComponents{} +} + +// +k8s:openapi-gen=true +type MetaV0alpha1ExtensionsExtensionPoints struct { + Id string `json:"id"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` +} + +// NewMetaV0alpha1ExtensionsExtensionPoints creates a new MetaV0alpha1ExtensionsExtensionPoints object. +func NewMetaV0alpha1ExtensionsExtensionPoints() *MetaV0alpha1ExtensionsExtensionPoints { + return &MetaV0alpha1ExtensionsExtensionPoints{} +} + +// +k8s:openapi-gen=true +type MetaJSONDataType string + +const ( + MetaJSONDataTypeApp MetaJSONDataType = "app" + MetaJSONDataTypeDatasource MetaJSONDataType = "datasource" + MetaJSONDataTypePanel MetaJSONDataType = "panel" + MetaJSONDataTypeRenderer MetaJSONDataType = "renderer" +) + +// +k8s:openapi-gen=true +type MetaJSONDataCategory string + +const ( + MetaJSONDataCategoryTsdb MetaJSONDataCategory = "tsdb" + MetaJSONDataCategoryLogging MetaJSONDataCategory = "logging" + MetaJSONDataCategoryCloud MetaJSONDataCategory = "cloud" + MetaJSONDataCategoryTracing MetaJSONDataCategory = "tracing" + MetaJSONDataCategoryProfiling MetaJSONDataCategory = "profiling" + MetaJSONDataCategorySql MetaJSONDataCategory = "sql" + MetaJSONDataCategoryEnterprise MetaJSONDataCategory = "enterprise" + MetaJSONDataCategoryIot MetaJSONDataCategory = "iot" + MetaJSONDataCategoryOther MetaJSONDataCategory = "other" +) + +// +k8s:openapi-gen=true +type MetaJSONDataState string + +const ( + MetaJSONDataStateAlpha MetaJSONDataState = "alpha" + MetaJSONDataStateBeta MetaJSONDataState = "beta" +) + +// +k8s:openapi-gen=true +type MetaIncludeType string + +const ( + MetaIncludeTypeDashboard MetaIncludeType = "dashboard" + MetaIncludeTypePage MetaIncludeType = "page" + MetaIncludeTypePanel MetaIncludeType = "panel" + MetaIncludeTypeDatasource MetaIncludeType = "datasource" +) + +// +k8s:openapi-gen=true +type MetaIncludeRole string + +const ( + MetaIncludeRoleAdmin MetaIncludeRole = "Admin" + MetaIncludeRoleEditor MetaIncludeRole = "Editor" + MetaIncludeRoleViewer MetaIncludeRole = "Viewer" +) + +// +k8s:openapi-gen=true +type MetaV0alpha1DependenciesPluginsType string + +const ( + MetaV0alpha1DependenciesPluginsTypeApp MetaV0alpha1DependenciesPluginsType = "app" + MetaV0alpha1DependenciesPluginsTypeDatasource MetaV0alpha1DependenciesPluginsType = "datasource" + MetaV0alpha1DependenciesPluginsTypePanel MetaV0alpha1DependenciesPluginsType = "panel" +) diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_status_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_status_gen.go similarity index 52% rename from apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_status_gen.go rename to apps/plugins/pkg/apis/plugins/v0alpha1/meta_status_gen.go index 60fa37dbb32..5f37ac58fb7 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_status_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/meta_status_gen.go @@ -3,42 +3,42 @@ package v0alpha1 // +k8s:openapi-gen=true -type PluginMetastatusOperatorState struct { +type MetastatusOperatorState struct { // lastEvaluation is the ResourceVersion last evaluated LastEvaluation string `json:"lastEvaluation"` // state describes the state of the lastEvaluation. // It is limited to three possible states for machine evaluation. - State PluginMetaStatusOperatorStateState `json:"state"` + State MetaStatusOperatorStateState `json:"state"` // descriptiveState is an optional more descriptive state field which has no requirements on format DescriptiveState *string `json:"descriptiveState,omitempty"` // details contains any extra information that is operator-specific Details map[string]interface{} `json:"details,omitempty"` } -// NewPluginMetastatusOperatorState creates a new PluginMetastatusOperatorState object. -func NewPluginMetastatusOperatorState() *PluginMetastatusOperatorState { - return &PluginMetastatusOperatorState{} +// NewMetastatusOperatorState creates a new MetastatusOperatorState object. +func NewMetastatusOperatorState() *MetastatusOperatorState { + return &MetastatusOperatorState{} } // +k8s:openapi-gen=true -type PluginMetaStatus struct { +type MetaStatus struct { // operatorStates is a map of operator ID to operator state evaluations. // Any operator which consumes this kind SHOULD add its state evaluation information to this field. - OperatorStates map[string]PluginMetastatusOperatorState `json:"operatorStates,omitempty"` + OperatorStates map[string]MetastatusOperatorState `json:"operatorStates,omitempty"` // additionalFields is reserved for future use AdditionalFields map[string]interface{} `json:"additionalFields,omitempty"` } -// NewPluginMetaStatus creates a new PluginMetaStatus object. -func NewPluginMetaStatus() *PluginMetaStatus { - return &PluginMetaStatus{} +// NewMetaStatus creates a new MetaStatus object. +func NewMetaStatus() *MetaStatus { + return &MetaStatus{} } // +k8s:openapi-gen=true -type PluginMetaStatusOperatorStateState string +type MetaStatusOperatorStateState string const ( - PluginMetaStatusOperatorStateStateSuccess PluginMetaStatusOperatorStateState = "success" - PluginMetaStatusOperatorStateStateInProgress PluginMetaStatusOperatorStateState = "in_progress" - PluginMetaStatusOperatorStateStateFailed PluginMetaStatusOperatorStateState = "failed" + MetaStatusOperatorStateStateSuccess MetaStatusOperatorStateState = "success" + MetaStatusOperatorStateStateInProgress MetaStatusOperatorStateState = "in_progress" + MetaStatusOperatorStateStateFailed MetaStatusOperatorStateState = "failed" ) diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_object_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_object_gen.go index d2cdedba399..b92b11f4cba 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_object_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_object_gen.go @@ -25,6 +25,13 @@ type Plugin struct { Status PluginStatus `json:"status" yaml:"status"` } +func NewPlugin() *Plugin { + return &Plugin{ + Spec: *NewPluginSpec(), + Status: *NewPluginStatus(), + } +} + func (o *Plugin) GetSpec() any { return o.Spec } diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_schema_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_schema_gen.go index 97024275a1c..144ddd5af89 100644 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_schema_gen.go +++ b/apps/plugins/pkg/apis/plugins/v0alpha1/plugin_schema_gen.go @@ -10,7 +10,7 @@ import ( // schema is unexported to prevent accidental overwrites var ( - schemaPlugin = resource.NewSimpleSchema("plugins.grafana.app", "v0alpha1", &Plugin{}, &PluginList{}, resource.WithKind("Plugin"), + schemaPlugin = resource.NewSimpleSchema("plugins.grafana.app", "v0alpha1", NewPlugin(), &PluginList{}, resource.WithKind("Plugin"), resource.WithPlural("plugins"), resource.WithScope(resource.NamespacedScope)) kindPlugin = resource.Kind{ Schema: schemaPlugin, diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_schema_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_schema_gen.go deleted file mode 100644 index a4022c8de97..00000000000 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_schema_gen.go +++ /dev/null @@ -1,34 +0,0 @@ -// -// Code generated by grafana-app-sdk. DO NOT EDIT. -// - -package v0alpha1 - -import ( - "github.com/grafana/grafana-app-sdk/resource" -) - -// schema is unexported to prevent accidental overwrites -var ( - schemaPluginMeta = resource.NewSimpleSchema("plugins.grafana.app", "v0alpha1", &PluginMeta{}, &PluginMetaList{}, resource.WithKind("PluginMeta"), - resource.WithPlural("pluginmetas"), resource.WithScope(resource.NamespacedScope)) - kindPluginMeta = resource.Kind{ - Schema: schemaPluginMeta, - Codecs: map[resource.KindEncoding]resource.Codec{ - resource.KindEncodingJSON: &PluginMetaJSONCodec{}, - }, - } -) - -// Kind returns a resource.Kind for this Schema with a JSON codec -func PluginMetaKind() resource.Kind { - return kindPluginMeta -} - -// Schema returns a resource.SimpleSchema representation of PluginMeta -func PluginMetaSchema() *resource.SimpleSchema { - return schemaPluginMeta -} - -// Interface compliance checks -var _ resource.Schema = kindPluginMeta diff --git a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_spec_gen.go b/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_spec_gen.go deleted file mode 100644 index 14a3b0515bd..00000000000 --- a/apps/plugins/pkg/apis/plugins/v0alpha1/pluginmeta_spec_gen.go +++ /dev/null @@ -1,474 +0,0 @@ -// Code generated - EDITING IS FUTILE. DO NOT EDIT. - -package v0alpha1 - -// JSON configuration schema for Grafana plugins -// Converted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json -// +k8s:openapi-gen=true -type PluginMetaJSONData struct { - // Unique name of the plugin - Id string `json:"id"` - // Plugin type - Type PluginMetaJSONDataType `json:"type"` - // Human-readable name of the plugin - Name string `json:"name"` - // Metadata for the plugin - Info PluginMetaInfo `json:"info"` - // Dependency information - Dependencies PluginMetaDependencies `json:"dependencies"` - // Optional fields - Alerting *bool `json:"alerting,omitempty"` - Annotations *bool `json:"annotations,omitempty"` - AutoEnabled *bool `json:"autoEnabled,omitempty"` - Backend *bool `json:"backend,omitempty"` - BuildMode *string `json:"buildMode,omitempty"` - BuiltIn *bool `json:"builtIn,omitempty"` - Category *PluginMetaJSONDataCategory `json:"category,omitempty"` - EnterpriseFeatures *PluginMetaEnterpriseFeatures `json:"enterpriseFeatures,omitempty"` - Executable *string `json:"executable,omitempty"` - HideFromList *bool `json:"hideFromList,omitempty"` - // +listType=atomic - Includes []PluginMetaInclude `json:"includes,omitempty"` - Logs *bool `json:"logs,omitempty"` - Metrics *bool `json:"metrics,omitempty"` - MultiValueFilterOperators *bool `json:"multiValueFilterOperators,omitempty"` - PascalName *string `json:"pascalName,omitempty"` - Preload *bool `json:"preload,omitempty"` - QueryOptions *PluginMetaQueryOptions `json:"queryOptions,omitempty"` - // +listType=atomic - Routes []PluginMetaRoute `json:"routes,omitempty"` - SkipDataQuery *bool `json:"skipDataQuery,omitempty"` - State *PluginMetaJSONDataState `json:"state,omitempty"` - Streaming *bool `json:"streaming,omitempty"` - Suggestions *bool `json:"suggestions,omitempty"` - Tracing *bool `json:"tracing,omitempty"` - Iam *PluginMetaIAM `json:"iam,omitempty"` - // +listType=atomic - Roles []PluginMetaRole `json:"roles,omitempty"` - Extensions *PluginMetaExtensions `json:"extensions,omitempty"` -} - -// NewPluginMetaJSONData creates a new PluginMetaJSONData object. -func NewPluginMetaJSONData() *PluginMetaJSONData { - return &PluginMetaJSONData{ - Info: *NewPluginMetaInfo(), - Dependencies: *NewPluginMetaDependencies(), - } -} - -// +k8s:openapi-gen=true -type PluginMetaInfo struct { - // Required fields - // +listType=set - Keywords []string `json:"keywords"` - Logos PluginMetaV0alpha1InfoLogos `json:"logos"` - Updated string `json:"updated"` - Version string `json:"version"` - // Optional fields - Author *PluginMetaV0alpha1InfoAuthor `json:"author,omitempty"` - Description *string `json:"description,omitempty"` - // +listType=atomic - Links []PluginMetaV0alpha1InfoLinks `json:"links,omitempty"` - // +listType=atomic - Screenshots []PluginMetaV0alpha1InfoScreenshots `json:"screenshots,omitempty"` -} - -// NewPluginMetaInfo creates a new PluginMetaInfo object. -func NewPluginMetaInfo() *PluginMetaInfo { - return &PluginMetaInfo{ - Keywords: []string{}, - Logos: *NewPluginMetaV0alpha1InfoLogos(), - } -} - -// +k8s:openapi-gen=true -type PluginMetaDependencies struct { - // Required field - GrafanaDependency string `json:"grafanaDependency"` - // Optional fields - GrafanaVersion *string `json:"grafanaVersion,omitempty"` - // +listType=set - // +listMapKey=id - Plugins []PluginMetaV0alpha1DependenciesPlugins `json:"plugins,omitempty"` - Extensions *PluginMetaV0alpha1DependenciesExtensions `json:"extensions,omitempty"` -} - -// NewPluginMetaDependencies creates a new PluginMetaDependencies object. -func NewPluginMetaDependencies() *PluginMetaDependencies { - return &PluginMetaDependencies{} -} - -// +k8s:openapi-gen=true -type PluginMetaEnterpriseFeatures struct { - // Allow additional properties - HealthDiagnosticsErrors *bool `json:"healthDiagnosticsErrors,omitempty"` -} - -// NewPluginMetaEnterpriseFeatures creates a new PluginMetaEnterpriseFeatures object. -func NewPluginMetaEnterpriseFeatures() *PluginMetaEnterpriseFeatures { - return &PluginMetaEnterpriseFeatures{ - HealthDiagnosticsErrors: (func(input bool) *bool { return &input })(false), - } -} - -// +k8s:openapi-gen=true -type PluginMetaInclude struct { - Uid *string `json:"uid,omitempty"` - Type *PluginMetaIncludeType `json:"type,omitempty"` - Name *string `json:"name,omitempty"` - Component *string `json:"component,omitempty"` - Role *PluginMetaIncludeRole `json:"role,omitempty"` - Action *string `json:"action,omitempty"` - Path *string `json:"path,omitempty"` - AddToNav *bool `json:"addToNav,omitempty"` - DefaultNav *bool `json:"defaultNav,omitempty"` - Icon *string `json:"icon,omitempty"` -} - -// NewPluginMetaInclude creates a new PluginMetaInclude object. -func NewPluginMetaInclude() *PluginMetaInclude { - return &PluginMetaInclude{} -} - -// +k8s:openapi-gen=true -type PluginMetaQueryOptions struct { - MaxDataPoints *bool `json:"maxDataPoints,omitempty"` - MinInterval *bool `json:"minInterval,omitempty"` - CacheTimeout *bool `json:"cacheTimeout,omitempty"` -} - -// NewPluginMetaQueryOptions creates a new PluginMetaQueryOptions object. -func NewPluginMetaQueryOptions() *PluginMetaQueryOptions { - return &PluginMetaQueryOptions{} -} - -// +k8s:openapi-gen=true -type PluginMetaRoute struct { - Path *string `json:"path,omitempty"` - Method *string `json:"method,omitempty"` - Url *string `json:"url,omitempty"` - ReqSignedIn *bool `json:"reqSignedIn,omitempty"` - ReqRole *string `json:"reqRole,omitempty"` - ReqAction *string `json:"reqAction,omitempty"` - // +listType=atomic - Headers []string `json:"headers,omitempty"` - Body map[string]interface{} `json:"body,omitempty"` - TokenAuth *PluginMetaV0alpha1RouteTokenAuth `json:"tokenAuth,omitempty"` - JwtTokenAuth *PluginMetaV0alpha1RouteJwtTokenAuth `json:"jwtTokenAuth,omitempty"` - // +listType=atomic - UrlParams []PluginMetaV0alpha1RouteUrlParams `json:"urlParams,omitempty"` -} - -// NewPluginMetaRoute creates a new PluginMetaRoute object. -func NewPluginMetaRoute() *PluginMetaRoute { - return &PluginMetaRoute{} -} - -// +k8s:openapi-gen=true -type PluginMetaIAM struct { - // +listType=atomic - Permissions []PluginMetaV0alpha1IAMPermissions `json:"permissions,omitempty"` -} - -// NewPluginMetaIAM creates a new PluginMetaIAM object. -func NewPluginMetaIAM() *PluginMetaIAM { - return &PluginMetaIAM{} -} - -// +k8s:openapi-gen=true -type PluginMetaRole struct { - Role *PluginMetaV0alpha1RoleRole `json:"role,omitempty"` - // +listType=set - Grants []string `json:"grants,omitempty"` -} - -// NewPluginMetaRole creates a new PluginMetaRole object. -func NewPluginMetaRole() *PluginMetaRole { - return &PluginMetaRole{} -} - -// +k8s:openapi-gen=true -type PluginMetaExtensions struct { - // +listType=atomic - AddedComponents []PluginMetaV0alpha1ExtensionsAddedComponents `json:"addedComponents,omitempty"` - // +listType=atomic - AddedLinks []PluginMetaV0alpha1ExtensionsAddedLinks `json:"addedLinks,omitempty"` - // +listType=set - // +listMapKey=id - ExposedComponents []PluginMetaV0alpha1ExtensionsExposedComponents `json:"exposedComponents,omitempty"` - // +listType=set - // +listMapKey=id - ExtensionPoints []PluginMetaV0alpha1ExtensionsExtensionPoints `json:"extensionPoints,omitempty"` -} - -// NewPluginMetaExtensions creates a new PluginMetaExtensions object. -func NewPluginMetaExtensions() *PluginMetaExtensions { - return &PluginMetaExtensions{} -} - -// +k8s:openapi-gen=true -type PluginMetaSpec struct { - PluginJSON PluginMetaJSONData `json:"pluginJSON"` -} - -// NewPluginMetaSpec creates a new PluginMetaSpec object. -func NewPluginMetaSpec() *PluginMetaSpec { - return &PluginMetaSpec{ - PluginJSON: *NewPluginMetaJSONData(), - } -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1InfoLogos struct { - Small string `json:"small"` - Large string `json:"large"` -} - -// NewPluginMetaV0alpha1InfoLogos creates a new PluginMetaV0alpha1InfoLogos object. -func NewPluginMetaV0alpha1InfoLogos() *PluginMetaV0alpha1InfoLogos { - return &PluginMetaV0alpha1InfoLogos{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1InfoAuthor struct { - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` - Url *string `json:"url,omitempty"` -} - -// NewPluginMetaV0alpha1InfoAuthor creates a new PluginMetaV0alpha1InfoAuthor object. -func NewPluginMetaV0alpha1InfoAuthor() *PluginMetaV0alpha1InfoAuthor { - return &PluginMetaV0alpha1InfoAuthor{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1InfoLinks struct { - Name *string `json:"name,omitempty"` - Url *string `json:"url,omitempty"` -} - -// NewPluginMetaV0alpha1InfoLinks creates a new PluginMetaV0alpha1InfoLinks object. -func NewPluginMetaV0alpha1InfoLinks() *PluginMetaV0alpha1InfoLinks { - return &PluginMetaV0alpha1InfoLinks{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1InfoScreenshots struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` -} - -// NewPluginMetaV0alpha1InfoScreenshots creates a new PluginMetaV0alpha1InfoScreenshots object. -func NewPluginMetaV0alpha1InfoScreenshots() *PluginMetaV0alpha1InfoScreenshots { - return &PluginMetaV0alpha1InfoScreenshots{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1DependenciesPlugins struct { - Id string `json:"id"` - Type PluginMetaV0alpha1DependenciesPluginsType `json:"type"` - Name string `json:"name"` -} - -// NewPluginMetaV0alpha1DependenciesPlugins creates a new PluginMetaV0alpha1DependenciesPlugins object. -func NewPluginMetaV0alpha1DependenciesPlugins() *PluginMetaV0alpha1DependenciesPlugins { - return &PluginMetaV0alpha1DependenciesPlugins{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1DependenciesExtensions struct { - // +listType=set - ExposedComponents []string `json:"exposedComponents,omitempty"` -} - -// NewPluginMetaV0alpha1DependenciesExtensions creates a new PluginMetaV0alpha1DependenciesExtensions object. -func NewPluginMetaV0alpha1DependenciesExtensions() *PluginMetaV0alpha1DependenciesExtensions { - return &PluginMetaV0alpha1DependenciesExtensions{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1RouteTokenAuth struct { - Url *string `json:"url,omitempty"` - // +listType=set - Scopes []string `json:"scopes,omitempty"` - Params map[string]interface{} `json:"params,omitempty"` -} - -// NewPluginMetaV0alpha1RouteTokenAuth creates a new PluginMetaV0alpha1RouteTokenAuth object. -func NewPluginMetaV0alpha1RouteTokenAuth() *PluginMetaV0alpha1RouteTokenAuth { - return &PluginMetaV0alpha1RouteTokenAuth{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1RouteJwtTokenAuth struct { - Url *string `json:"url,omitempty"` - // +listType=set - Scopes []string `json:"scopes,omitempty"` - Params map[string]interface{} `json:"params,omitempty"` -} - -// NewPluginMetaV0alpha1RouteJwtTokenAuth creates a new PluginMetaV0alpha1RouteJwtTokenAuth object. -func NewPluginMetaV0alpha1RouteJwtTokenAuth() *PluginMetaV0alpha1RouteJwtTokenAuth { - return &PluginMetaV0alpha1RouteJwtTokenAuth{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1RouteUrlParams struct { - Name *string `json:"name,omitempty"` - Content *string `json:"content,omitempty"` -} - -// NewPluginMetaV0alpha1RouteUrlParams creates a new PluginMetaV0alpha1RouteUrlParams object. -func NewPluginMetaV0alpha1RouteUrlParams() *PluginMetaV0alpha1RouteUrlParams { - return &PluginMetaV0alpha1RouteUrlParams{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1IAMPermissions struct { - Action *string `json:"action,omitempty"` - Scope *string `json:"scope,omitempty"` -} - -// NewPluginMetaV0alpha1IAMPermissions creates a new PluginMetaV0alpha1IAMPermissions object. -func NewPluginMetaV0alpha1IAMPermissions() *PluginMetaV0alpha1IAMPermissions { - return &PluginMetaV0alpha1IAMPermissions{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1RoleRolePermissions struct { - Action *string `json:"action,omitempty"` - Scope *string `json:"scope,omitempty"` -} - -// NewPluginMetaV0alpha1RoleRolePermissions creates a new PluginMetaV0alpha1RoleRolePermissions object. -func NewPluginMetaV0alpha1RoleRolePermissions() *PluginMetaV0alpha1RoleRolePermissions { - return &PluginMetaV0alpha1RoleRolePermissions{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1RoleRole struct { - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - // +listType=atomic - Permissions []PluginMetaV0alpha1RoleRolePermissions `json:"permissions,omitempty"` -} - -// NewPluginMetaV0alpha1RoleRole creates a new PluginMetaV0alpha1RoleRole object. -func NewPluginMetaV0alpha1RoleRole() *PluginMetaV0alpha1RoleRole { - return &PluginMetaV0alpha1RoleRole{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1ExtensionsAddedComponents struct { - // +listType=set - Targets []string `json:"targets"` - Title string `json:"title"` - Description *string `json:"description,omitempty"` -} - -// NewPluginMetaV0alpha1ExtensionsAddedComponents creates a new PluginMetaV0alpha1ExtensionsAddedComponents object. -func NewPluginMetaV0alpha1ExtensionsAddedComponents() *PluginMetaV0alpha1ExtensionsAddedComponents { - return &PluginMetaV0alpha1ExtensionsAddedComponents{ - Targets: []string{}, - } -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1ExtensionsAddedLinks struct { - // +listType=set - Targets []string `json:"targets"` - Title string `json:"title"` - Description *string `json:"description,omitempty"` -} - -// NewPluginMetaV0alpha1ExtensionsAddedLinks creates a new PluginMetaV0alpha1ExtensionsAddedLinks object. -func NewPluginMetaV0alpha1ExtensionsAddedLinks() *PluginMetaV0alpha1ExtensionsAddedLinks { - return &PluginMetaV0alpha1ExtensionsAddedLinks{ - Targets: []string{}, - } -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1ExtensionsExposedComponents struct { - Id string `json:"id"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` -} - -// NewPluginMetaV0alpha1ExtensionsExposedComponents creates a new PluginMetaV0alpha1ExtensionsExposedComponents object. -func NewPluginMetaV0alpha1ExtensionsExposedComponents() *PluginMetaV0alpha1ExtensionsExposedComponents { - return &PluginMetaV0alpha1ExtensionsExposedComponents{} -} - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1ExtensionsExtensionPoints struct { - Id string `json:"id"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` -} - -// NewPluginMetaV0alpha1ExtensionsExtensionPoints creates a new PluginMetaV0alpha1ExtensionsExtensionPoints object. -func NewPluginMetaV0alpha1ExtensionsExtensionPoints() *PluginMetaV0alpha1ExtensionsExtensionPoints { - return &PluginMetaV0alpha1ExtensionsExtensionPoints{} -} - -// +k8s:openapi-gen=true -type PluginMetaJSONDataType string - -const ( - PluginMetaJSONDataTypeApp PluginMetaJSONDataType = "app" - PluginMetaJSONDataTypeDatasource PluginMetaJSONDataType = "datasource" - PluginMetaJSONDataTypePanel PluginMetaJSONDataType = "panel" - PluginMetaJSONDataTypeRenderer PluginMetaJSONDataType = "renderer" -) - -// +k8s:openapi-gen=true -type PluginMetaJSONDataCategory string - -const ( - PluginMetaJSONDataCategoryTsdb PluginMetaJSONDataCategory = "tsdb" - PluginMetaJSONDataCategoryLogging PluginMetaJSONDataCategory = "logging" - PluginMetaJSONDataCategoryCloud PluginMetaJSONDataCategory = "cloud" - PluginMetaJSONDataCategoryTracing PluginMetaJSONDataCategory = "tracing" - PluginMetaJSONDataCategoryProfiling PluginMetaJSONDataCategory = "profiling" - PluginMetaJSONDataCategorySql PluginMetaJSONDataCategory = "sql" - PluginMetaJSONDataCategoryEnterprise PluginMetaJSONDataCategory = "enterprise" - PluginMetaJSONDataCategoryIot PluginMetaJSONDataCategory = "iot" - PluginMetaJSONDataCategoryOther PluginMetaJSONDataCategory = "other" -) - -// +k8s:openapi-gen=true -type PluginMetaJSONDataState string - -const ( - PluginMetaJSONDataStateAlpha PluginMetaJSONDataState = "alpha" - PluginMetaJSONDataStateBeta PluginMetaJSONDataState = "beta" -) - -// +k8s:openapi-gen=true -type PluginMetaIncludeType string - -const ( - PluginMetaIncludeTypeDashboard PluginMetaIncludeType = "dashboard" - PluginMetaIncludeTypePage PluginMetaIncludeType = "page" - PluginMetaIncludeTypePanel PluginMetaIncludeType = "panel" - PluginMetaIncludeTypeDatasource PluginMetaIncludeType = "datasource" -) - -// +k8s:openapi-gen=true -type PluginMetaIncludeRole string - -const ( - PluginMetaIncludeRoleAdmin PluginMetaIncludeRole = "Admin" - PluginMetaIncludeRoleEditor PluginMetaIncludeRole = "Editor" - PluginMetaIncludeRoleViewer PluginMetaIncludeRole = "Viewer" -) - -// +k8s:openapi-gen=true -type PluginMetaV0alpha1DependenciesPluginsType string - -const ( - PluginMetaV0alpha1DependenciesPluginsTypeApp PluginMetaV0alpha1DependenciesPluginsType = "app" - PluginMetaV0alpha1DependenciesPluginsTypeDatasource PluginMetaV0alpha1DependenciesPluginsType = "datasource" - PluginMetaV0alpha1DependenciesPluginsTypePanel PluginMetaV0alpha1DependenciesPluginsType = "panel" -) diff --git a/apps/plugins/pkg/apis/plugins_manifest.go b/apps/plugins/pkg/apis/plugins_manifest.go index e09c70244a7..1a351eb2baf 100644 --- a/apps/plugins/pkg/apis/plugins_manifest.go +++ b/apps/plugins/pkg/apis/plugins_manifest.go @@ -20,12 +20,12 @@ import ( ) var ( - rawSchemaPluginv0alpha1 = []byte(`{"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"Plugin":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"spec":{"additionalProperties":false,"properties":{"class":{"enum":["core","external"],"type":"string"},"id":{"type":"string"},"url":{"type":"string"},"version":{"type":"string"}},"required":["id","version","class"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) - versionSchemaPluginv0alpha1 app.VersionSchema - _ = json.Unmarshal(rawSchemaPluginv0alpha1, &versionSchemaPluginv0alpha1) - rawSchemaPluginMetav0alpha1 = []byte(`{"Dependencies":{"additionalProperties":false,"properties":{"extensions":{"additionalProperties":false,"properties":{"exposedComponents":{"description":"+listType=set","items":{"type":"string"},"type":"array"}},"type":"object"},"grafanaDependency":{"description":"Required field","type":"string"},"grafanaVersion":{"description":"Optional fields","type":"string"},"plugins":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"enum":["app","datasource","panel"],"type":"string"}},"required":["id","type","name"],"type":"object"},"type":"array"}},"required":["grafanaDependency"],"type":"object"},"EnterpriseFeatures":{"additionalProperties":false,"properties":{"healthDiagnosticsErrors":{"default":false,"description":"Allow additional properties","type":"boolean"}},"type":"object"},"Extensions":{"additionalProperties":false,"properties":{"addedComponents":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"targets":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"title":{"type":"string"}},"required":["targets","title"],"type":"object"},"type":"array"},"addedLinks":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"targets":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"title":{"type":"string"}},"required":["targets","title"],"type":"object"},"type":"array"},"exposedComponents":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"id":{"type":"string"},"title":{"type":"string"}},"required":["id"],"type":"object"},"type":"array"},"extensionPoints":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"id":{"type":"string"},"title":{"type":"string"}},"required":["id"],"type":"object"},"type":"array"}},"type":"object"},"IAM":{"additionalProperties":false,"properties":{"permissions":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"action":{"type":"string"},"scope":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"},"Include":{"additionalProperties":false,"properties":{"action":{"type":"string"},"addToNav":{"type":"boolean"},"component":{"type":"string"},"defaultNav":{"type":"boolean"},"icon":{"type":"string"},"name":{"type":"string"},"path":{"type":"string"},"role":{"enum":["Admin","Editor","Viewer"],"type":"string"},"type":{"enum":["dashboard","page","panel","datasource"],"type":"string"},"uid":{"type":"string"}},"type":"object"},"Info":{"additionalProperties":false,"properties":{"author":{"additionalProperties":false,"description":"Optional fields","properties":{"email":{"type":"string"},"name":{"type":"string"},"url":{"type":"string"}},"type":"object"},"description":{"type":"string"},"keywords":{"description":"Required fields\n+listType=set","items":{"type":"string"},"type":"array"},"links":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"name":{"type":"string"},"url":{"type":"string"}},"type":"object"},"type":"array"},"logos":{"additionalProperties":false,"properties":{"large":{"type":"string"},"small":{"type":"string"}},"required":["small","large"],"type":"object"},"screenshots":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"name":{"type":"string"},"path":{"type":"string"}},"type":"object"},"type":"array"},"updated":{"type":"string"},"version":{"type":"string"}},"required":["keywords","logos","updated","version"],"type":"object"},"JSONData":{"additionalProperties":false,"description":"JSON configuration schema for Grafana plugins\nConverted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json","properties":{"alerting":{"description":"Optional fields","type":"boolean"},"annotations":{"type":"boolean"},"autoEnabled":{"type":"boolean"},"backend":{"type":"boolean"},"buildMode":{"type":"string"},"builtIn":{"type":"boolean"},"category":{"enum":["tsdb","logging","cloud","tracing","profiling","sql","enterprise","iot","other"],"type":"string"},"dependencies":{"$ref":"#/components/schemas/Dependencies","description":"Dependency information"},"enterpriseFeatures":{"$ref":"#/components/schemas/EnterpriseFeatures"},"executable":{"type":"string"},"extensions":{"$ref":"#/components/schemas/Extensions"},"hideFromList":{"type":"boolean"},"iam":{"$ref":"#/components/schemas/IAM"},"id":{"description":"Unique name of the plugin","type":"string"},"includes":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Include"},"type":"array"},"info":{"$ref":"#/components/schemas/Info","description":"Metadata for the plugin"},"logs":{"type":"boolean"},"metrics":{"type":"boolean"},"multiValueFilterOperators":{"type":"boolean"},"name":{"description":"Human-readable name of the plugin","type":"string"},"pascalName":{"type":"string"},"preload":{"type":"boolean"},"queryOptions":{"$ref":"#/components/schemas/QueryOptions"},"roles":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Role"},"type":"array"},"routes":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Route"},"type":"array"},"skipDataQuery":{"type":"boolean"},"state":{"enum":["alpha","beta"],"type":"string"},"streaming":{"type":"boolean"},"suggestions":{"type":"boolean"},"tracing":{"type":"boolean"},"type":{"description":"Plugin type","enum":["app","datasource","panel","renderer"],"type":"string"}},"required":["id","type","name","info","dependencies"],"type":"object"},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"PluginMeta":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"QueryOptions":{"additionalProperties":false,"properties":{"cacheTimeout":{"type":"boolean"},"maxDataPoints":{"type":"boolean"},"minInterval":{"type":"boolean"}},"type":"object"},"Role":{"additionalProperties":false,"properties":{"grants":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"role":{"additionalProperties":false,"properties":{"description":{"type":"string"},"name":{"type":"string"},"permissions":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"action":{"type":"string"},"scope":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"}},"type":"object"},"Route":{"additionalProperties":false,"properties":{"body":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"headers":{"description":"+listType=atomic","items":{"type":"string"},"type":"array"},"jwtTokenAuth":{"additionalProperties":false,"properties":{"params":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"scopes":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"url":{"type":"string"}},"type":"object"},"method":{"type":"string"},"path":{"type":"string"},"reqAction":{"type":"string"},"reqRole":{"type":"string"},"reqSignedIn":{"type":"boolean"},"tokenAuth":{"additionalProperties":false,"properties":{"params":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"scopes":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"url":{"type":"string"}},"type":"object"},"url":{"type":"string"},"urlParams":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"content":{"type":"string"},"name":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"},"spec":{"additionalProperties":false,"properties":{"pluginJSON":{"$ref":"#/components/schemas/JSONData"}},"required":["pluginJSON"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) - versionSchemaPluginMetav0alpha1 app.VersionSchema - _ = json.Unmarshal(rawSchemaPluginMetav0alpha1, &versionSchemaPluginMetav0alpha1) + rawSchemaPluginv0alpha1 = []byte(`{"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"Plugin":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"spec":{"additionalProperties":false,"properties":{"class":{"enum":["core","external"],"type":"string"},"id":{"type":"string"},"url":{"type":"string"},"version":{"type":"string"}},"required":["id","version","class"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaPluginv0alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaPluginv0alpha1, &versionSchemaPluginv0alpha1) + rawSchemaMetav0alpha1 = []byte(`{"Dependencies":{"additionalProperties":false,"properties":{"extensions":{"additionalProperties":false,"properties":{"exposedComponents":{"description":"+listType=set","items":{"type":"string"},"type":"array"}},"type":"object"},"grafanaDependency":{"description":"Required field","type":"string"},"grafanaVersion":{"description":"Optional fields","type":"string"},"plugins":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"id":{"type":"string"},"name":{"type":"string"},"type":{"enum":["app","datasource","panel"],"type":"string"}},"required":["id","type","name"],"type":"object"},"type":"array"}},"required":["grafanaDependency"],"type":"object"},"EnterpriseFeatures":{"additionalProperties":false,"properties":{"healthDiagnosticsErrors":{"default":false,"description":"Allow additional properties","type":"boolean"}},"type":"object"},"Extensions":{"additionalProperties":false,"properties":{"addedComponents":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"targets":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"title":{"type":"string"}},"required":["targets","title"],"type":"object"},"type":"array"},"addedLinks":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"targets":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"title":{"type":"string"}},"required":["targets","title"],"type":"object"},"type":"array"},"exposedComponents":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"id":{"type":"string"},"title":{"type":"string"}},"required":["id"],"type":"object"},"type":"array"},"extensionPoints":{"description":"+listType=set\n+listMapKey=id","items":{"additionalProperties":false,"properties":{"description":{"type":"string"},"id":{"type":"string"},"title":{"type":"string"}},"required":["id"],"type":"object"},"type":"array"}},"type":"object"},"IAM":{"additionalProperties":false,"properties":{"permissions":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"action":{"type":"string"},"scope":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"},"Include":{"additionalProperties":false,"properties":{"action":{"type":"string"},"addToNav":{"type":"boolean"},"component":{"type":"string"},"defaultNav":{"type":"boolean"},"icon":{"type":"string"},"name":{"type":"string"},"path":{"type":"string"},"role":{"enum":["Admin","Editor","Viewer"],"type":"string"},"type":{"enum":["dashboard","page","panel","datasource"],"type":"string"},"uid":{"type":"string"}},"type":"object"},"Info":{"additionalProperties":false,"properties":{"author":{"additionalProperties":false,"description":"Optional fields","properties":{"email":{"type":"string"},"name":{"type":"string"},"url":{"type":"string"}},"type":"object"},"description":{"type":"string"},"keywords":{"description":"Required fields\n+listType=set","items":{"type":"string"},"type":"array"},"links":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"name":{"type":"string"},"url":{"type":"string"}},"type":"object"},"type":"array"},"logos":{"additionalProperties":false,"properties":{"large":{"type":"string"},"small":{"type":"string"}},"required":["small","large"],"type":"object"},"screenshots":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"name":{"type":"string"},"path":{"type":"string"}},"type":"object"},"type":"array"},"updated":{"type":"string"},"version":{"type":"string"}},"required":["keywords","logos","updated","version"],"type":"object"},"JSONData":{"additionalProperties":false,"description":"JSON configuration schema for Grafana plugins\nConverted from: https://github.com/grafana/grafana/blob/main/docs/sources/developers/plugins/plugin.schema.json","properties":{"alerting":{"description":"Optional fields","type":"boolean"},"annotations":{"type":"boolean"},"autoEnabled":{"type":"boolean"},"backend":{"type":"boolean"},"buildMode":{"type":"string"},"builtIn":{"type":"boolean"},"category":{"enum":["tsdb","logging","cloud","tracing","profiling","sql","enterprise","iot","other"],"type":"string"},"dependencies":{"$ref":"#/components/schemas/Dependencies","description":"Dependency information"},"enterpriseFeatures":{"$ref":"#/components/schemas/EnterpriseFeatures"},"executable":{"type":"string"},"extensions":{"$ref":"#/components/schemas/Extensions"},"hideFromList":{"type":"boolean"},"iam":{"$ref":"#/components/schemas/IAM"},"id":{"description":"Unique name of the plugin","type":"string"},"includes":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Include"},"type":"array"},"info":{"$ref":"#/components/schemas/Info","description":"Metadata for the plugin"},"logs":{"type":"boolean"},"metrics":{"type":"boolean"},"multiValueFilterOperators":{"type":"boolean"},"name":{"description":"Human-readable name of the plugin","type":"string"},"pascalName":{"type":"string"},"preload":{"type":"boolean"},"queryOptions":{"$ref":"#/components/schemas/QueryOptions"},"roles":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Role"},"type":"array"},"routes":{"description":"+listType=atomic","items":{"$ref":"#/components/schemas/Route"},"type":"array"},"skipDataQuery":{"type":"boolean"},"state":{"enum":["alpha","beta"],"type":"string"},"streaming":{"type":"boolean"},"suggestions":{"type":"boolean"},"tracing":{"type":"boolean"},"type":{"description":"Plugin type","enum":["app","datasource","panel","renderer"],"type":"string"}},"required":["id","type","name","info","dependencies"],"type":"object"},"Meta":{"properties":{"spec":{"$ref":"#/components/schemas/spec"},"status":{"$ref":"#/components/schemas/status"}},"required":["spec"]},"OperatorState":{"additionalProperties":false,"properties":{"descriptiveState":{"description":"descriptiveState is an optional more descriptive state field which has no requirements on format","type":"string"},"details":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"details contains any extra information that is operator-specific","type":"object"},"lastEvaluation":{"description":"lastEvaluation is the ResourceVersion last evaluated","type":"string"},"state":{"description":"state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.","enum":["success","in_progress","failed"],"type":"string"}},"required":["lastEvaluation","state"],"type":"object"},"QueryOptions":{"additionalProperties":false,"properties":{"cacheTimeout":{"type":"boolean"},"maxDataPoints":{"type":"boolean"},"minInterval":{"type":"boolean"}},"type":"object"},"Role":{"additionalProperties":false,"properties":{"grants":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"role":{"additionalProperties":false,"properties":{"description":{"type":"string"},"name":{"type":"string"},"permissions":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"action":{"type":"string"},"scope":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"}},"type":"object"},"Route":{"additionalProperties":false,"properties":{"body":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"headers":{"description":"+listType=atomic","items":{"type":"string"},"type":"array"},"jwtTokenAuth":{"additionalProperties":false,"properties":{"params":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"scopes":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"url":{"type":"string"}},"type":"object"},"method":{"type":"string"},"path":{"type":"string"},"reqAction":{"type":"string"},"reqRole":{"type":"string"},"reqSignedIn":{"type":"boolean"},"tokenAuth":{"additionalProperties":false,"properties":{"params":{"additionalProperties":{"additionalProperties":{},"type":"object"},"type":"object"},"scopes":{"description":"+listType=set","items":{"type":"string"},"type":"array"},"url":{"type":"string"}},"type":"object"},"url":{"type":"string"},"urlParams":{"description":"+listType=atomic","items":{"additionalProperties":false,"properties":{"content":{"type":"string"},"name":{"type":"string"}},"type":"object"},"type":"array"}},"type":"object"},"spec":{"additionalProperties":false,"properties":{"pluginJSON":{"$ref":"#/components/schemas/JSONData"}},"required":["pluginJSON"],"type":"object"},"status":{"additionalProperties":false,"properties":{"additionalFields":{"additionalProperties":{"additionalProperties":{},"type":"object"},"description":"additionalFields is reserved for future use","type":"object"},"operatorStates":{"additionalProperties":{"$ref":"#/components/schemas/OperatorState"},"description":"operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.","type":"object"}},"type":"object"}}`) + versionSchemaMetav0alpha1 app.VersionSchema + _ = json.Unmarshal(rawSchemaMetav0alpha1, &versionSchemaMetav0alpha1) ) var appManifestData = app.ManifestData{ @@ -46,11 +46,11 @@ var appManifestData = app.ManifestData{ }, { - Kind: "PluginMeta", - Plural: "PluginMetas", + Kind: "Meta", + Plural: "Metas", Scope: "Namespaced", Conversion: false, - Schema: &versionSchemaPluginMetav0alpha1, + Schema: &versionSchemaMetav0alpha1, }, }, Routes: app.ManifestVersionRoutes{ @@ -71,8 +71,8 @@ func RemoteManifest() app.Manifest { } var kindVersionToGoType = map[string]resource.Kind{ - "Plugin/v0alpha1": v0alpha1.PluginKind(), - "PluginMeta/v0alpha1": v0alpha1.PluginMetaKind(), + "Plugin/v0alpha1": v0alpha1.PluginKind(), + "Meta/v0alpha1": v0alpha1.MetaKind(), } // ManifestGoTypeAssociator returns the associated resource.Kind instance for a given Kind and Version, if one exists. diff --git a/apps/plugins/pkg/app/app.go b/apps/plugins/pkg/app/app.go index 3d17cc34221..c296bccd9e1 100644 --- a/apps/plugins/pkg/app/app.go +++ b/apps/plugins/pkg/app/app.go @@ -3,6 +3,7 @@ package app import ( "context" "fmt" + "sync" "github.com/grafana/grafana-app-sdk/app" "github.com/grafana/grafana-app-sdk/k8s" @@ -16,7 +17,6 @@ import ( restclient "k8s.io/client-go/rest" "k8s.io/klog/v2" - authlib "github.com/grafana/authlib/types" pluginsappapis "github.com/grafana/grafana/apps/plugins/pkg/apis" pluginsv0alpha1 "github.com/grafana/grafana/apps/plugins/pkg/apis/plugins/v0alpha1" "github.com/grafana/grafana/apps/plugins/pkg/app/meta" @@ -43,7 +43,7 @@ func New(cfg app.Config) (app.App, error) { Kind: pluginsv0alpha1.PluginKind(), }, { - Kind: pluginsv0alpha1.PluginMetaKind(), + Kind: pluginsv0alpha1.MetaKind(), }, }, } @@ -69,6 +69,7 @@ type PluginAppConfig struct { } func ProvideAppInstaller( + authorizer authorizer.Authorizer, metaProviderManager *meta.ProviderManager, ) (*PluginAppInstaller, error) { specificConfig := &PluginAppConfig{ @@ -87,31 +88,30 @@ func ProvideAppInstaller( appInstaller := &PluginAppInstaller{ AppInstaller: defaultInstaller, + authorizer: authorizer, metaManager: metaProviderManager, ready: make(chan struct{}), } return appInstaller, nil } -func (p *PluginAppInstaller) WithAccessChecker(access authlib.AccessChecker) *PluginAppInstaller { - p.access = access - return p -} - type PluginAppInstaller struct { appsdkapiserver.AppInstaller metaManager *meta.ProviderManager - access authlib.AccessChecker + authorizer authorizer.Authorizer // restConfig is set during InitializeApp and used by the client factory restConfig *restclient.Config ready chan struct{} + readyOnce sync.Once } func (p *PluginAppInstaller) InitializeApp(restConfig restclient.Config) error { if p.restConfig == nil { p.restConfig = &restConfig - close(p.ready) + p.readyOnce.Do(func() { + close(p.ready) + }) } return p.AppInstaller.InitializeApp(restConfig) } @@ -137,9 +137,9 @@ func (p *PluginAppInstaller) InstallAPIs( return client, nil } - pluginMetaGVR := pluginsv0alpha1.PluginMetaKind().GroupVersionResource() + pluginMetaGVR := pluginsv0alpha1.MetaKind().GroupVersionResource() replacedStorage := map[schema.GroupVersionResource]rest.Storage{ - pluginMetaGVR: NewPluginMetaStorage(p.metaManager, clientFactory), + pluginMetaGVR: NewMetaStorage(p.metaManager, clientFactory), } wrappedServer := &customStorageWrapper{ wrapped: server, @@ -149,34 +149,5 @@ func (p *PluginAppInstaller) InstallAPIs( } func (p *PluginAppInstaller) GetAuthorizer() authorizer.Authorizer { - if p.access == nil { - return nil - } - - return authorizer.AuthorizerFunc( - func(ctx context.Context, a authorizer.Attributes) (decision authorizer.Decision, reason string, err error) { - info, ok := authlib.AuthInfoFrom(ctx) - if !ok { - return authorizer.DecisionDeny, "failed to get auth info", nil - } - - res, err := p.access.Check(ctx, info, authlib.CheckRequest{ - Verb: a.GetVerb(), - Group: a.GetAPIGroup(), - Resource: a.GetResource(), - Name: a.GetName(), - Namespace: a.GetNamespace(), - Subresource: a.GetSubresource(), - Path: a.GetPath(), - }, "") - if err != nil { - return authorizer.DecisionDeny, "failed to perform authorization", err - } - - if !res.Allowed { - return authorizer.DecisionDeny, "permission denied", nil - } - - return authorizer.DecisionAllow, "", nil - }) + return p.authorizer } diff --git a/apps/plugins/pkg/app/authorizer.go b/apps/plugins/pkg/app/authorizer.go deleted file mode 100644 index b6a800694f7..00000000000 --- a/apps/plugins/pkg/app/authorizer.go +++ /dev/null @@ -1,32 +0,0 @@ -package app - -import ( - "context" - - "k8s.io/apiserver/pkg/authorization/authorizer" - - "github.com/grafana/grafana/pkg/apimachinery/identity" -) - -func GetAuthorizer() authorizer.Authorizer { - return authorizer.AuthorizerFunc(func( - ctx context.Context, attr authorizer.Attributes, - ) (authorized authorizer.Decision, reason string, err error) { - if !attr.IsResourceRequest() { - return authorizer.DecisionNoOpinion, "", nil - } - - // require a user - u, err := identity.GetRequester(ctx) - if err != nil { - return authorizer.DecisionDeny, "valid user is required", err - } - - // check if is admin - if u.HasRole(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - - return authorizer.DecisionDeny, "forbidden", nil - }) -} diff --git a/apps/plugins/pkg/app/meta/cloud.go b/apps/plugins/pkg/app/meta/catalog.go similarity index 56% rename from apps/plugins/pkg/app/meta/cloud.go rename to apps/plugins/pkg/app/meta/catalog.go index f49445d093a..6e6a47fa0bd 100644 --- a/apps/plugins/pkg/app/meta/cloud.go +++ b/apps/plugins/pkg/app/meta/catalog.go @@ -15,29 +15,29 @@ import ( ) const ( - defaultCloudTTL = 1 * time.Hour + defaultCatalogTTL = 1 * time.Hour ) -// CloudProvider retrieves plugin metadata from the grafana.com API. -type CloudProvider struct { +// CatalogProvider retrieves plugin metadata from the grafana.com API. +type CatalogProvider struct { httpClient *http.Client grafanaComAPIURL string log logging.Logger ttl time.Duration } -// NewCloudProvider creates a new CloudProvider that fetches metadata from grafana.com. -func NewCloudProvider(grafanaComAPIURL string) *CloudProvider { - return NewCloudProviderWithTTL(grafanaComAPIURL, defaultCloudTTL) +// NewCatalogProvider creates a new CatalogProvider that fetches metadata from grafana.com. +func NewCatalogProvider(grafanaComAPIURL string) *CatalogProvider { + return NewCatalogProviderWithTTL(grafanaComAPIURL, defaultCatalogTTL) } -// NewCloudProviderWithTTL creates a new CloudProvider with a custom TTL. -func NewCloudProviderWithTTL(grafanaComAPIURL string, ttl time.Duration) *CloudProvider { +// NewCatalogProviderWithTTL creates a new CatalogProvider with a custom TTL. +func NewCatalogProviderWithTTL(grafanaComAPIURL string, ttl time.Duration) *CatalogProvider { if grafanaComAPIURL == "" { grafanaComAPIURL = "https://grafana.com/api/plugins" } - return &CloudProvider{ + return &CatalogProvider{ httpClient: &http.Client{ Timeout: 10 * time.Second, }, @@ -49,7 +49,7 @@ func NewCloudProviderWithTTL(grafanaComAPIURL string, ttl time.Duration) *CloudP // GetMeta fetches plugin metadata from grafana.com API endpoint: // GET /api/plugins/{pluginId}/versions/{version} -func (p *CloudProvider) GetMeta(ctx context.Context, pluginID, version string) (*Result, error) { +func (p *CatalogProvider) GetMeta(ctx context.Context, pluginID, version string) (*Result, error) { u, err := url.Parse(p.grafanaComAPIURL) if err != nil { return nil, fmt.Errorf("invalid grafana.com API URL: %w", err) @@ -96,24 +96,24 @@ func (p *CloudProvider) GetMeta(ctx context.Context, pluginID, version string) ( // grafanaComPluginVersionMeta represents the response from grafana.com API // GET /api/plugins/{pluginId}/versions/{version} type grafanaComPluginVersionMeta struct { - PluginID string `json:"pluginSlug"` - Version string `json:"version"` - URL string `json:"url"` - Commit string `json:"commit"` - Description string `json:"description"` - Keywords []string `json:"keywords"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - JSON pluginsv0alpha1.PluginMetaJSONData `json:"json"` - Readme string `json:"readme"` - Downloads int `json:"downloads"` - Verified bool `json:"verified"` - Status string `json:"status"` - StatusContext string `json:"statusContext"` - DownloadSlug string `json:"downloadSlug"` - SignatureType string `json:"signatureType"` - SignedByOrg string `json:"signedByOrg"` - SignedByOrgName string `json:"signedByOrgName"` + PluginID string `json:"pluginSlug"` + Version string `json:"version"` + URL string `json:"url"` + Commit string `json:"commit"` + Description string `json:"description"` + Keywords []string `json:"keywords"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + JSON pluginsv0alpha1.MetaJSONData `json:"json"` + Readme string `json:"readme"` + Downloads int `json:"downloads"` + Verified bool `json:"verified"` + Status string `json:"status"` + StatusContext string `json:"statusContext"` + DownloadSlug string `json:"downloadSlug"` + SignatureType string `json:"signatureType"` + SignedByOrg string `json:"signedByOrg"` + SignedByOrgName string `json:"signedByOrgName"` Packages struct { Any struct { Md5 string `json:"md5"` diff --git a/apps/plugins/pkg/app/meta/cloud_test.go b/apps/plugins/pkg/app/meta/catalog_test.go similarity index 79% rename from apps/plugins/pkg/app/meta/cloud_test.go rename to apps/plugins/pkg/app/meta/catalog_test.go index bef2d1a5041..845afc7cd54 100644 --- a/apps/plugins/pkg/app/meta/cloud_test.go +++ b/apps/plugins/pkg/app/meta/catalog_test.go @@ -15,14 +15,14 @@ import ( pluginsv0alpha1 "github.com/grafana/grafana/apps/plugins/pkg/apis/plugins/v0alpha1" ) -func TestCloudProvider_GetMeta(t *testing.T) { +func TestCatalogProvider_GetMeta(t *testing.T) { ctx := context.Background() t.Run("successfully fetches plugin metadata", func(t *testing.T) { - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -44,13 +44,13 @@ func TestCloudProvider_GetMeta(t *testing.T) { })) defer server.Close() - provider := NewCloudProvider(server.URL + "/api/plugins") + provider := NewCatalogProvider(server.URL + "/api/plugins") result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") require.NoError(t, err) require.NotNil(t, result) assert.Equal(t, expectedMeta, result.Meta) - assert.Equal(t, defaultCloudTTL, result.TTL) + assert.Equal(t, defaultCatalogTTL, result.TTL) }) t.Run("returns ErrMetaNotFound for 404 status", func(t *testing.T) { @@ -59,7 +59,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { })) defer server.Close() - provider := NewCloudProvider(server.URL + "/api/plugins") + provider := NewCatalogProvider(server.URL + "/api/plugins") result, err := provider.GetMeta(ctx, "nonexistent-plugin", "1.0.0") assert.Error(t, err) @@ -73,7 +73,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { })) defer server.Close() - provider := NewCloudProvider(server.URL + "/api/plugins") + provider := NewCatalogProvider(server.URL + "/api/plugins") result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") assert.Error(t, err) @@ -89,7 +89,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { })) defer server.Close() - provider := NewCloudProvider(server.URL + "/api/plugins") + provider := NewCatalogProvider(server.URL + "/api/plugins") result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") assert.Error(t, err) @@ -98,7 +98,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { }) t.Run("returns error for invalid API URL", func(t *testing.T) { - provider := NewCloudProvider("://invalid-url") + provider := NewCatalogProvider("://invalid-url") result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") assert.Error(t, err) @@ -108,10 +108,10 @@ func TestCloudProvider_GetMeta(t *testing.T) { t.Run("uses custom TTL when provided", func(t *testing.T) { customTTL := 2 * time.Hour - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -127,7 +127,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { })) defer server.Close() - provider := NewCloudProviderWithTTL(server.URL+"/api/plugins", customTTL) + provider := NewCatalogProviderWithTTL(server.URL+"/api/plugins", customTTL) result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") require.NoError(t, err) @@ -145,7 +145,7 @@ func TestCloudProvider_GetMeta(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - provider := NewCloudProvider(server.URL + "/api/plugins") + provider := NewCatalogProvider(server.URL + "/api/plugins") result, err := provider.GetMeta(ctx, "test-plugin", "1.0.0") assert.Error(t, err) @@ -153,34 +153,34 @@ func TestCloudProvider_GetMeta(t *testing.T) { }) } -func TestNewCloudProvider(t *testing.T) { +func TestNewCatalogProvider(t *testing.T) { t.Run("creates provider with default TTL", func(t *testing.T) { - provider := NewCloudProvider("https://grafana.com/api/plugins") - assert.Equal(t, defaultCloudTTL, provider.ttl) + provider := NewCatalogProvider("https://grafana.com/api/plugins") + assert.Equal(t, defaultCatalogTTL, provider.ttl) assert.NotNil(t, provider.httpClient) assert.Equal(t, "https://grafana.com/api/plugins", provider.grafanaComAPIURL) }) t.Run("uses default URL when empty", func(t *testing.T) { - provider := NewCloudProvider("") + provider := NewCatalogProvider("") assert.Equal(t, "https://grafana.com/api/plugins", provider.grafanaComAPIURL) }) } -func TestNewCloudProviderWithTTL(t *testing.T) { +func TestNewCatalogProviderWithTTL(t *testing.T) { t.Run("creates provider with custom TTL", func(t *testing.T) { customTTL := 2 * time.Hour - provider := NewCloudProviderWithTTL("https://grafana.com/api/plugins", customTTL) + provider := NewCatalogProviderWithTTL("https://grafana.com/api/plugins", customTTL) assert.Equal(t, customTTL, provider.ttl) }) t.Run("accepts zero TTL", func(t *testing.T) { - provider := NewCloudProviderWithTTL("https://grafana.com/api/plugins", 0) + provider := NewCatalogProviderWithTTL("https://grafana.com/api/plugins", 0) assert.Equal(t, time.Duration(0), provider.ttl) }) t.Run("uses default URL when empty", func(t *testing.T) { - provider := NewCloudProviderWithTTL("", defaultCloudTTL) + provider := NewCatalogProviderWithTTL("", defaultCatalogTTL) assert.Equal(t, "https://grafana.com/api/plugins", provider.grafanaComAPIURL) }) } diff --git a/apps/plugins/pkg/app/meta/core.go b/apps/plugins/pkg/app/meta/core.go index 3452f95b24b..e16f7a23db5 100644 --- a/apps/plugins/pkg/app/meta/core.go +++ b/apps/plugins/pkg/app/meta/core.go @@ -23,7 +23,7 @@ const ( // CoreProvider retrieves plugin metadata for core plugins. type CoreProvider struct { mu sync.RWMutex - loadedPlugins map[string]pluginsv0alpha1.PluginMetaJSONData + loadedPlugins map[string]pluginsv0alpha1.MetaJSONData initialized bool ttl time.Duration } @@ -36,7 +36,7 @@ func NewCoreProvider() *CoreProvider { // NewCoreProviderWithTTL creates a new CoreProvider with a custom TTL. func NewCoreProviderWithTTL(ttl time.Duration) *CoreProvider { return &CoreProvider{ - loadedPlugins: make(map[string]pluginsv0alpha1.PluginMetaJSONData), + loadedPlugins: make(map[string]pluginsv0alpha1.MetaJSONData), ttl: ttl, } } @@ -119,17 +119,17 @@ func (p *CoreProvider) loadPlugins(ctx context.Context) error { } for _, bundle := range ps { - meta := jsonDataToPluginMetaJSONData(bundle.Primary.JSONData) + meta := jsonDataToMetaJSONData(bundle.Primary.JSONData) p.loadedPlugins[bundle.Primary.JSONData.ID] = meta } return nil } -// jsonDataToPluginMetaJSONData converts a plugins.JSONData to a pluginsv0alpha1.PluginMetaJSONData. +// jsonDataToMetaJSONData converts a plugins.JSONData to a pluginsv0alpha1.MetaJSONData. // nolint:gocyclo -func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.PluginMetaJSONData { - meta := pluginsv0alpha1.PluginMetaJSONData{ +func jsonDataToMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.MetaJSONData { + meta := pluginsv0alpha1.MetaJSONData{ Id: jsonData.ID, Name: jsonData.Name, } @@ -137,19 +137,19 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map plugin type switch jsonData.Type { case plugins.TypeApp: - meta.Type = pluginsv0alpha1.PluginMetaJSONDataTypeApp + meta.Type = pluginsv0alpha1.MetaJSONDataTypeApp case plugins.TypeDataSource: - meta.Type = pluginsv0alpha1.PluginMetaJSONDataTypeDatasource + meta.Type = pluginsv0alpha1.MetaJSONDataTypeDatasource case plugins.TypePanel: - meta.Type = pluginsv0alpha1.PluginMetaJSONDataTypePanel + meta.Type = pluginsv0alpha1.MetaJSONDataTypePanel case plugins.TypeRenderer: - meta.Type = pluginsv0alpha1.PluginMetaJSONDataTypeRenderer + meta.Type = pluginsv0alpha1.MetaJSONDataTypeRenderer } // Map Info - meta.Info = pluginsv0alpha1.PluginMetaInfo{ + meta.Info = pluginsv0alpha1.MetaInfo{ Keywords: jsonData.Info.Keywords, - Logos: pluginsv0alpha1.PluginMetaV0alpha1InfoLogos{ + Logos: pluginsv0alpha1.MetaV0alpha1InfoLogos{ Small: jsonData.Info.Logos.Small, Large: jsonData.Info.Logos.Large, }, @@ -162,7 +162,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if jsonData.Info.Author.Name != "" || jsonData.Info.Author.URL != "" { - author := &pluginsv0alpha1.PluginMetaV0alpha1InfoAuthor{} + author := &pluginsv0alpha1.MetaV0alpha1InfoAuthor{} if jsonData.Info.Author.Name != "" { author.Name = &jsonData.Info.Author.Name } @@ -173,9 +173,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Info.Links) > 0 { - meta.Info.Links = make([]pluginsv0alpha1.PluginMetaV0alpha1InfoLinks, 0, len(jsonData.Info.Links)) + meta.Info.Links = make([]pluginsv0alpha1.MetaV0alpha1InfoLinks, 0, len(jsonData.Info.Links)) for _, link := range jsonData.Info.Links { - v0Link := pluginsv0alpha1.PluginMetaV0alpha1InfoLinks{} + v0Link := pluginsv0alpha1.MetaV0alpha1InfoLinks{} if link.Name != "" { v0Link.Name = &link.Name } @@ -187,9 +187,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Info.Screenshots) > 0 { - meta.Info.Screenshots = make([]pluginsv0alpha1.PluginMetaV0alpha1InfoScreenshots, 0, len(jsonData.Info.Screenshots)) + meta.Info.Screenshots = make([]pluginsv0alpha1.MetaV0alpha1InfoScreenshots, 0, len(jsonData.Info.Screenshots)) for _, screenshot := range jsonData.Info.Screenshots { - v0Screenshot := pluginsv0alpha1.PluginMetaV0alpha1InfoScreenshots{} + v0Screenshot := pluginsv0alpha1.MetaV0alpha1InfoScreenshots{} if screenshot.Name != "" { v0Screenshot.Name = &screenshot.Name } @@ -201,7 +201,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } // Map Dependencies - meta.Dependencies = pluginsv0alpha1.PluginMetaDependencies{ + meta.Dependencies = pluginsv0alpha1.MetaDependencies{ GrafanaDependency: jsonData.Dependencies.GrafanaDependency, } @@ -210,18 +210,18 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Dependencies.Plugins) > 0 { - meta.Dependencies.Plugins = make([]pluginsv0alpha1.PluginMetaV0alpha1DependenciesPlugins, 0, len(jsonData.Dependencies.Plugins)) + meta.Dependencies.Plugins = make([]pluginsv0alpha1.MetaV0alpha1DependenciesPlugins, 0, len(jsonData.Dependencies.Plugins)) for _, dep := range jsonData.Dependencies.Plugins { - var depType pluginsv0alpha1.PluginMetaV0alpha1DependenciesPluginsType + var depType pluginsv0alpha1.MetaV0alpha1DependenciesPluginsType switch dep.Type { case "app": - depType = pluginsv0alpha1.PluginMetaV0alpha1DependenciesPluginsTypeApp + depType = pluginsv0alpha1.MetaV0alpha1DependenciesPluginsTypeApp case "datasource": - depType = pluginsv0alpha1.PluginMetaV0alpha1DependenciesPluginsTypeDatasource + depType = pluginsv0alpha1.MetaV0alpha1DependenciesPluginsTypeDatasource case "panel": - depType = pluginsv0alpha1.PluginMetaV0alpha1DependenciesPluginsTypePanel + depType = pluginsv0alpha1.MetaV0alpha1DependenciesPluginsTypePanel } - meta.Dependencies.Plugins = append(meta.Dependencies.Plugins, pluginsv0alpha1.PluginMetaV0alpha1DependenciesPlugins{ + meta.Dependencies.Plugins = append(meta.Dependencies.Plugins, pluginsv0alpha1.MetaV0alpha1DependenciesPlugins{ Id: dep.ID, Type: depType, Name: dep.Name, @@ -230,7 +230,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Dependencies.Extensions.ExposedComponents) > 0 { - meta.Dependencies.Extensions = &pluginsv0alpha1.PluginMetaV0alpha1DependenciesExtensions{ + meta.Dependencies.Extensions = &pluginsv0alpha1.MetaV0alpha1DependenciesExtensions{ ExposedComponents: jsonData.Dependencies.Extensions.ExposedComponents, } } @@ -278,40 +278,40 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map category if jsonData.Category != "" { - var category pluginsv0alpha1.PluginMetaJSONDataCategory + var category pluginsv0alpha1.MetaJSONDataCategory switch jsonData.Category { case "tsdb": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryTsdb + category = pluginsv0alpha1.MetaJSONDataCategoryTsdb case "logging": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryLogging + category = pluginsv0alpha1.MetaJSONDataCategoryLogging case "cloud": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryCloud + category = pluginsv0alpha1.MetaJSONDataCategoryCloud case "tracing": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryTracing + category = pluginsv0alpha1.MetaJSONDataCategoryTracing case "profiling": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryProfiling + category = pluginsv0alpha1.MetaJSONDataCategoryProfiling case "sql": - category = pluginsv0alpha1.PluginMetaJSONDataCategorySql + category = pluginsv0alpha1.MetaJSONDataCategorySql case "enterprise": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryEnterprise + category = pluginsv0alpha1.MetaJSONDataCategoryEnterprise case "iot": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryIot + category = pluginsv0alpha1.MetaJSONDataCategoryIot case "other": - category = pluginsv0alpha1.PluginMetaJSONDataCategoryOther + category = pluginsv0alpha1.MetaJSONDataCategoryOther default: - category = pluginsv0alpha1.PluginMetaJSONDataCategoryOther + category = pluginsv0alpha1.MetaJSONDataCategoryOther } meta.Category = &category } // Map state if jsonData.State != "" { - var state pluginsv0alpha1.PluginMetaJSONDataState + var state pluginsv0alpha1.MetaJSONDataState switch jsonData.State { case plugins.ReleaseStateAlpha: - state = pluginsv0alpha1.PluginMetaJSONDataStateAlpha + state = pluginsv0alpha1.MetaJSONDataStateAlpha case plugins.ReleaseStateBeta: - state = pluginsv0alpha1.PluginMetaJSONDataStateBeta + state = pluginsv0alpha1.MetaJSONDataStateBeta default: } if state != "" { @@ -326,7 +326,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map QueryOptions if len(jsonData.QueryOptions) > 0 { - queryOptions := &pluginsv0alpha1.PluginMetaQueryOptions{} + queryOptions := &pluginsv0alpha1.MetaQueryOptions{} if val, ok := jsonData.QueryOptions["maxDataPoints"]; ok { queryOptions.MaxDataPoints = &val } @@ -341,23 +341,23 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map Includes if len(jsonData.Includes) > 0 { - meta.Includes = make([]pluginsv0alpha1.PluginMetaInclude, 0, len(jsonData.Includes)) + meta.Includes = make([]pluginsv0alpha1.MetaInclude, 0, len(jsonData.Includes)) for _, include := range jsonData.Includes { - v0Include := pluginsv0alpha1.PluginMetaInclude{} + v0Include := pluginsv0alpha1.MetaInclude{} if include.UID != "" { v0Include.Uid = &include.UID } if include.Type != "" { - var includeType pluginsv0alpha1.PluginMetaIncludeType + var includeType pluginsv0alpha1.MetaIncludeType switch include.Type { case "dashboard": - includeType = pluginsv0alpha1.PluginMetaIncludeTypeDashboard + includeType = pluginsv0alpha1.MetaIncludeTypeDashboard case "page": - includeType = pluginsv0alpha1.PluginMetaIncludeTypePage + includeType = pluginsv0alpha1.MetaIncludeTypePage case "panel": - includeType = pluginsv0alpha1.PluginMetaIncludeTypePanel + includeType = pluginsv0alpha1.MetaIncludeTypePanel case "datasource": - includeType = pluginsv0alpha1.PluginMetaIncludeTypeDatasource + includeType = pluginsv0alpha1.MetaIncludeTypeDatasource } v0Include.Type = &includeType } @@ -368,14 +368,14 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu v0Include.Component = &include.Component } if include.Role != "" { - var role pluginsv0alpha1.PluginMetaIncludeRole + var role pluginsv0alpha1.MetaIncludeRole switch include.Role { case "Admin": - role = pluginsv0alpha1.PluginMetaIncludeRoleAdmin + role = pluginsv0alpha1.MetaIncludeRoleAdmin case "Editor": - role = pluginsv0alpha1.PluginMetaIncludeRoleEditor + role = pluginsv0alpha1.MetaIncludeRoleEditor case "Viewer": - role = pluginsv0alpha1.PluginMetaIncludeRoleViewer + role = pluginsv0alpha1.MetaIncludeRoleViewer } v0Include.Role = &role } @@ -400,9 +400,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map Routes if len(jsonData.Routes) > 0 { - meta.Routes = make([]pluginsv0alpha1.PluginMetaRoute, 0, len(jsonData.Routes)) + meta.Routes = make([]pluginsv0alpha1.MetaRoute, 0, len(jsonData.Routes)) for _, route := range jsonData.Routes { - v0Route := pluginsv0alpha1.PluginMetaRoute{} + v0Route := pluginsv0alpha1.MetaRoute{} if route.Path != "" { v0Route.Path = &route.Path } @@ -427,9 +427,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu v0Route.Headers = headers } if len(route.URLParams) > 0 { - v0Route.UrlParams = make([]pluginsv0alpha1.PluginMetaV0alpha1RouteUrlParams, 0, len(route.URLParams)) + v0Route.UrlParams = make([]pluginsv0alpha1.MetaV0alpha1RouteUrlParams, 0, len(route.URLParams)) for _, param := range route.URLParams { - v0Param := pluginsv0alpha1.PluginMetaV0alpha1RouteUrlParams{} + v0Param := pluginsv0alpha1.MetaV0alpha1RouteUrlParams{} if param.Name != "" { v0Param.Name = ¶m.Name } @@ -440,7 +440,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } } if route.TokenAuth != nil { - v0Route.TokenAuth = &pluginsv0alpha1.PluginMetaV0alpha1RouteTokenAuth{} + v0Route.TokenAuth = &pluginsv0alpha1.MetaV0alpha1RouteTokenAuth{} if route.TokenAuth.Url != "" { v0Route.TokenAuth.Url = &route.TokenAuth.Url } @@ -455,7 +455,7 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } } if route.JwtTokenAuth != nil { - v0Route.JwtTokenAuth = &pluginsv0alpha1.PluginMetaV0alpha1RouteJwtTokenAuth{} + v0Route.JwtTokenAuth = &pluginsv0alpha1.MetaV0alpha1RouteJwtTokenAuth{} if route.JwtTokenAuth.Url != "" { v0Route.JwtTokenAuth.Url = &route.JwtTokenAuth.Url } @@ -482,12 +482,12 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map Extensions if len(jsonData.Extensions.AddedLinks) > 0 || len(jsonData.Extensions.AddedComponents) > 0 || len(jsonData.Extensions.ExposedComponents) > 0 || len(jsonData.Extensions.ExtensionPoints) > 0 { - extensions := &pluginsv0alpha1.PluginMetaExtensions{} + extensions := &pluginsv0alpha1.MetaExtensions{} if len(jsonData.Extensions.AddedLinks) > 0 { - extensions.AddedLinks = make([]pluginsv0alpha1.PluginMetaV0alpha1ExtensionsAddedLinks, 0, len(jsonData.Extensions.AddedLinks)) + extensions.AddedLinks = make([]pluginsv0alpha1.MetaV0alpha1ExtensionsAddedLinks, 0, len(jsonData.Extensions.AddedLinks)) for _, link := range jsonData.Extensions.AddedLinks { - v0Link := pluginsv0alpha1.PluginMetaV0alpha1ExtensionsAddedLinks{ + v0Link := pluginsv0alpha1.MetaV0alpha1ExtensionsAddedLinks{ Targets: link.Targets, Title: link.Title, } @@ -499,9 +499,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Extensions.AddedComponents) > 0 { - extensions.AddedComponents = make([]pluginsv0alpha1.PluginMetaV0alpha1ExtensionsAddedComponents, 0, len(jsonData.Extensions.AddedComponents)) + extensions.AddedComponents = make([]pluginsv0alpha1.MetaV0alpha1ExtensionsAddedComponents, 0, len(jsonData.Extensions.AddedComponents)) for _, comp := range jsonData.Extensions.AddedComponents { - v0Comp := pluginsv0alpha1.PluginMetaV0alpha1ExtensionsAddedComponents{ + v0Comp := pluginsv0alpha1.MetaV0alpha1ExtensionsAddedComponents{ Targets: comp.Targets, Title: comp.Title, } @@ -513,9 +513,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Extensions.ExposedComponents) > 0 { - extensions.ExposedComponents = make([]pluginsv0alpha1.PluginMetaV0alpha1ExtensionsExposedComponents, 0, len(jsonData.Extensions.ExposedComponents)) + extensions.ExposedComponents = make([]pluginsv0alpha1.MetaV0alpha1ExtensionsExposedComponents, 0, len(jsonData.Extensions.ExposedComponents)) for _, comp := range jsonData.Extensions.ExposedComponents { - v0Comp := pluginsv0alpha1.PluginMetaV0alpha1ExtensionsExposedComponents{ + v0Comp := pluginsv0alpha1.MetaV0alpha1ExtensionsExposedComponents{ Id: comp.Id, } if comp.Title != "" { @@ -529,9 +529,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu } if len(jsonData.Extensions.ExtensionPoints) > 0 { - extensions.ExtensionPoints = make([]pluginsv0alpha1.PluginMetaV0alpha1ExtensionsExtensionPoints, 0, len(jsonData.Extensions.ExtensionPoints)) + extensions.ExtensionPoints = make([]pluginsv0alpha1.MetaV0alpha1ExtensionsExtensionPoints, 0, len(jsonData.Extensions.ExtensionPoints)) for _, point := range jsonData.Extensions.ExtensionPoints { - v0Point := pluginsv0alpha1.PluginMetaV0alpha1ExtensionsExtensionPoints{ + v0Point := pluginsv0alpha1.MetaV0alpha1ExtensionsExtensionPoints{ Id: point.Id, } if point.Title != "" { @@ -549,13 +549,13 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map Roles if len(jsonData.Roles) > 0 { - meta.Roles = make([]pluginsv0alpha1.PluginMetaRole, 0, len(jsonData.Roles)) + meta.Roles = make([]pluginsv0alpha1.MetaRole, 0, len(jsonData.Roles)) for _, role := range jsonData.Roles { - v0Role := pluginsv0alpha1.PluginMetaRole{ + v0Role := pluginsv0alpha1.MetaRole{ Grants: role.Grants, } if role.Role.Name != "" || role.Role.Description != "" || len(role.Role.Permissions) > 0 { - v0RoleRole := &pluginsv0alpha1.PluginMetaV0alpha1RoleRole{} + v0RoleRole := &pluginsv0alpha1.MetaV0alpha1RoleRole{} if role.Role.Name != "" { v0RoleRole.Name = &role.Role.Name } @@ -563,9 +563,9 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu v0RoleRole.Description = &role.Role.Description } if len(role.Role.Permissions) > 0 { - v0RoleRole.Permissions = make([]pluginsv0alpha1.PluginMetaV0alpha1RoleRolePermissions, 0, len(role.Role.Permissions)) + v0RoleRole.Permissions = make([]pluginsv0alpha1.MetaV0alpha1RoleRolePermissions, 0, len(role.Role.Permissions)) for _, perm := range role.Role.Permissions { - v0Perm := pluginsv0alpha1.PluginMetaV0alpha1RoleRolePermissions{} + v0Perm := pluginsv0alpha1.MetaV0alpha1RoleRolePermissions{} if perm.Action != "" { v0Perm.Action = &perm.Action } @@ -583,11 +583,11 @@ func jsonDataToPluginMetaJSONData(jsonData plugins.JSONData) pluginsv0alpha1.Plu // Map IAM if jsonData.IAM != nil && len(jsonData.IAM.Permissions) > 0 { - iam := &pluginsv0alpha1.PluginMetaIAM{ - Permissions: make([]pluginsv0alpha1.PluginMetaV0alpha1IAMPermissions, 0, len(jsonData.IAM.Permissions)), + iam := &pluginsv0alpha1.MetaIAM{ + Permissions: make([]pluginsv0alpha1.MetaV0alpha1IAMPermissions, 0, len(jsonData.IAM.Permissions)), } for _, perm := range jsonData.IAM.Permissions { - v0Perm := pluginsv0alpha1.PluginMetaV0alpha1IAMPermissions{} + v0Perm := pluginsv0alpha1.MetaV0alpha1IAMPermissions{} if perm.Action != "" { v0Perm.Action = &perm.Action } diff --git a/apps/plugins/pkg/app/meta/core_test.go b/apps/plugins/pkg/app/meta/core_test.go index a9d7103e4a2..d5235c9d120 100644 --- a/apps/plugins/pkg/app/meta/core_test.go +++ b/apps/plugins/pkg/app/meta/core_test.go @@ -22,10 +22,10 @@ func TestCoreProvider_GetMeta(t *testing.T) { t.Run("returns cached plugin when available", func(t *testing.T) { provider := NewCoreProvider() - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider.mu.Lock() @@ -58,10 +58,10 @@ func TestCoreProvider_GetMeta(t *testing.T) { t.Run("ignores version parameter", func(t *testing.T) { provider := NewCoreProvider() - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider.mu.Lock() @@ -81,10 +81,10 @@ func TestCoreProvider_GetMeta(t *testing.T) { customTTL := 2 * time.Hour provider := NewCoreProviderWithTTL(customTTL) - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider.mu.Lock() @@ -271,11 +271,11 @@ func TestJsonDataToMeta(t *testing.T) { }, } - meta := jsonDataToPluginMetaJSONData(jsonData) + meta := jsonDataToMetaJSONData(jsonData) assert.Equal(t, "test-plugin", meta.Id) assert.Equal(t, "Test Plugin", meta.Name) - assert.Equal(t, pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, meta.Type) + assert.Equal(t, pluginsv0alpha1.MetaJSONDataTypeDatasource, meta.Type) assert.Equal(t, "1.0.0", meta.Info.Version) assert.Equal(t, "Test description", *meta.Info.Description) assert.Equal(t, []string{"test", "plugin"}, meta.Info.Keywords) @@ -293,7 +293,7 @@ func TestJsonDataToMeta(t *testing.T) { }, } - meta := jsonDataToPluginMetaJSONData(jsonData) + meta := jsonDataToMetaJSONData(jsonData) assert.Nil(t, meta.Info.Description) assert.Nil(t, meta.Info.Author) diff --git a/apps/plugins/pkg/app/meta/manager.go b/apps/plugins/pkg/app/meta/manager.go index e694e88bba7..7e99d0cc197 100644 --- a/apps/plugins/pkg/app/meta/manager.go +++ b/apps/plugins/pkg/app/meta/manager.go @@ -16,7 +16,7 @@ const ( // cachedMeta represents a cached metadata entry with expiration time type cachedMeta struct { - meta pluginsv0alpha1.PluginMetaJSONData + meta pluginsv0alpha1.MetaJSONData ttl time.Duration expiresAt time.Time } diff --git a/apps/plugins/pkg/app/meta/manager_test.go b/apps/plugins/pkg/app/meta/manager_test.go index 3d3fe3c936c..31a75424a23 100644 --- a/apps/plugins/pkg/app/meta/manager_test.go +++ b/apps/plugins/pkg/app/meta/manager_test.go @@ -35,10 +35,10 @@ func TestProviderManager_GetMeta(t *testing.T) { ctx := context.Background() t.Run("returns cached result when available and not expired", func(t *testing.T) { - cachedMeta := pluginsv0alpha1.PluginMetaJSONData{ + cachedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider := &mockProvider{ @@ -60,7 +60,7 @@ func TestProviderManager_GetMeta(t *testing.T) { provider.getMetaFunc = func(ctx context.Context, pluginID, version string) (*Result, error) { return &Result{ - Meta: pluginsv0alpha1.PluginMetaJSONData{Id: "different"}, + Meta: pluginsv0alpha1.MetaJSONData{Id: "different"}, TTL: time.Hour, }, nil } @@ -73,10 +73,10 @@ func TestProviderManager_GetMeta(t *testing.T) { }) t.Run("fetches from provider when not cached", func(t *testing.T) { - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } expectedTTL := 2 * time.Hour @@ -108,15 +108,15 @@ func TestProviderManager_GetMeta(t *testing.T) { }) t.Run("does not cache result with zero TTL and tries next provider", func(t *testing.T) { - zeroTTLMeta := pluginsv0alpha1.PluginMetaJSONData{ + zeroTTLMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Zero TTL Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider1 := &mockProvider{ @@ -154,10 +154,10 @@ func TestProviderManager_GetMeta(t *testing.T) { }) t.Run("tries next provider when first returns ErrMetaNotFound", func(t *testing.T) { - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider1 := &mockProvider{ @@ -229,15 +229,15 @@ func TestProviderManager_GetMeta(t *testing.T) { }) t.Run("skips expired cache entries", func(t *testing.T) { - expiredMeta := pluginsv0alpha1.PluginMetaJSONData{ + expiredMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Expired Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } - expectedMeta := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Test Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } callCount := 0 @@ -272,15 +272,15 @@ func TestProviderManager_GetMeta(t *testing.T) { }) t.Run("uses first successful provider", func(t *testing.T) { - expectedMeta1 := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta1 := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Provider 1 Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } - expectedMeta2 := pluginsv0alpha1.PluginMetaJSONData{ + expectedMeta2 := pluginsv0alpha1.MetaJSONData{ Id: "test-plugin", Name: "Provider 2 Plugin", - Type: pluginsv0alpha1.PluginMetaJSONDataTypeDatasource, + Type: pluginsv0alpha1.MetaJSONDataTypeDatasource, } provider1 := &mockProvider{ @@ -331,9 +331,9 @@ func TestProviderManager_Run(t *testing.T) { func TestProviderManager_cleanupExpired(t *testing.T) { t.Run("removes expired entries", func(t *testing.T) { - validMeta := pluginsv0alpha1.PluginMetaJSONData{Id: "valid"} - expiredMeta1 := pluginsv0alpha1.PluginMetaJSONData{Id: "expired1"} - expiredMeta2 := pluginsv0alpha1.PluginMetaJSONData{Id: "expired2"} + validMeta := pluginsv0alpha1.MetaJSONData{Id: "valid"} + expiredMeta1 := pluginsv0alpha1.MetaJSONData{Id: "expired1"} + expiredMeta2 := pluginsv0alpha1.MetaJSONData{Id: "expired2"} provider := &mockProvider{ getMetaFunc: func(ctx context.Context, pluginID, version string) (*Result, error) { diff --git a/apps/plugins/pkg/app/meta/provider.go b/apps/plugins/pkg/app/meta/provider.go index 8b5d8b0fcbd..818c0da9dc5 100644 --- a/apps/plugins/pkg/app/meta/provider.go +++ b/apps/plugins/pkg/app/meta/provider.go @@ -14,14 +14,14 @@ var ( // Result contains plugin metadata along with its recommended TTL. type Result struct { - Meta pluginsv0alpha1.PluginMetaJSONData + Meta pluginsv0alpha1.MetaJSONData TTL time.Duration } // Provider is used for retrieving plugin metadata. type Provider interface { // GetMeta retrieves plugin metadata for the given plugin ID and version. - // Returns the Result containing the PluginMetaJSONData and its recommended TTL. + // Returns the Result containing the MetaJSONData and its recommended TTL. // If the plugin is not found, returns ErrMetaNotFound. GetMeta(ctx context.Context, pluginID, version string) (*Result, error) } diff --git a/apps/plugins/pkg/app/storage.go b/apps/plugins/pkg/app/storage.go index 575b1ca21c8..f2dd2ac98d5 100644 --- a/apps/plugins/pkg/app/storage.go +++ b/apps/plugins/pkg/app/storage.go @@ -22,15 +22,15 @@ import ( ) var ( - _ rest.Scoper = (*PluginMetaStorage)(nil) - _ rest.SingularNameProvider = (*PluginMetaStorage)(nil) - _ rest.Getter = (*PluginMetaStorage)(nil) - _ rest.Lister = (*PluginMetaStorage)(nil) - _ rest.Storage = (*PluginMetaStorage)(nil) - _ rest.TableConvertor = (*PluginMetaStorage)(nil) + _ rest.Scoper = (*MetaStorage)(nil) + _ rest.SingularNameProvider = (*MetaStorage)(nil) + _ rest.Getter = (*MetaStorage)(nil) + _ rest.Lister = (*MetaStorage)(nil) + _ rest.Storage = (*MetaStorage)(nil) + _ rest.TableConvertor = (*MetaStorage)(nil) ) -type PluginMetaStorage struct { +type MetaStorage struct { metaManager *meta.ProviderManager client *pluginsv0alpha1.PluginClient clientFactory func(context.Context) (*pluginsv0alpha1.PluginClient, error) @@ -41,16 +41,16 @@ type PluginMetaStorage struct { tableConverter rest.TableConvertor } -func NewPluginMetaStorage( +func NewMetaStorage( metaManager *meta.ProviderManager, clientFactory func(context.Context) (*pluginsv0alpha1.PluginClient, error), -) *PluginMetaStorage { +) *MetaStorage { gr := schema.GroupResource{ Group: pluginsv0alpha1.APIGroup, - Resource: strings.ToLower(pluginsv0alpha1.PluginMetaKind().Plural()), + Resource: strings.ToLower(pluginsv0alpha1.MetaKind().Plural()), } - return &PluginMetaStorage{ + return &MetaStorage{ metaManager: metaManager, clientFactory: clientFactory, gr: gr, @@ -58,7 +58,7 @@ func NewPluginMetaStorage( } } -func (s *PluginMetaStorage) getClient(ctx context.Context) (*pluginsv0alpha1.PluginClient, error) { +func (s *MetaStorage) getClient(ctx context.Context) (*pluginsv0alpha1.PluginClient, error) { s.clientOnce.Do(func() { client, err := s.clientFactory(ctx) if err != nil { @@ -72,29 +72,29 @@ func (s *PluginMetaStorage) getClient(ctx context.Context) (*pluginsv0alpha1.Plu return s.client, s.clientErr } -func (s *PluginMetaStorage) New() runtime.Object { - return pluginsv0alpha1.PluginMetaKind().ZeroValue() +func (s *MetaStorage) New() runtime.Object { + return pluginsv0alpha1.MetaKind().ZeroValue() } -func (s *PluginMetaStorage) Destroy() {} +func (s *MetaStorage) Destroy() {} -func (s *PluginMetaStorage) NamespaceScoped() bool { +func (s *MetaStorage) NamespaceScoped() bool { return true } -func (s *PluginMetaStorage) GetSingularName() string { - return strings.ToLower(pluginsv0alpha1.PluginMetaKind().Kind()) +func (s *MetaStorage) GetSingularName() string { + return strings.ToLower(pluginsv0alpha1.MetaKind().Kind()) } -func (s *PluginMetaStorage) NewList() runtime.Object { - return pluginsv0alpha1.PluginMetaKind().ZeroListValue() +func (s *MetaStorage) NewList() runtime.Object { + return pluginsv0alpha1.MetaKind().ZeroListValue() } -func (s *PluginMetaStorage) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { +func (s *MetaStorage) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { return s.tableConverter.ConvertToTable(ctx, object, tableOptions) } -func (s *PluginMetaStorage) List(ctx context.Context, options *internalversion.ListOptions) (runtime.Object, error) { +func (s *MetaStorage) List(ctx context.Context, options *internalversion.ListOptions) (runtime.Object, error) { ns, err := request.NamespaceInfoFrom(ctx, true) if err != nil { return nil, err @@ -111,8 +111,8 @@ func (s *PluginMetaStorage) List(ctx context.Context, options *internalversion.L return nil, apierrors.NewInternalError(fmt.Errorf("failed to list plugins: %w", err)) } - // Convert each Plugin to PluginMeta - metaItems := make([]pluginsv0alpha1.PluginMeta, 0, len(plugins.Items)) + // Convert each Plugin to Meta + metaItems := make([]pluginsv0alpha1.Meta, 0, len(plugins.Items)) for _, plugin := range plugins.Items { result, err := s.metaManager.GetMeta(ctx, plugin.Spec.Id, plugin.Spec.Version) if err != nil { @@ -121,14 +121,14 @@ func (s *PluginMetaStorage) List(ctx context.Context, options *internalversion.L continue } - pluginMeta := createPluginMetaFromPluginMetaJSONData(result.Meta, plugin.Name, plugin.Namespace) + pluginMeta := createMetaFromMetaJSONData(result.Meta, plugin.Name, plugin.Namespace) metaItems = append(metaItems, *pluginMeta) } - list := &pluginsv0alpha1.PluginMetaList{ + list := &pluginsv0alpha1.MetaList{ TypeMeta: metav1.TypeMeta{ APIVersion: pluginsv0alpha1.APIGroup + "/" + pluginsv0alpha1.APIVersion, - Kind: pluginsv0alpha1.PluginMetaKind().Kind() + "List", + Kind: pluginsv0alpha1.MetaKind().Kind() + "List", }, Items: metaItems, } @@ -136,7 +136,7 @@ func (s *PluginMetaStorage) List(ctx context.Context, options *internalversion.L return list, nil } -func (s *PluginMetaStorage) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { +func (s *MetaStorage) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { ns, err := request.NamespaceInfoFrom(ctx, true) if err != nil { return nil, err @@ -169,17 +169,17 @@ func (s *PluginMetaStorage) Get(ctx context.Context, name string, options *metav return nil, apierrors.NewInternalError(fmt.Errorf("failed to fetch plugin metadata: %w", err)) } - return createPluginMetaFromPluginMetaJSONData(result.Meta, name, ns.Value), nil + return createMetaFromMetaJSONData(result.Meta, name, ns.Value), nil } -// createPluginMetaFromPluginMetaJSONData creates a PluginMeta k8s object from PluginMetaJSONData and plugin metadata. -func createPluginMetaFromPluginMetaJSONData(pluginJSON pluginsv0alpha1.PluginMetaJSONData, name, namespace string) *pluginsv0alpha1.PluginMeta { - pluginMeta := &pluginsv0alpha1.PluginMeta{ +// createMetaFromMetaJSONData creates a Meta k8s object from MetaJSONData and plugin metadata. +func createMetaFromMetaJSONData(pluginJSON pluginsv0alpha1.MetaJSONData, name, namespace string) *pluginsv0alpha1.Meta { + pluginMeta := &pluginsv0alpha1.Meta{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: namespace, }, - Spec: pluginsv0alpha1.PluginMetaSpec{ + Spec: pluginsv0alpha1.MetaSpec{ PluginJSON: pluginJSON, }, } @@ -188,7 +188,7 @@ func createPluginMetaFromPluginMetaJSONData(pluginJSON pluginsv0alpha1.PluginMet pluginMeta.SetGroupVersionKind(schema.GroupVersionKind{ Group: pluginsv0alpha1.APIGroup, Version: pluginsv0alpha1.APIVersion, - Kind: pluginsv0alpha1.PluginMetaKind().Kind(), + Kind: pluginsv0alpha1.MetaKind().Kind(), }) return pluginMeta diff --git a/apps/provisioning/kinds/connection.cue b/apps/provisioning/kinds/connection.cue new file mode 100644 index 00000000000..23af1991c02 --- /dev/null +++ b/apps/provisioning/kinds/connection.cue @@ -0,0 +1,73 @@ +package repository + +connection: { + kind: "Connection" + pluralName: "Connections" + current: "v0alpha1" + validation: { + operations: [ + "CREATE", + "UPDATE", + ] + } + versions: { + "v0alpha1": { + codegen: { + ts: {enabled: false} + go: {enabled: true} + } + schema: { + #GitHubConnectionConfig: { + // App-level information + // GitHub App ID + appID: int + + // Installation-level information + // GitHub App installation ID + installationID: int + } + #BitbucketConnectionConfig: { + // The app clientID + clientID: string + } + #GitlabConnectionConfig: { + // The app clientID + clientID: string + } + #HealthStatus: { + // When not healthy, requests will not be executed + healthy: bool + // When the health was checked last time + checked?: int + // Summary messages (can be shown to users) + // Will only be populated when not healthy + message?: [...string] + } + spec: { + // The connection provider type + type: "github" | "bitbucket" | "gitlab" + // The connection URL + url: *"" | string + // GitHub connection configuration + // Only applicable when provider is "github" + github?: #GitHubConnectionConfig + // Bitbucket connection configuration + // Only applicable when provider is "bitbucket" + bitbucket?: #BitbucketConnectionConfig + // Gitlab connection configuration + // Only applicable when provider is "gitlab" + gitlab?: #GitlabConnectionConfig + } + status: { + // The generation of the spec last time reconciliation ran + observedGeneration?: int + // Connection state + state: "connected" | "disconnected" + // The connection health status + health: #HealthStatus + } + } + } + } +} + diff --git a/apps/provisioning/kinds/manifest.cue b/apps/provisioning/kinds/manifest.cue index 40ffa64d922..d0d751dd62b 100644 --- a/apps/provisioning/kinds/manifest.cue +++ b/apps/provisioning/kinds/manifest.cue @@ -5,5 +5,6 @@ manifest: { groupOverride: "provisioning.grafana.app" kinds: [ repository, + connection ] -} \ No newline at end of file +} diff --git a/apps/provisioning/kinds/repository.cue b/apps/provisioning/kinds/repository.cue index ba36b4b962f..fec3d1f9e20 100644 --- a/apps/provisioning/kinds/repository.cue +++ b/apps/provisioning/kinds/repository.cue @@ -84,6 +84,9 @@ repository: { // When non-zero, the sync will run periodically intervalSeconds?: int } + #ConnectionInfo: { + name: string + } #HealthStatus: { // When not healthy, requests will not be executed healthy: bool @@ -152,6 +155,9 @@ repository: { // The repository on GitLab. // Mutually exclusive with local | github | git. gitlab?: #GitLabRepositoryConfig + // The connection the repository references. + // This means the Repository is interacting with git via a Connection. + connection?: #ConnectionInfo } status: { // The generation of the spec last time reconciliation ran @@ -168,4 +174,4 @@ repository: { } } } -} \ No newline at end of file +} diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/connections.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/connections.go new file mode 100644 index 00000000000..228523f598e --- /dev/null +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/connections.go @@ -0,0 +1,118 @@ +package v0alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1" +) + +// When this code is changed, make sure to update the code generation. +// As of writing, this can be done via the hack dir in the root of the repo: ./hack/update-codegen.sh provisioning +// If you've opened the generated files in this dir at some point in VSCode, you may also have to re-open them to clear errors. +// +genclient +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type Connection struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ConnectionSpec `json:"spec,omitempty"` + Secure ConnectionSecure `json:"secure,omitzero,omitempty"` + Status ConnectionStatus `json:"status,omitempty"` +} + +type ConnectionSecure struct { + // PrivateKey is the reference to the private key used for GitHub App authentication. + // This value is stored securely and cannot be read back + PrivateKey common.InlineSecureValue `json:"privateKey,omitzero,omitempty"` + + // ClientSecret is the reference to the secret used for other providers authentication, + // and Github on-behalf-of authentication. + // This value is stored securely and cannot be read back + ClientSecret common.InlineSecureValue `json:"clientSecret,omitzero,omitempty"` + + // Token is the reference of the token used to act as the Connection. + // This value is stored securely and cannot be read back + Token common.InlineSecureValue `json:"webhook,omitzero,omitempty"` +} + +func (v ConnectionSecure) IsZero() bool { + return v.PrivateKey.IsZero() && v.Token.IsZero() +} + +type GitHubConnectionConfig struct { + // GitHub App ID + AppID string `json:"appID"` + + // GitHub App installation ID + InstallationID string `json:"installationID"` +} + +type BitbucketConnectionConfig struct { + // App client ID + ClientID string `json:"clientID"` +} + +type GitlabConnectionConfig struct { + // App client ID + ClientID string `json:"clientID"` +} + +// ConnectionType defines the types of Connection providers +// +enum +type ConnectionType string + +// ConnectionType values. +const ( + GithubConnectionType ConnectionType = "github" + GitlabConnectionType ConnectionType = "gitlab" + BitbucketConnectionType ConnectionType = "bitbucket" +) + +type ConnectionSpec struct { + // The connection provider type + Type ConnectionType `json:"type"` + // The connection URL + URL string `json:"url,omitempty"` + + // GitHub connection configuration + // Only applicable when provider is "github" + GitHub *GitHubConnectionConfig `json:"github,omitempty"` + // Bitbucket connection configuration + // Only applicable when provider is "bitbucket" + Bitbucket *BitbucketConnectionConfig `json:"bitbucket,omitempty"` + // Gitlab connection configuration + // Only applicable when provider is "gitlab" + Gitlab *GitlabConnectionConfig `json:"gitlab,omitempty"` +} + +// ConnectionState defines the state of a Connection +// +enum +type ConnectionState string + +// ConnectionState values +const ( + ConnectionStateConnected ConnectionState = "connected" + ConnectionStateDisconnected ConnectionState = "disconnected" +) + +// The status of a Connection. +// This is expected never to be created by a kubectl call or similar, and is expected to rarely (if ever) be edited manually. +type ConnectionStatus struct { + // The generation of the spec last time reconciliation ran + ObservedGeneration int64 `json:"observedGeneration"` + + // Connection state + State ConnectionState `json:"state"` + + // The connection health status + Health HealthStatus `json:"health"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type ConnectionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + + // +listType=atomic + Items []Connection `json:"items"` +} diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/health.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/health.go new file mode 100644 index 00000000000..1298580c9a9 --- /dev/null +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/health.go @@ -0,0 +1,26 @@ +package v0alpha1 + +// HealthFailureType represents different types of healthcheck 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"` + + // Summary messages (can be shown to users) + // Will only be populated when not healthy + // +listType=atomic + Message []string `json:"message,omitempty"` +} diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/jobs.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/jobs.go index b96fb1a6d27..2e7700ac4a2 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/jobs.go +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/jobs.go @@ -198,6 +198,7 @@ type JobStatus struct { Finished int64 `json:"finished,omitempty"` Message string `json:"message,omitempty"` Errors []string `json:"errors,omitempty"` + Warnings []string `json:"warnings,omitempty"` // Optional value 0-100 that can be set while running Progress float64 `json:"progress,omitempty"` @@ -225,18 +226,20 @@ type JobResourceSummary struct { Kind string `json:"kind,omitempty"` Total int64 `json:"total,omitempty"` // the count (if known) - Create int64 `json:"create,omitempty"` - Update int64 `json:"update,omitempty"` - Delete int64 `json:"delete,omitempty"` - Write int64 `json:"write,omitempty"` // Create or update (export) - Error int64 `json:"error,omitempty"` // The error count + Create int64 `json:"create,omitempty"` + Update int64 `json:"update,omitempty"` + Delete int64 `json:"delete,omitempty"` + Write int64 `json:"write,omitempty"` // Create or update (export) + Error int64 `json:"error,omitempty"` // The error count + Warning int64 `json:"warning,omitempty"` // The warning count // No action required (useful for sync) Noop int64 `json:"noop,omitempty"` - // Report errors for this resource type + // Report errors/warnings for this resource type // This may not be an exhaustive list and recommend looking at the logs for more info - Errors []string `json:"errors,omitempty"` + Errors []string `json:"errors,omitempty"` + Warnings []string `json:"warnings,omitempty"` } // HistoricJob is an append only log, saving all jobs that have been processed. diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/register.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/register.go index 777484828f6..f06798c0ddd 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/register.go +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/register.go @@ -115,6 +115,47 @@ var HistoricJobResourceInfo = utils.NewResourceInfo(GROUP, VERSION, }, }) +var ConnectionResourceInfo = utils.NewResourceInfo(GROUP, VERSION, + "connections", "connection", "Connection", + func() runtime.Object { return &Connection{} }, // newObj + func() runtime.Object { return &ConnectionList{} }, // newList + utils.TableColumns{ // Returned by `kubectl get`. Doesn't affect disk storage. + Definition: []metav1.TableColumnDefinition{ + {Name: "Name", Type: "string", Format: "name"}, + {Name: "Created At", Type: "date"}, + {Name: "Type", Type: "string"}, + {Name: "AppID", Type: "string"}, + {Name: "InstallationID", Type: "string"}, + {Name: "ClientID", Type: "string"}, + }, + Reader: func(obj any) ([]interface{}, error) { + m, ok := obj.(*Connection) + if !ok { + return nil, errors.New("expected Repository") + } + + var appID, installationID, clientID string + switch m.Spec.Type { + case GithubConnectionType: + appID = m.Spec.GitHub.AppID + installationID = m.Spec.GitHub.InstallationID + case BitbucketConnectionType: + clientID = m.Spec.Bitbucket.ClientID + case GitlabConnectionType: + clientID = m.Spec.Gitlab.ClientID + } + + return []interface{}{ + m.Name, + m.CreationTimestamp.UTC().Format(time.RFC3339), + m.Spec.Type, + appID, + installationID, + clientID, + }, nil + }, + }) + var ( // SchemeGroupVersion is group version used to register these objects SchemeGroupVersion = schema.GroupVersion{Group: GROUP, Version: VERSION} @@ -154,6 +195,8 @@ func AddKnownTypes(gv schema.GroupVersion, scheme *runtime.Scheme) error { &RefList{}, &HistoricJob{}, &HistoricJobList{}, + &Connection{}, + &ConnectionList{}, ) return nil } diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/types.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/types.go index dff7c3813e5..c2247e21809 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/types.go +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/types.go @@ -219,6 +219,10 @@ func (r *Repository) Path() string { return "" } +type ConnectionInfo struct { + Name string `json:"name"` +} + type RepositorySpec struct { // The repository display name (shown in the UI) Title string `json:"title"` @@ -256,6 +260,10 @@ type RepositorySpec struct { // The repository on GitLab. // Mutually exclusive with local | github | git. GitLab *GitLabRepositoryConfig `json:"gitlab,omitempty"` + + // The connection the repository references. + // This means the Repository is interacting with git via a Connection. + Connection *ConnectionInfo `json:"connection,omitempty"` } // SyncTargetType defines where we want all values to resolve @@ -315,31 +323,6 @@ type RepositoryStatus struct { DeleteError string `json:"deleteError,omitempty"` } -// 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"` - - // Summary messages (can be shown to users) - // Will only be populated when not healthy - // +listType=atomic - Message []string `json:"message,omitempty"` -} - type SyncStatus struct { // pending, running, success, error State JobState `json:"state"` diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.deepcopy.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.deepcopy.go index 8a3def39e8d..48d03d23f99 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.deepcopy.go +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.deepcopy.go @@ -27,6 +27,22 @@ func (in *Author) DeepCopy() *Author { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BitbucketConnectionConfig) DeepCopyInto(out *BitbucketConnectionConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BitbucketConnectionConfig. +func (in *BitbucketConnectionConfig) DeepCopy() *BitbucketConnectionConfig { + if in == nil { + return nil + } + out := new(BitbucketConnectionConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BitbucketRepositoryConfig) DeepCopyInto(out *BitbucketRepositoryConfig) { *out = *in @@ -43,6 +59,151 @@ func (in *BitbucketRepositoryConfig) DeepCopy() *BitbucketRepositoryConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Connection) DeepCopyInto(out *Connection) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + out.Secure = in.Secure + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Connection. +func (in *Connection) DeepCopy() *Connection { + if in == nil { + return nil + } + out := new(Connection) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Connection) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionInfo) DeepCopyInto(out *ConnectionInfo) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionInfo. +func (in *ConnectionInfo) DeepCopy() *ConnectionInfo { + if in == nil { + return nil + } + out := new(ConnectionInfo) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionList) DeepCopyInto(out *ConnectionList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Connection, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionList. +func (in *ConnectionList) DeepCopy() *ConnectionList { + if in == nil { + return nil + } + out := new(ConnectionList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ConnectionList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionSecure) DeepCopyInto(out *ConnectionSecure) { + *out = *in + out.PrivateKey = in.PrivateKey + out.ClientSecret = in.ClientSecret + out.Token = in.Token + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionSecure. +func (in *ConnectionSecure) DeepCopy() *ConnectionSecure { + if in == nil { + return nil + } + out := new(ConnectionSecure) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionSpec) DeepCopyInto(out *ConnectionSpec) { + *out = *in + if in.GitHub != nil { + in, out := &in.GitHub, &out.GitHub + *out = new(GitHubConnectionConfig) + **out = **in + } + if in.Bitbucket != nil { + in, out := &in.Bitbucket, &out.Bitbucket + *out = new(BitbucketConnectionConfig) + **out = **in + } + if in.Gitlab != nil { + in, out := &in.Gitlab, &out.Gitlab + *out = new(GitlabConnectionConfig) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionSpec. +func (in *ConnectionSpec) DeepCopy() *ConnectionSpec { + if in == nil { + return nil + } + out := new(ConnectionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConnectionStatus) DeepCopyInto(out *ConnectionStatus) { + *out = *in + in.Health.DeepCopyInto(&out.Health) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConnectionStatus. +func (in *ConnectionStatus) DeepCopy() *ConnectionStatus { + if in == nil { + return nil + } + out := new(ConnectionStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DeleteJobOptions) DeepCopyInto(out *DeleteJobOptions) { *out = *in @@ -148,6 +309,22 @@ func (in *FileList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GitHubConnectionConfig) DeepCopyInto(out *GitHubConnectionConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitHubConnectionConfig. +func (in *GitHubConnectionConfig) DeepCopy() *GitHubConnectionConfig { + if in == nil { + return nil + } + out := new(GitHubConnectionConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitHubRepositoryConfig) DeepCopyInto(out *GitHubRepositoryConfig) { *out = *in @@ -196,6 +373,22 @@ func (in *GitRepositoryConfig) DeepCopy() *GitRepositoryConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *GitlabConnectionConfig) DeepCopyInto(out *GitlabConnectionConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitlabConnectionConfig. +func (in *GitlabConnectionConfig) DeepCopy() *GitlabConnectionConfig { + if in == nil { + return nil + } + out := new(GitlabConnectionConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HealthStatus) DeepCopyInto(out *HealthStatus) { *out = *in @@ -401,6 +594,11 @@ func (in *JobResourceSummary) DeepCopyInto(out *JobResourceSummary) { *out = make([]string, len(*in)) copy(*out, *in) } + if in.Warnings != nil { + in, out := &in.Warnings, &out.Warnings + *out = make([]string, len(*in)) + copy(*out, *in) + } return } @@ -468,6 +666,11 @@ func (in *JobStatus) DeepCopyInto(out *JobStatus) { *out = make([]string, len(*in)) copy(*out, *in) } + if in.Warnings != nil { + in, out := &in.Warnings, &out.Warnings + *out = make([]string, len(*in)) + copy(*out, *in) + } if in.Summary != nil { in, out := &in.Summary, &out.Summary *out = make([]*JobResourceSummary, len(*in)) @@ -735,6 +938,11 @@ func (in *RepositorySpec) DeepCopyInto(out *RepositorySpec) { *out = new(GitLabRepositoryConfig) **out = **in } + if in.Connection != nil { + in, out := &in.Connection, &out.Connection + *out = new(ConnectionInfo) + **out = **in + } return } diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi.go b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi.go index 9a4a99d703a..aeee1d407e1 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi.go +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi.go @@ -15,15 +15,24 @@ import ( func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { return map[string]common.OpenAPIDefinition{ "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.Author": schema_pkg_apis_provisioning_v0alpha1_Author(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketConnectionConfig": schema_pkg_apis_provisioning_v0alpha1_BitbucketConnectionConfig(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketRepositoryConfig": schema_pkg_apis_provisioning_v0alpha1_BitbucketRepositoryConfig(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.Connection": schema_pkg_apis_provisioning_v0alpha1_Connection(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionInfo": schema_pkg_apis_provisioning_v0alpha1_ConnectionInfo(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionList": schema_pkg_apis_provisioning_v0alpha1_ConnectionList(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSecure": schema_pkg_apis_provisioning_v0alpha1_ConnectionSecure(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSpec": schema_pkg_apis_provisioning_v0alpha1_ConnectionSpec(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionStatus": schema_pkg_apis_provisioning_v0alpha1_ConnectionStatus(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.DeleteJobOptions": schema_pkg_apis_provisioning_v0alpha1_DeleteJobOptions(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ErrorDetails": schema_pkg_apis_provisioning_v0alpha1_ErrorDetails(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ExportJobOptions": schema_pkg_apis_provisioning_v0alpha1_ExportJobOptions(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.FileItem": schema_pkg_apis_provisioning_v0alpha1_FileItem(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.FileList": schema_pkg_apis_provisioning_v0alpha1_FileList(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubConnectionConfig": schema_pkg_apis_provisioning_v0alpha1_GitHubConnectionConfig(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubRepositoryConfig": schema_pkg_apis_provisioning_v0alpha1_GitHubRepositoryConfig(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitLabRepositoryConfig": schema_pkg_apis_provisioning_v0alpha1_GitLabRepositoryConfig(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitRepositoryConfig": schema_pkg_apis_provisioning_v0alpha1_GitRepositoryConfig(ref), + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitlabConnectionConfig": schema_pkg_apis_provisioning_v0alpha1_GitlabConnectionConfig(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.HealthStatus": schema_pkg_apis_provisioning_v0alpha1_HealthStatus(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.HistoricJob": schema_pkg_apis_provisioning_v0alpha1_HistoricJob(ref), "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.HistoricJobList": schema_pkg_apis_provisioning_v0alpha1_HistoricJobList(ref), @@ -100,6 +109,27 @@ func schema_pkg_apis_provisioning_v0alpha1_Author(ref common.ReferenceCallback) } } +func schema_pkg_apis_provisioning_v0alpha1_BitbucketConnectionConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clientID": { + SchemaProps: spec.SchemaProps{ + Description: "App client ID", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"clientID"}, + }, + }, + } +} + func schema_pkg_apis_provisioning_v0alpha1_BitbucketRepositoryConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -142,6 +172,256 @@ func schema_pkg_apis_provisioning_v0alpha1_BitbucketRepositoryConfig(ref common. } } +func schema_pkg_apis_provisioning_v0alpha1_Connection(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "When this code is changed, make sure to update the code generation. As of writing, this can be done via the hack dir in the root of the repo: ./hack/update-codegen.sh provisioning If you've opened the generated files in this dir at some point in VSCode, you may also have to re-open them to clear errors.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSpec"), + }, + }, + "secure": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSecure"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionStatus"), + }, + }, + }, + }, + }, + Dependencies: []string{ + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSecure", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionSpec", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"}, + } +} + +func schema_pkg_apis_provisioning_v0alpha1_ConnectionInfo(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"name"}, + }, + }, + } +} + +func schema_pkg_apis_provisioning_v0alpha1_ConnectionList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"), + }, + }, + "items": { + VendorExtensible: spec.VendorExtensible{ + Extensions: spec.Extensions{ + "x-kubernetes-list-type": "atomic", + }, + }, + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.Connection"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.Connection", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"}, + } +} + +func schema_pkg_apis_provisioning_v0alpha1_ConnectionSecure(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "privateKey": { + SchemaProps: spec.SchemaProps{ + Description: "PrivateKey is the reference to the private key used for GitHub App authentication. This value is stored securely and cannot be read back", + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1.InlineSecureValue"), + }, + }, + "clientSecret": { + SchemaProps: spec.SchemaProps{ + Description: "ClientSecret is the reference to the secret used for other providers authentication, and Github on-behalf-of authentication. This value is stored securely and cannot be read back", + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1.InlineSecureValue"), + }, + }, + "webhook": { + SchemaProps: spec.SchemaProps{ + Description: "Token is the reference of the token used to act as the Connection. This value is stored securely and cannot be read back", + 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_ConnectionSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "type": { + SchemaProps: spec.SchemaProps{ + Description: "The connection provider type\n\nPossible enum values:\n - `\"bitbucket\"`\n - `\"github\"`\n - `\"gitlab\"`", + Default: "", + Type: []string{"string"}, + Format: "", + Enum: []interface{}{"bitbucket", "github", "gitlab"}, + }, + }, + "url": { + SchemaProps: spec.SchemaProps{ + Description: "The connection URL", + Type: []string{"string"}, + Format: "", + }, + }, + "github": { + SchemaProps: spec.SchemaProps{ + Description: "GitHub connection configuration Only applicable when provider is \"github\"", + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubConnectionConfig"), + }, + }, + "bitbucket": { + SchemaProps: spec.SchemaProps{ + Description: "Bitbucket connection configuration Only applicable when provider is \"bitbucket\"", + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketConnectionConfig"), + }, + }, + "gitlab": { + SchemaProps: spec.SchemaProps{ + Description: "Gitlab connection configuration Only applicable when provider is \"gitlab\"", + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitlabConnectionConfig"), + }, + }, + }, + Required: []string{"type"}, + }, + }, + Dependencies: []string{ + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketConnectionConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubConnectionConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitlabConnectionConfig"}, + } +} + +func schema_pkg_apis_provisioning_v0alpha1_ConnectionStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "The status of a Connection. This is expected never to be created by a kubectl call or similar, and is expected to rarely (if ever) be edited manually.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "observedGeneration": { + SchemaProps: spec.SchemaProps{ + Description: "The generation of the spec last time reconciliation ran", + Default: 0, + Type: []string{"integer"}, + Format: "int64", + }, + }, + "state": { + SchemaProps: spec.SchemaProps{ + Description: "Connection state\n\nPossible enum values:\n - `\"connected\"`\n - `\"disconnected\"`", + Default: "", + Type: []string{"string"}, + Format: "", + Enum: []interface{}{"connected", "disconnected"}, + }, + }, + "health": { + SchemaProps: spec.SchemaProps{ + Description: "The connection health status", + Default: map[string]interface{}{}, + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.HealthStatus"), + }, + }, + }, + Required: []string{"observedGeneration", "state", "health"}, + }, + }, + Dependencies: []string{ + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.HealthStatus"}, + } +} + func schema_pkg_apis_provisioning_v0alpha1_DeleteJobOptions(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -362,6 +642,35 @@ func schema_pkg_apis_provisioning_v0alpha1_FileList(ref common.ReferenceCallback } } +func schema_pkg_apis_provisioning_v0alpha1_GitHubConnectionConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "appID": { + SchemaProps: spec.SchemaProps{ + Description: "GitHub App ID", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "installationID": { + SchemaProps: spec.SchemaProps{ + Description: "GitHub App installation ID", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"appID", "installationID"}, + }, + }, + } +} + func schema_pkg_apis_provisioning_v0alpha1_GitHubRepositoryConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -481,6 +790,27 @@ func schema_pkg_apis_provisioning_v0alpha1_GitRepositoryConfig(ref common.Refere } } +func schema_pkg_apis_provisioning_v0alpha1_GitlabConnectionConfig(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "clientID": { + SchemaProps: spec.SchemaProps{ + Description: "App client ID", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"clientID"}, + }, + }, + } +} + func schema_pkg_apis_provisioning_v0alpha1_HealthStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -889,6 +1219,13 @@ func schema_pkg_apis_provisioning_v0alpha1_JobResourceSummary(ref common.Referen Format: "int64", }, }, + "warning": { + SchemaProps: spec.SchemaProps{ + Description: "The error count", + Type: []string{"integer"}, + Format: "int64", + }, + }, "noop": { SchemaProps: spec.SchemaProps{ Description: "No action required (useful for sync)", @@ -898,7 +1235,7 @@ func schema_pkg_apis_provisioning_v0alpha1_JobResourceSummary(ref common.Referen }, "errors": { SchemaProps: spec.SchemaProps{ - Description: "Report errors for this resource type This may not be an exhaustive list and recommend looking at the logs for more info", + Description: "Report errors/warnings for this resource type This may not be an exhaustive list and recommend looking at the logs for more info", Type: []string{"array"}, Items: &spec.SchemaOrArray{ Schema: &spec.Schema{ @@ -911,6 +1248,20 @@ func schema_pkg_apis_provisioning_v0alpha1_JobResourceSummary(ref common.Referen }, }, }, + "warnings": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, }, }, }, @@ -1029,6 +1380,20 @@ func schema_pkg_apis_provisioning_v0alpha1_JobStatus(ref common.ReferenceCallbac }, }, }, + "warnings": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, "progress": { SchemaProps: spec.SchemaProps{ Description: "Optional value 0-100 that can be set while running", @@ -1524,12 +1889,18 @@ func schema_pkg_apis_provisioning_v0alpha1_RepositorySpec(ref common.ReferenceCa Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitLabRepositoryConfig"), }, }, + "connection": { + SchemaProps: spec.SchemaProps{ + Description: "The connection the repository references. This means the Repository is interacting with git via a Connection.", + Ref: ref("github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionInfo"), + }, + }, }, Required: []string{"title", "workflows", "sync", "type"}, }, }, Dependencies: []string{ - "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitLabRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.LocalRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SyncOptions"}, + "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.BitbucketRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.ConnectionInfo", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitHubRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitLabRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.GitRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.LocalRepositoryConfig", "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1.SyncOptions"}, } } diff --git a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi_violation_exceptions.list b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi_violation_exceptions.list index c67b1462a9e..b9504855b80 100644 --- a/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi_violation_exceptions.list +++ b/apps/provisioning/pkg/apis/provisioning/v0alpha1/zz_generated.openapi_violation_exceptions.list @@ -1,10 +1,13 @@ +API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ConnectionList,Items API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,DeleteJobOptions,Paths API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,DeleteJobOptions,Resources API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,FileList,Items API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,HistoryList,Items API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobResourceSummary,Errors +API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobResourceSummary,Warnings API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobStatus,Errors API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobStatus,Summary +API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobStatus,Warnings API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ManagerStats,Stats API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,MoveJobOptions,Paths API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,MoveJobOptions,Resources @@ -18,6 +21,8 @@ API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioni API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ResourceList,Items API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,TestResults,Errors API rule violation: list_type_missing,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,WebhookStatus,SubscribedEvents +API rule violation: names_match,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ConnectionSecure,Token +API rule violation: names_match,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ConnectionSpec,GitHub API rule violation: names_match,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobSpec,PullRequest API rule violation: names_match,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,JobStatus,URLs API rule violation: names_match,github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1,ManagerStats,Identity diff --git a/apps/provisioning/pkg/connection/mutator.go b/apps/provisioning/pkg/connection/mutator.go new file mode 100644 index 00000000000..30291669905 --- /dev/null +++ b/apps/provisioning/pkg/connection/mutator.go @@ -0,0 +1,28 @@ +package connection + +import ( + "fmt" + + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" +) + +const ( + githubInstallationURL = "https://github.com/settings/installations" +) + +func MutateConnection(connection *provisioning.Connection) error { + switch connection.Spec.Type { + case provisioning.GithubConnectionType: + // Do nothing in case spec.Github is nil. + // If this field is required, we should fail at validation time. + if connection.Spec.GitHub == nil { + return nil + } + + connection.Spec.URL = fmt.Sprintf("%s/%s", githubInstallationURL, connection.Spec.GitHub.InstallationID) + return nil + default: + // TODO: we need to setup the URL for bitbucket and gitlab. + return nil + } +} diff --git a/apps/provisioning/pkg/connection/mutator_test.go b/apps/provisioning/pkg/connection/mutator_test.go new file mode 100644 index 00000000000..a25aabd10a1 --- /dev/null +++ b/apps/provisioning/pkg/connection/mutator_test.go @@ -0,0 +1,35 @@ +package connection_test + +import ( + "testing" + + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/connection" + common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestMutateConnection(t *testing.T) { + t.Run("should add URL to Github connection", func(t *testing.T) { + c := &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GithubConnectionType, + GitHub: &provisioning.GitHubConnectionConfig{ + AppID: "123", + InstallationID: "456", + }, + }, + Secure: provisioning.ConnectionSecure{ + PrivateKey: common.InlineSecureValue{ + Name: "test-private-key", + }, + }, + } + + require.NoError(t, connection.MutateConnection(c)) + assert.Equal(t, "https://github.com/settings/installations/456", c.Spec.URL) + }) +} diff --git a/apps/provisioning/pkg/connection/validator.go b/apps/provisioning/pkg/connection/validator.go new file mode 100644 index 00000000000..c2537e3af2f --- /dev/null +++ b/apps/provisioning/pkg/connection/validator.go @@ -0,0 +1,104 @@ +package connection + +import ( + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func ValidateConnection(connection *provisioning.Connection) error { + list := field.ErrorList{} + + if connection.Spec.Type == "" { + list = append(list, field.Required(field.NewPath("spec", "type"), "type must be specified")) + } + + switch connection.Spec.Type { + case provisioning.GithubConnectionType: + list = append(list, validateGithubConnection(connection)...) + case provisioning.BitbucketConnectionType: + list = append(list, validateBitbucketConnection(connection)...) + case provisioning.GitlabConnectionType: + list = append(list, validateGitlabConnection(connection)...) + default: + list = append( + list, field.NotSupported( + field.NewPath("spec", "type"), + connection.Spec.Type, + []provisioning.ConnectionType{ + provisioning.GithubConnectionType, + provisioning.BitbucketConnectionType, + provisioning.GitlabConnectionType, + }), + ) + } + + return toError(connection.GetName(), list) +} + +func validateGithubConnection(connection *provisioning.Connection) field.ErrorList { + list := field.ErrorList{} + + if connection.Spec.GitHub == nil { + list = append( + list, field.Required(field.NewPath("spec", "github"), "github info must be specified for GitHub connection"), + ) + } + + if connection.Secure.PrivateKey.IsZero() { + list = append(list, field.Required(field.NewPath("secure", "privateKey"), "privateKey must be specified for GitHub connection")) + } + if !connection.Secure.ClientSecret.IsZero() { + list = append(list, field.Forbidden(field.NewPath("secure", "clientSecret"), "clientSecret is forbidden in GitHub connection")) + } + + return list +} + +func validateBitbucketConnection(connection *provisioning.Connection) field.ErrorList { + list := field.ErrorList{} + + if connection.Spec.Bitbucket == nil { + list = append( + list, field.Required(field.NewPath("spec", "bitbucket"), "bitbucket info must be specified in Bitbucket connection"), + ) + } + if connection.Secure.ClientSecret.IsZero() { + list = append(list, field.Required(field.NewPath("secure", "clientSecret"), "clientSecret must be specified for Bitbucket connection")) + } + if !connection.Secure.PrivateKey.IsZero() { + list = append(list, field.Forbidden(field.NewPath("secure", "privateKey"), "privateKey is forbidden in Bitbucket connection")) + } + + return list +} + +func validateGitlabConnection(connection *provisioning.Connection) field.ErrorList { + list := field.ErrorList{} + + if connection.Spec.Gitlab == nil { + list = append( + list, field.Required(field.NewPath("spec", "gitlab"), "gitlab info must be specified in Gitlab connection"), + ) + } + if connection.Secure.ClientSecret.IsZero() { + list = append(list, field.Required(field.NewPath("secure", "clientSecret"), "clientSecret must be specified for Gitlab connection")) + } + if !connection.Secure.PrivateKey.IsZero() { + list = append(list, field.Forbidden(field.NewPath("secure", "privateKey"), "privateKey is forbidden in Gitlab connection")) + } + + return list +} + +// toError converts a field.ErrorList to an error, returning nil if the list is empty +func toError(name string, list field.ErrorList) error { + if len(list) == 0 { + return nil + } + return apierrors.NewInvalid( + provisioning.ConnectionResourceInfo.GroupVersionKind().GroupKind(), + name, + list, + ) +} diff --git a/apps/provisioning/pkg/connection/validator_test.go b/apps/provisioning/pkg/connection/validator_test.go new file mode 100644 index 00000000000..23d4b01b800 --- /dev/null +++ b/apps/provisioning/pkg/connection/validator_test.go @@ -0,0 +1,253 @@ +package connection_test + +import ( + "testing" + + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/connection" + common "github.com/grafana/grafana/pkg/apimachinery/apis/common/v0alpha1" + "github.com/stretchr/testify/assert" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestValidateConnection(t *testing.T) { + tests := []struct { + name string + connection *provisioning.Connection + wantErr bool + errMsg string + }{ + { + name: "empty type returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{}, + }, + wantErr: true, + errMsg: "spec.type", + }, + { + name: "invalid type returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: "invalid", + }, + }, + wantErr: true, + errMsg: "spec.type", + }, + { + name: "github type without github config returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GithubConnectionType, + }, + }, + wantErr: true, + errMsg: "spec.github", + }, + { + name: "github type without private key returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GithubConnectionType, + GitHub: &provisioning.GitHubConnectionConfig{ + AppID: "123", + InstallationID: "456", + }, + }, + }, + wantErr: true, + errMsg: "secure.privateKey", + }, + { + name: "github type with client secret returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GithubConnectionType, + GitHub: &provisioning.GitHubConnectionConfig{ + AppID: "123", + InstallationID: "456", + }, + }, + Secure: provisioning.ConnectionSecure{ + PrivateKey: common.InlineSecureValue{ + Name: "test-private-key", + }, + ClientSecret: common.InlineSecureValue{ + Name: "test-client-secret", + }, + }, + }, + wantErr: true, + errMsg: "secure.clientSecret", + }, + { + name: "github type with github config is valid", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GithubConnectionType, + GitHub: &provisioning.GitHubConnectionConfig{ + AppID: "123", + InstallationID: "456", + }, + }, + Secure: provisioning.ConnectionSecure{ + PrivateKey: common.InlineSecureValue{ + Name: "test-private-key", + }, + }, + }, + wantErr: false, + }, + { + name: "bitbucket type without bitbucket config returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.BitbucketConnectionType, + }, + }, + wantErr: true, + errMsg: "spec.bitbucket", + }, + { + name: "bitbucket type without client secret returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.BitbucketConnectionType, + Bitbucket: &provisioning.BitbucketConnectionConfig{ + ClientID: "client-123", + }, + }, + }, + wantErr: true, + errMsg: "secure.clientSecret", + }, + { + name: "bitbucket type with private key returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.BitbucketConnectionType, + Bitbucket: &provisioning.BitbucketConnectionConfig{ + ClientID: "client-123", + }, + }, + Secure: provisioning.ConnectionSecure{ + PrivateKey: common.InlineSecureValue{ + Name: "test-private-key", + }, + ClientSecret: common.InlineSecureValue{ + Name: "test-client-secret", + }, + }, + }, + wantErr: true, + errMsg: "secure.privateKey", + }, + { + name: "bitbucket type with bitbucket config is valid", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.BitbucketConnectionType, + Bitbucket: &provisioning.BitbucketConnectionConfig{ + ClientID: "client-123", + }, + }, + Secure: provisioning.ConnectionSecure{ + ClientSecret: common.InlineSecureValue{ + Name: "test-client-secret", + }, + }, + }, + wantErr: false, + }, + { + name: "gitlab type without gitlab config returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GitlabConnectionType, + }, + }, + wantErr: true, + errMsg: "spec.gitlab", + }, + { + name: "gitlab type without client secret returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GitlabConnectionType, + Gitlab: &provisioning.GitlabConnectionConfig{ + ClientID: "client-456", + }, + }, + }, + wantErr: true, + errMsg: "secure.clientSecret", + }, + { + name: "gitlab type with private key returns error", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GitlabConnectionType, + Gitlab: &provisioning.GitlabConnectionConfig{ + ClientID: "client-456", + }, + }, + Secure: provisioning.ConnectionSecure{ + PrivateKey: common.InlineSecureValue{ + Name: "test-private-key", + }, + ClientSecret: common.InlineSecureValue{ + Name: "test-client-secret", + }, + }, + }, + wantErr: true, + errMsg: "secure.privateKey", + }, + { + name: "gitlab type with gitlab config is valid", + connection: &provisioning.Connection{ + ObjectMeta: metav1.ObjectMeta{Name: "test-connection"}, + Spec: provisioning.ConnectionSpec{ + Type: provisioning.GitlabConnectionType, + Gitlab: &provisioning.GitlabConnectionConfig{ + ClientID: "client-456", + }, + }, + Secure: provisioning.ConnectionSecure{ + ClientSecret: common.InlineSecureValue{ + Name: "test-client-secret", + }, + }, + }, + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := connection.ValidateConnection(tt.connection) + if tt.wantErr { + assert.Error(t, err) + if tt.errMsg != "" { + assert.Contains(t, err.Error(), tt.errMsg) + } + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/bitbucketconnectionconfig.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/bitbucketconnectionconfig.go new file mode 100644 index 00000000000..9a3604afe71 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/bitbucketconnectionconfig.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +// BitbucketConnectionConfigApplyConfiguration represents a declarative configuration of the BitbucketConnectionConfig type for use +// with apply. +type BitbucketConnectionConfigApplyConfiguration struct { + ClientID *string `json:"clientID,omitempty"` +} + +// BitbucketConnectionConfigApplyConfiguration constructs a declarative configuration of the BitbucketConnectionConfig type for use with +// apply. +func BitbucketConnectionConfig() *BitbucketConnectionConfigApplyConfiguration { + return &BitbucketConnectionConfigApplyConfiguration{} +} + +// WithClientID sets the ClientID 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 ClientID field is set to the value of the last call. +func (b *BitbucketConnectionConfigApplyConfiguration) WithClientID(value string) *BitbucketConnectionConfigApplyConfiguration { + b.ClientID = &value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connection.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connection.go new file mode 100644 index 00000000000..a7a56c62a14 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connection.go @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + v1 "k8s.io/client-go/applyconfigurations/meta/v1" +) + +// ConnectionApplyConfiguration represents a declarative configuration of the Connection type for use +// with apply. +type ConnectionApplyConfiguration struct { + v1.TypeMetaApplyConfiguration `json:",inline"` + *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` + Spec *ConnectionSpecApplyConfiguration `json:"spec,omitempty"` + Secure *ConnectionSecureApplyConfiguration `json:"secure,omitempty"` + Status *ConnectionStatusApplyConfiguration `json:"status,omitempty"` +} + +// Connection constructs a declarative configuration of the Connection type for use with +// apply. +func Connection(name, namespace string) *ConnectionApplyConfiguration { + b := &ConnectionApplyConfiguration{} + b.WithName(name) + b.WithNamespace(namespace) + b.WithKind("Connection") + b.WithAPIVersion("provisioning.grafana.app/v0alpha1") + return b +} +func (b ConnectionApplyConfiguration) IsApplyConfiguration() {} + +// WithKind sets the Kind 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 Kind field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithKind(value string) *ConnectionApplyConfiguration { + b.TypeMetaApplyConfiguration.Kind = &value + return b +} + +// WithAPIVersion sets the APIVersion 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 APIVersion field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithAPIVersion(value string) *ConnectionApplyConfiguration { + b.TypeMetaApplyConfiguration.APIVersion = &value + return b +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithName(value string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Name = &value + return b +} + +// WithGenerateName sets the GenerateName 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 GenerateName field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithGenerateName(value string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.GenerateName = &value + return b +} + +// WithNamespace sets the Namespace 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 Namespace field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithNamespace(value string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Namespace = &value + return b +} + +// WithUID sets the UID 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 UID field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithUID(value types.UID) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.UID = &value + return b +} + +// WithResourceVersion sets the ResourceVersion 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 ResourceVersion field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithResourceVersion(value string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.ResourceVersion = &value + return b +} + +// WithGeneration sets the Generation 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 Generation field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithGeneration(value int64) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.Generation = &value + return b +} + +// WithCreationTimestamp sets the CreationTimestamp 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 CreationTimestamp field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.CreationTimestamp = &value + return b +} + +// WithDeletionTimestamp sets the DeletionTimestamp 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 DeletionTimestamp field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionTimestamp = &value + return b +} + +// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds 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 DeletionGracePeriodSeconds field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + b.ObjectMetaApplyConfiguration.DeletionGracePeriodSeconds = &value + return b +} + +// WithLabels puts the entries into the Labels field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Labels field, +// overwriting an existing map entries in Labels field with the same key. +func (b *ConnectionApplyConfiguration) WithLabels(entries map[string]string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Labels == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Labels = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Labels[k] = v + } + return b +} + +// WithAnnotations puts the entries into the Annotations field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the Annotations field, +// overwriting an existing map entries in Annotations field with the same key. +func (b *ConnectionApplyConfiguration) WithAnnotations(entries map[string]string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + if b.ObjectMetaApplyConfiguration.Annotations == nil && len(entries) > 0 { + b.ObjectMetaApplyConfiguration.Annotations = make(map[string]string, len(entries)) + } + for k, v := range entries { + b.ObjectMetaApplyConfiguration.Annotations[k] = v + } + return b +} + +// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the OwnerReferences field. +func (b *ConnectionApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + if values[i] == nil { + panic("nil value passed to WithOwnerReferences") + } + b.ObjectMetaApplyConfiguration.OwnerReferences = append(b.ObjectMetaApplyConfiguration.OwnerReferences, *values[i]) + } + return b +} + +// WithFinalizers adds the given value to the Finalizers field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Finalizers field. +func (b *ConnectionApplyConfiguration) WithFinalizers(values ...string) *ConnectionApplyConfiguration { + b.ensureObjectMetaApplyConfigurationExists() + for i := range values { + b.ObjectMetaApplyConfiguration.Finalizers = append(b.ObjectMetaApplyConfiguration.Finalizers, values[i]) + } + return b +} + +func (b *ConnectionApplyConfiguration) ensureObjectMetaApplyConfigurationExists() { + if b.ObjectMetaApplyConfiguration == nil { + b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{} + } +} + +// WithSpec sets the Spec 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 Spec field is set to the value of the last call. +func (b *ConnectionApplyConfiguration) WithSpec(value *ConnectionSpecApplyConfiguration) *ConnectionApplyConfiguration { + b.Spec = value + 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 *ConnectionApplyConfiguration) WithSecure(value *ConnectionSecureApplyConfiguration) *ConnectionApplyConfiguration { + 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. +func (b *ConnectionApplyConfiguration) WithStatus(value *ConnectionStatusApplyConfiguration) *ConnectionApplyConfiguration { + b.Status = value + return b +} + +// GetKind retrieves the value of the Kind field in the declarative configuration. +func (b *ConnectionApplyConfiguration) GetKind() *string { + return b.TypeMetaApplyConfiguration.Kind +} + +// GetAPIVersion retrieves the value of the APIVersion field in the declarative configuration. +func (b *ConnectionApplyConfiguration) GetAPIVersion() *string { + return b.TypeMetaApplyConfiguration.APIVersion +} + +// GetName retrieves the value of the Name field in the declarative configuration. +func (b *ConnectionApplyConfiguration) GetName() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Name +} + +// GetNamespace retrieves the value of the Namespace field in the declarative configuration. +func (b *ConnectionApplyConfiguration) GetNamespace() *string { + b.ensureObjectMetaApplyConfigurationExists() + return b.ObjectMetaApplyConfiguration.Namespace +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectioninfo.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectioninfo.go new file mode 100644 index 00000000000..87e4aa7e180 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectioninfo.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +// ConnectionInfoApplyConfiguration represents a declarative configuration of the ConnectionInfo type for use +// with apply. +type ConnectionInfoApplyConfiguration struct { + Name *string `json:"name,omitempty"` +} + +// ConnectionInfoApplyConfiguration constructs a declarative configuration of the ConnectionInfo type for use with +// apply. +func ConnectionInfo() *ConnectionInfoApplyConfiguration { + return &ConnectionInfoApplyConfiguration{} +} + +// WithName sets the Name 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 Name field is set to the value of the last call. +func (b *ConnectionInfoApplyConfiguration) WithName(value string) *ConnectionInfoApplyConfiguration { + b.Name = &value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionsecure.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionsecure.go new file mode 100644 index 00000000000..8ac26b192c9 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionsecure.go @@ -0,0 +1,47 @@ +// 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" +) + +// ConnectionSecureApplyConfiguration represents a declarative configuration of the ConnectionSecure type for use +// with apply. +type ConnectionSecureApplyConfiguration struct { + PrivateKey *commonv0alpha1.InlineSecureValue `json:"privateKey,omitempty"` + ClientSecret *commonv0alpha1.InlineSecureValue `json:"clientSecret,omitempty"` + Token *commonv0alpha1.InlineSecureValue `json:"webhook,omitempty"` +} + +// ConnectionSecureApplyConfiguration constructs a declarative configuration of the ConnectionSecure type for use with +// apply. +func ConnectionSecure() *ConnectionSecureApplyConfiguration { + return &ConnectionSecureApplyConfiguration{} +} + +// WithPrivateKey sets the PrivateKey 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 PrivateKey field is set to the value of the last call. +func (b *ConnectionSecureApplyConfiguration) WithPrivateKey(value commonv0alpha1.InlineSecureValue) *ConnectionSecureApplyConfiguration { + b.PrivateKey = &value + return b +} + +// WithClientSecret sets the ClientSecret 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 ClientSecret field is set to the value of the last call. +func (b *ConnectionSecureApplyConfiguration) WithClientSecret(value commonv0alpha1.InlineSecureValue) *ConnectionSecureApplyConfiguration { + b.ClientSecret = &value + return b +} + +// 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 *ConnectionSecureApplyConfiguration) WithToken(value commonv0alpha1.InlineSecureValue) *ConnectionSecureApplyConfiguration { + b.Token = &value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionspec.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionspec.go new file mode 100644 index 00000000000..1b55b832ae1 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionspec.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" +) + +// ConnectionSpecApplyConfiguration represents a declarative configuration of the ConnectionSpec type for use +// with apply. +type ConnectionSpecApplyConfiguration struct { + Type *provisioningv0alpha1.ConnectionType `json:"type,omitempty"` + URL *string `json:"url,omitempty"` + GitHub *GitHubConnectionConfigApplyConfiguration `json:"github,omitempty"` + Bitbucket *BitbucketConnectionConfigApplyConfiguration `json:"bitbucket,omitempty"` + Gitlab *GitlabConnectionConfigApplyConfiguration `json:"gitlab,omitempty"` +} + +// ConnectionSpecApplyConfiguration constructs a declarative configuration of the ConnectionSpec type for use with +// apply. +func ConnectionSpec() *ConnectionSpecApplyConfiguration { + return &ConnectionSpecApplyConfiguration{} +} + +// WithType sets the Type 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 Type field is set to the value of the last call. +func (b *ConnectionSpecApplyConfiguration) WithType(value provisioningv0alpha1.ConnectionType) *ConnectionSpecApplyConfiguration { + b.Type = &value + return b +} + +// WithURL sets the URL 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 URL field is set to the value of the last call. +func (b *ConnectionSpecApplyConfiguration) WithURL(value string) *ConnectionSpecApplyConfiguration { + b.URL = &value + return b +} + +// WithGitHub sets the GitHub 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 GitHub field is set to the value of the last call. +func (b *ConnectionSpecApplyConfiguration) WithGitHub(value *GitHubConnectionConfigApplyConfiguration) *ConnectionSpecApplyConfiguration { + b.GitHub = value + return b +} + +// WithBitbucket sets the Bitbucket 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 Bitbucket field is set to the value of the last call. +func (b *ConnectionSpecApplyConfiguration) WithBitbucket(value *BitbucketConnectionConfigApplyConfiguration) *ConnectionSpecApplyConfiguration { + b.Bitbucket = value + return b +} + +// WithGitlab sets the Gitlab 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 Gitlab field is set to the value of the last call. +func (b *ConnectionSpecApplyConfiguration) WithGitlab(value *GitlabConnectionConfigApplyConfiguration) *ConnectionSpecApplyConfiguration { + b.Gitlab = value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionstatus.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionstatus.go new file mode 100644 index 00000000000..b9d510aac91 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/connectionstatus.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" +) + +// ConnectionStatusApplyConfiguration represents a declarative configuration of the ConnectionStatus type for use +// with apply. +type ConnectionStatusApplyConfiguration struct { + ObservedGeneration *int64 `json:"observedGeneration,omitempty"` + State *provisioningv0alpha1.ConnectionState `json:"state,omitempty"` + Health *HealthStatusApplyConfiguration `json:"health,omitempty"` +} + +// ConnectionStatusApplyConfiguration constructs a declarative configuration of the ConnectionStatus type for use with +// apply. +func ConnectionStatus() *ConnectionStatusApplyConfiguration { + return &ConnectionStatusApplyConfiguration{} +} + +// WithObservedGeneration sets the ObservedGeneration 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 ObservedGeneration field is set to the value of the last call. +func (b *ConnectionStatusApplyConfiguration) WithObservedGeneration(value int64) *ConnectionStatusApplyConfiguration { + b.ObservedGeneration = &value + return b +} + +// WithState sets the State 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 State field is set to the value of the last call. +func (b *ConnectionStatusApplyConfiguration) WithState(value provisioningv0alpha1.ConnectionState) *ConnectionStatusApplyConfiguration { + b.State = &value + return b +} + +// WithHealth sets the Health 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 Health field is set to the value of the last call. +func (b *ConnectionStatusApplyConfiguration) WithHealth(value *HealthStatusApplyConfiguration) *ConnectionStatusApplyConfiguration { + b.Health = value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/githubconnectionconfig.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/githubconnectionconfig.go new file mode 100644 index 00000000000..c2f2a8b291b --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/githubconnectionconfig.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +// GitHubConnectionConfigApplyConfiguration represents a declarative configuration of the GitHubConnectionConfig type for use +// with apply. +type GitHubConnectionConfigApplyConfiguration struct { + AppID *string `json:"appID,omitempty"` + InstallationID *string `json:"installationID,omitempty"` +} + +// GitHubConnectionConfigApplyConfiguration constructs a declarative configuration of the GitHubConnectionConfig type for use with +// apply. +func GitHubConnectionConfig() *GitHubConnectionConfigApplyConfiguration { + return &GitHubConnectionConfigApplyConfiguration{} +} + +// WithAppID sets the AppID 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 AppID field is set to the value of the last call. +func (b *GitHubConnectionConfigApplyConfiguration) WithAppID(value string) *GitHubConnectionConfigApplyConfiguration { + b.AppID = &value + return b +} + +// WithInstallationID sets the InstallationID 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 InstallationID field is set to the value of the last call. +func (b *GitHubConnectionConfigApplyConfiguration) WithInstallationID(value string) *GitHubConnectionConfigApplyConfiguration { + b.InstallationID = &value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/gitlabconnectionconfig.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/gitlabconnectionconfig.go new file mode 100644 index 00000000000..0238ae3c226 --- /dev/null +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/gitlabconnectionconfig.go @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v0alpha1 + +// GitlabConnectionConfigApplyConfiguration represents a declarative configuration of the GitlabConnectionConfig type for use +// with apply. +type GitlabConnectionConfigApplyConfiguration struct { + ClientID *string `json:"clientID,omitempty"` +} + +// GitlabConnectionConfigApplyConfiguration constructs a declarative configuration of the GitlabConnectionConfig type for use with +// apply. +func GitlabConnectionConfig() *GitlabConnectionConfigApplyConfiguration { + return &GitlabConnectionConfigApplyConfiguration{} +} + +// WithClientID sets the ClientID 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 ClientID field is set to the value of the last call. +func (b *GitlabConnectionConfigApplyConfiguration) WithClientID(value string) *GitlabConnectionConfigApplyConfiguration { + b.ClientID = &value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobresourcesummary.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobresourcesummary.go index ed6a62f651a..8986d2f85a6 100644 --- a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobresourcesummary.go +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobresourcesummary.go @@ -7,16 +7,18 @@ package v0alpha1 // JobResourceSummaryApplyConfiguration represents a declarative configuration of the JobResourceSummary type for use // with apply. type JobResourceSummaryApplyConfiguration struct { - Group *string `json:"group,omitempty"` - Kind *string `json:"kind,omitempty"` - Total *int64 `json:"total,omitempty"` - Create *int64 `json:"create,omitempty"` - Update *int64 `json:"update,omitempty"` - Delete *int64 `json:"delete,omitempty"` - Write *int64 `json:"write,omitempty"` - Error *int64 `json:"error,omitempty"` - Noop *int64 `json:"noop,omitempty"` - Errors []string `json:"errors,omitempty"` + Group *string `json:"group,omitempty"` + Kind *string `json:"kind,omitempty"` + Total *int64 `json:"total,omitempty"` + Create *int64 `json:"create,omitempty"` + Update *int64 `json:"update,omitempty"` + Delete *int64 `json:"delete,omitempty"` + Write *int64 `json:"write,omitempty"` + Error *int64 `json:"error,omitempty"` + Warning *int64 `json:"warning,omitempty"` + Noop *int64 `json:"noop,omitempty"` + Errors []string `json:"errors,omitempty"` + Warnings []string `json:"warnings,omitempty"` } // JobResourceSummaryApplyConfiguration constructs a declarative configuration of the JobResourceSummary type for use with @@ -89,6 +91,14 @@ func (b *JobResourceSummaryApplyConfiguration) WithError(value int64) *JobResour return b } +// WithWarning sets the Warning 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 Warning field is set to the value of the last call. +func (b *JobResourceSummaryApplyConfiguration) WithWarning(value int64) *JobResourceSummaryApplyConfiguration { + b.Warning = &value + return b +} + // WithNoop sets the Noop 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 Noop field is set to the value of the last call. @@ -106,3 +116,13 @@ func (b *JobResourceSummaryApplyConfiguration) WithErrors(values ...string) *Job } return b } + +// WithWarnings adds the given value to the Warnings field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Warnings field. +func (b *JobResourceSummaryApplyConfiguration) WithWarnings(values ...string) *JobResourceSummaryApplyConfiguration { + for i := range values { + b.Warnings = append(b.Warnings, values[i]) + } + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobstatus.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobstatus.go index ea9228473a5..0ad62090c62 100644 --- a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobstatus.go +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/jobstatus.go @@ -16,6 +16,7 @@ type JobStatusApplyConfiguration struct { Finished *int64 `json:"finished,omitempty"` Message *string `json:"message,omitempty"` Errors []string `json:"errors,omitempty"` + Warnings []string `json:"warnings,omitempty"` Progress *float64 `json:"progress,omitempty"` Summary []*provisioningv0alpha1.JobResourceSummary `json:"summary,omitempty"` URLs *RepositoryURLsApplyConfiguration `json:"url,omitempty"` @@ -69,6 +70,16 @@ func (b *JobStatusApplyConfiguration) WithErrors(values ...string) *JobStatusApp return b } +// WithWarnings adds the given value to the Warnings field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, values provided by each call will be appended to the Warnings field. +func (b *JobStatusApplyConfiguration) WithWarnings(values ...string) *JobStatusApplyConfiguration { + for i := range values { + b.Warnings = append(b.Warnings, values[i]) + } + return b +} + // WithProgress sets the Progress 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 Progress field is set to the value of the last call. diff --git a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/repositoryspec.go b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/repositoryspec.go index 6fff6f2de42..5caf805702b 100644 --- a/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/repositoryspec.go +++ b/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1/repositoryspec.go @@ -21,6 +21,7 @@ type RepositorySpecApplyConfiguration struct { Git *GitRepositoryConfigApplyConfiguration `json:"git,omitempty"` Bitbucket *BitbucketRepositoryConfigApplyConfiguration `json:"bitbucket,omitempty"` GitLab *GitLabRepositoryConfigApplyConfiguration `json:"gitlab,omitempty"` + Connection *ConnectionInfoApplyConfiguration `json:"connection,omitempty"` } // RepositorySpecApplyConfiguration constructs a declarative configuration of the RepositorySpec type for use with @@ -110,3 +111,11 @@ func (b *RepositorySpecApplyConfiguration) WithGitLab(value *GitLabRepositoryCon b.GitLab = value return b } + +// WithConnection sets the Connection 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 Connection field is set to the value of the last call. +func (b *RepositorySpecApplyConfiguration) WithConnection(value *ConnectionInfoApplyConfiguration) *RepositorySpecApplyConfiguration { + b.Connection = value + return b +} diff --git a/apps/provisioning/pkg/generated/applyconfiguration/utils.go b/apps/provisioning/pkg/generated/applyconfiguration/utils.go index 400f2b7c083..7168418b82d 100644 --- a/apps/provisioning/pkg/generated/applyconfiguration/utils.go +++ b/apps/provisioning/pkg/generated/applyconfiguration/utils.go @@ -18,14 +18,30 @@ import ( func ForKind(kind schema.GroupVersionKind) interface{} { switch kind { // Group=provisioning.grafana.app, Version=v0alpha1 + case v0alpha1.SchemeGroupVersion.WithKind("BitbucketConnectionConfig"): + return &provisioningv0alpha1.BitbucketConnectionConfigApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("BitbucketRepositoryConfig"): return &provisioningv0alpha1.BitbucketRepositoryConfigApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("Connection"): + return &provisioningv0alpha1.ConnectionApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("ConnectionInfo"): + return &provisioningv0alpha1.ConnectionInfoApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("ConnectionSecure"): + return &provisioningv0alpha1.ConnectionSecureApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("ConnectionSpec"): + return &provisioningv0alpha1.ConnectionSpecApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("ConnectionStatus"): + return &provisioningv0alpha1.ConnectionStatusApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("DeleteJobOptions"): return &provisioningv0alpha1.DeleteJobOptionsApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("ExportJobOptions"): return &provisioningv0alpha1.ExportJobOptionsApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("GitHubConnectionConfig"): + return &provisioningv0alpha1.GitHubConnectionConfigApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("GitHubRepositoryConfig"): return &provisioningv0alpha1.GitHubRepositoryConfigApplyConfiguration{} + case v0alpha1.SchemeGroupVersion.WithKind("GitlabConnectionConfig"): + return &provisioningv0alpha1.GitlabConnectionConfigApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("GitLabRepositoryConfig"): return &provisioningv0alpha1.GitLabRepositoryConfigApplyConfiguration{} case v0alpha1.SchemeGroupVersion.WithKind("GitRepositoryConfig"): diff --git a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/connection.go b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/connection.go new file mode 100644 index 00000000000..fe585e5c0bb --- /dev/null +++ b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/connection.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by client-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + context "context" + + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + applyconfigurationprovisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1" + scheme "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + gentype "k8s.io/client-go/gentype" +) + +// ConnectionsGetter has a method to return a ConnectionInterface. +// A group's client should implement this interface. +type ConnectionsGetter interface { + Connections(namespace string) ConnectionInterface +} + +// ConnectionInterface has methods to work with Connection resources. +type ConnectionInterface interface { + Create(ctx context.Context, connection *provisioningv0alpha1.Connection, opts v1.CreateOptions) (*provisioningv0alpha1.Connection, error) + Update(ctx context.Context, connection *provisioningv0alpha1.Connection, opts v1.UpdateOptions) (*provisioningv0alpha1.Connection, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, connection *provisioningv0alpha1.Connection, opts v1.UpdateOptions) (*provisioningv0alpha1.Connection, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*provisioningv0alpha1.Connection, error) + List(ctx context.Context, opts v1.ListOptions) (*provisioningv0alpha1.ConnectionList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *provisioningv0alpha1.Connection, err error) + Apply(ctx context.Context, connection *applyconfigurationprovisioningv0alpha1.ConnectionApplyConfiguration, opts v1.ApplyOptions) (result *provisioningv0alpha1.Connection, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, connection *applyconfigurationprovisioningv0alpha1.ConnectionApplyConfiguration, opts v1.ApplyOptions) (result *provisioningv0alpha1.Connection, err error) + ConnectionExpansion +} + +// connections implements ConnectionInterface +type connections struct { + *gentype.ClientWithListAndApply[*provisioningv0alpha1.Connection, *provisioningv0alpha1.ConnectionList, *applyconfigurationprovisioningv0alpha1.ConnectionApplyConfiguration] +} + +// newConnections returns a Connections +func newConnections(c *ProvisioningV0alpha1Client, namespace string) *connections { + return &connections{ + gentype.NewClientWithListAndApply[*provisioningv0alpha1.Connection, *provisioningv0alpha1.ConnectionList, *applyconfigurationprovisioningv0alpha1.ConnectionApplyConfiguration]( + "connections", + c.RESTClient(), + scheme.ParameterCodec, + namespace, + func() *provisioningv0alpha1.Connection { return &provisioningv0alpha1.Connection{} }, + func() *provisioningv0alpha1.ConnectionList { return &provisioningv0alpha1.ConnectionList{} }, + ), + } +} diff --git a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_connection.go b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_connection.go new file mode 100644 index 00000000000..2059d044172 --- /dev/null +++ b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_connection.go @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/generated/applyconfiguration/provisioning/v0alpha1" + typedprovisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1" + gentype "k8s.io/client-go/gentype" +) + +// fakeConnections implements ConnectionInterface +type fakeConnections struct { + *gentype.FakeClientWithListAndApply[*v0alpha1.Connection, *v0alpha1.ConnectionList, *provisioningv0alpha1.ConnectionApplyConfiguration] + Fake *FakeProvisioningV0alpha1 +} + +func newFakeConnections(fake *FakeProvisioningV0alpha1, namespace string) typedprovisioningv0alpha1.ConnectionInterface { + return &fakeConnections{ + gentype.NewFakeClientWithListAndApply[*v0alpha1.Connection, *v0alpha1.ConnectionList, *provisioningv0alpha1.ConnectionApplyConfiguration]( + fake.Fake, + namespace, + v0alpha1.SchemeGroupVersion.WithResource("connections"), + v0alpha1.SchemeGroupVersion.WithKind("Connection"), + func() *v0alpha1.Connection { return &v0alpha1.Connection{} }, + func() *v0alpha1.ConnectionList { return &v0alpha1.ConnectionList{} }, + func(dst, src *v0alpha1.ConnectionList) { dst.ListMeta = src.ListMeta }, + func(list *v0alpha1.ConnectionList) []*v0alpha1.Connection { return gentype.ToPointerSlice(list.Items) }, + func(list *v0alpha1.ConnectionList, items []*v0alpha1.Connection) { + list.Items = gentype.FromPointerSlice(items) + }, + ), + fake, + } +} diff --git a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_provisioning_client.go b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_provisioning_client.go index d6fe94156be..2f1422cadc1 100644 --- a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_provisioning_client.go +++ b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/fake/fake_provisioning_client.go @@ -14,6 +14,10 @@ type FakeProvisioningV0alpha1 struct { *testing.Fake } +func (c *FakeProvisioningV0alpha1) Connections(namespace string) v0alpha1.ConnectionInterface { + return newFakeConnections(c, namespace) +} + func (c *FakeProvisioningV0alpha1) HistoricJobs(namespace string) v0alpha1.HistoricJobInterface { return newFakeHistoricJobs(c, namespace) } diff --git a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/generated_expansion.go b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/generated_expansion.go index 21b7a18b414..5220accc813 100644 --- a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/generated_expansion.go +++ b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/generated_expansion.go @@ -4,6 +4,8 @@ package v0alpha1 +type ConnectionExpansion interface{} + type HistoricJobExpansion interface{} type JobExpansion interface{} diff --git a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/provisioning_client.go b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/provisioning_client.go index 401bc533cfe..03a1e2e0ceb 100644 --- a/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/provisioning_client.go +++ b/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1/provisioning_client.go @@ -14,6 +14,7 @@ import ( type ProvisioningV0alpha1Interface interface { RESTClient() rest.Interface + ConnectionsGetter HistoricJobsGetter JobsGetter RepositoriesGetter @@ -24,6 +25,10 @@ type ProvisioningV0alpha1Client struct { restClient rest.Interface } +func (c *ProvisioningV0alpha1Client) Connections(namespace string) ConnectionInterface { + return newConnections(c, namespace) +} + func (c *ProvisioningV0alpha1Client) HistoricJobs(namespace string) HistoricJobInterface { return newHistoricJobs(c, namespace) } diff --git a/apps/provisioning/pkg/generated/informers/externalversions/generic.go b/apps/provisioning/pkg/generated/informers/externalversions/generic.go index 4a62aab044a..8429b75d959 100644 --- a/apps/provisioning/pkg/generated/informers/externalversions/generic.go +++ b/apps/provisioning/pkg/generated/informers/externalversions/generic.go @@ -39,6 +39,8 @@ func (f *genericInformer) Lister() cache.GenericLister { func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { // Group=provisioning.grafana.app, Version=v0alpha1 + case v0alpha1.SchemeGroupVersion.WithResource("connections"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Provisioning().V0alpha1().Connections().Informer()}, nil case v0alpha1.SchemeGroupVersion.WithResource("historicjobs"): return &genericInformer{resource: resource.GroupResource(), informer: f.Provisioning().V0alpha1().HistoricJobs().Informer()}, nil case v0alpha1.SchemeGroupVersion.WithResource("jobs"): diff --git a/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/connection.go b/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/connection.go new file mode 100644 index 00000000000..d8fa071219f --- /dev/null +++ b/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/connection.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by informer-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + context "context" + time "time" + + apisprovisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + versioned "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned" + internalinterfaces "github.com/grafana/grafana/apps/provisioning/pkg/generated/informers/externalversions/internalinterfaces" + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// ConnectionInformer provides access to a shared informer and lister for +// Connections. +type ConnectionInformer interface { + Informer() cache.SharedIndexInformer + Lister() provisioningv0alpha1.ConnectionLister +} + +type connectionInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewConnectionInformer constructs a new informer for Connection type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewConnectionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredConnectionInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredConnectionInformer constructs a new informer for Connection type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredConnectionInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ProvisioningV0alpha1().Connections(namespace).List(context.Background(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ProvisioningV0alpha1().Connections(namespace).Watch(context.Background(), options) + }, + ListWithContextFunc: func(ctx context.Context, options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ProvisioningV0alpha1().Connections(namespace).List(ctx, options) + }, + WatchFuncWithContext: func(ctx context.Context, options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.ProvisioningV0alpha1().Connections(namespace).Watch(ctx, options) + }, + }, + &apisprovisioningv0alpha1.Connection{}, + resyncPeriod, + indexers, + ) +} + +func (f *connectionInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredConnectionInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *connectionInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&apisprovisioningv0alpha1.Connection{}, f.defaultInformer) +} + +func (f *connectionInformer) Lister() provisioningv0alpha1.ConnectionLister { + return provisioningv0alpha1.NewConnectionLister(f.Informer().GetIndexer()) +} diff --git a/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/interface.go b/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/interface.go index cbe2fcefaf3..1a1908ab5f3 100644 --- a/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/interface.go +++ b/apps/provisioning/pkg/generated/informers/externalversions/provisioning/v0alpha1/interface.go @@ -10,6 +10,8 @@ import ( // Interface provides access to all the informers in this group version. type Interface interface { + // Connections returns a ConnectionInformer. + Connections() ConnectionInformer // HistoricJobs returns a HistoricJobInformer. HistoricJobs() HistoricJobInformer // Jobs returns a JobInformer. @@ -29,6 +31,11 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } +// Connections returns a ConnectionInformer. +func (v *version) Connections() ConnectionInformer { + return &connectionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // HistoricJobs returns a HistoricJobInformer. func (v *version) HistoricJobs() HistoricJobInformer { return &historicJobInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/connection.go b/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/connection.go new file mode 100644 index 00000000000..a12902c2bea --- /dev/null +++ b/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/connection.go @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Code generated by lister-gen. DO NOT EDIT. + +package v0alpha1 + +import ( + provisioningv0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + labels "k8s.io/apimachinery/pkg/labels" + listers "k8s.io/client-go/listers" + cache "k8s.io/client-go/tools/cache" +) + +// ConnectionLister helps list Connections. +// All objects returned here must be treated as read-only. +type ConnectionLister interface { + // List lists all Connections in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*provisioningv0alpha1.Connection, err error) + // Connections returns an object that can list and get Connections. + Connections(namespace string) ConnectionNamespaceLister + ConnectionListerExpansion +} + +// connectionLister implements the ConnectionLister interface. +type connectionLister struct { + listers.ResourceIndexer[*provisioningv0alpha1.Connection] +} + +// NewConnectionLister returns a new ConnectionLister. +func NewConnectionLister(indexer cache.Indexer) ConnectionLister { + return &connectionLister{listers.New[*provisioningv0alpha1.Connection](indexer, provisioningv0alpha1.Resource("connection"))} +} + +// Connections returns an object that can list and get Connections. +func (s *connectionLister) Connections(namespace string) ConnectionNamespaceLister { + return connectionNamespaceLister{listers.NewNamespaced[*provisioningv0alpha1.Connection](s.ResourceIndexer, namespace)} +} + +// ConnectionNamespaceLister helps list and get Connections. +// All objects returned here must be treated as read-only. +type ConnectionNamespaceLister interface { + // List lists all Connections in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*provisioningv0alpha1.Connection, err error) + // Get retrieves the Connection from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*provisioningv0alpha1.Connection, error) + ConnectionNamespaceListerExpansion +} + +// connectionNamespaceLister implements the ConnectionNamespaceLister +// interface. +type connectionNamespaceLister struct { + listers.ResourceIndexer[*provisioningv0alpha1.Connection] +} diff --git a/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/expansion_generated.go b/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/expansion_generated.go index 7f0649542b3..4d840b6e2db 100644 --- a/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/expansion_generated.go +++ b/apps/provisioning/pkg/generated/listers/provisioning/v0alpha1/expansion_generated.go @@ -4,6 +4,14 @@ package v0alpha1 +// ConnectionListerExpansion allows custom methods to be added to +// ConnectionLister. +type ConnectionListerExpansion interface{} + +// ConnectionNamespaceListerExpansion allows custom methods to be added to +// ConnectionNamespaceLister. +type ConnectionNamespaceListerExpansion interface{} + // HistoricJobListerExpansion allows custom methods to be added to // HistoricJobLister. type HistoricJobListerExpansion interface{} diff --git a/apps/scope/pkg/apis/scope/v0alpha1/types.go b/apps/scope/pkg/apis/scope/v0alpha1/types.go index 0c323d8d14b..20414f3caf6 100644 --- a/apps/scope/pkg/apis/scope/v0alpha1/types.go +++ b/apps/scope/pkg/apis/scope/v0alpha1/types.go @@ -211,6 +211,12 @@ type ScopeNavigationSpec struct { Scope string `json:"scope"` // Used to navigate to a sub-scope of the main scope. URL will not be used if this is set. SubScope string `json:"subScope,omitempty"` + // Preload the subscope children, as soon as the ScopeNavigation is loaded. + PreLoadSubScopeChildren bool `json:"preLoadSubScopeChildren,omitempty"` + // Expands to display the subscope children when the ScopeNavigation is loaded. + ExpandOnLoad bool `json:"expandOnLoad,omitempty"` + // Makes the subscope not selectable, only serving as a way to build the tree. + DisableSubScopeSelection bool `json:"disableSubScopeSelection,omitempty"` } // Type of the item. diff --git a/apps/scope/pkg/apis/scope/v0alpha1/zz_generated.openapi.go b/apps/scope/pkg/apis/scope/v0alpha1/zz_generated.openapi.go index 50015307139..1cb72adf4b1 100644 --- a/apps/scope/pkg/apis/scope/v0alpha1/zz_generated.openapi.go +++ b/apps/scope/pkg/apis/scope/v0alpha1/zz_generated.openapi.go @@ -642,6 +642,27 @@ func schema_pkg_apis_scope_v0alpha1_ScopeNavigationSpec(ref common.ReferenceCall Format: "", }, }, + "preLoadSubScopeChildren": { + SchemaProps: spec.SchemaProps{ + Description: "Preload the subscope children, as soon as the ScopeNavigation is loaded.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "expandOnLoad": { + SchemaProps: spec.SchemaProps{ + Description: "Expands to display the subscope children when the ScopeNavigation is loaded.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "disableSubScopeSelection": { + SchemaProps: spec.SchemaProps{ + Description: "Makes the subscope not selectable, only serving as a way to build the tree.", + Type: []string{"boolean"}, + Format: "", + }, + }, }, Required: []string{"url", "scope"}, }, diff --git a/conf/defaults.ini b/conf/defaults.ini index c2d7e4da3b6..de83393e43d 100644 --- a/conf/defaults.ini +++ b/conf/defaults.ini @@ -1327,6 +1327,10 @@ alertmanager_max_silences_count = # Maximum silence size in bytes. Default: 0 (no limit). alertmanager_max_silence_size_bytes = +# Maximum size of the expanded template output in bytes. Default: 10485760 (0 - no limit). +# The result of template expansion will be truncated to the limit. +alertmanager_max_template_output_bytes = + # Redis server address or addresses. It can be a single Redis address if using Redis standalone, # or a list of comma-separated addresses if using Redis Cluster/Sentinel. ha_redis_address = diff --git a/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json b/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json index 9cb204da48a..b3c47c9aa7a 100644 --- a/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json +++ b/devenv/dev-dashboards/panel-gauge/gauge_tests_new.json @@ -75,10 +75,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -152,10 +152,10 @@ "effects": { "barGlow": false, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -229,10 +229,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -306,10 +306,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -383,10 +383,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -460,10 +460,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -537,10 +537,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": false, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -627,10 +627,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -704,10 +704,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -781,10 +781,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -858,10 +858,10 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": false, "rounded": true, "spotlight": true }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -952,10 +952,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1029,10 +1029,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1106,10 +1106,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1183,10 +1183,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1260,10 +1260,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": false, "rounded": false, "spotlight": false }, - "gradient": "none", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1354,10 +1354,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1435,10 +1435,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1516,10 +1516,10 @@ "effects": { "barGlow": false, "centerGlow": false, + "gradient": true, "rounded": false, "spotlight": false }, - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1565,7 +1565,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1606,11 +1605,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "auto", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1631,7 +1630,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 98, "min": 5, "noise": 22, @@ -1649,7 +1647,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1690,11 +1687,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1715,7 +1712,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 98, "min": 5, "noise": 22, @@ -1746,7 +1742,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1788,11 +1783,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1813,7 +1808,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 8, "min": 1, "noise": 2, @@ -1831,7 +1825,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1873,12 +1866,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, - "sparkline": false, "spotlight": true }, "glow": "both", - "gradient": "scheme", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1899,7 +1891,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 12, "min": 1, "noise": 2, @@ -1917,7 +1908,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -1958,11 +1948,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -1983,7 +1973,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 100, "min": 10, "noise": 22, @@ -2001,7 +1990,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "description": "", "fieldConfig": { "defaults": { "color": { @@ -2042,11 +2030,11 @@ "effects": { "barGlow": true, "centerGlow": true, + "gradient": true, "rounded": true, "spotlight": true }, "glow": "both", - "gradient": "hue", "orientation": "auto", "reduceOptions": { "calcs": ["lastNotNull"], @@ -2067,7 +2055,6 @@ "datasource": { "type": "grafana-testdata-datasource" }, - "hide": false, "max": 100, "min": 10, "noise": 22, @@ -2080,6 +2067,147 @@ ], "title": "Backend", "type": "radialbar" + }, + { + "collapsed": false, + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 66 + }, + "id": 35, + "panels": [], + "title": "Empty data", + "type": "row" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 6, + "x": 0, + "y": 67 + }, + "id": 36, + "options": { + "barWidthFactor": 0.5, + "effects": { + "barGlow": false, + "centerGlow": false, + "gradient": true, + "rounded": false, + "spotlight": false + }, + "orientation": "auto", + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + }, + "segmentCount": 1, + "segmentSpacing": 0.3, + "shape": "gauge", + "showThresholdLabels": false, + "showThresholdMarkers": true, + "sparkline": true + }, + "pluginVersion": "13.0.0-pre", + "targets": [ + { + "refId": "A", + "scenarioId": "random_walk", + "seriesCount": 0 + } + ], + "title": "Numeric, no series", + "type": "gauge" + }, + { + "datasource": { + "type": "grafana-testdata-datasource" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": 0 + }, + { + "color": "red", + "value": 80 + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 6, + "x": 6, + "y": 67 + }, + "id": 37, + "options": { + "barWidthFactor": 0.5, + "effects": { + "barGlow": false, + "centerGlow": false, + "gradient": true, + "rounded": false, + "spotlight": false + }, + "orientation": "auto", + "reduceOptions": { + "calcs": ["lastNotNull"], + "fields": "", + "values": false + }, + "segmentCount": 1, + "segmentSpacing": 0.3, + "shape": "gauge", + "showThresholdLabels": false, + "showThresholdMarkers": true, + "sparkline": true + }, + "pluginVersion": "13.0.0-pre", + "targets": [ + { + "refId": "A", + "scenarioId": "logs" + } + ], + "title": "Non-numeric", + "type": "gauge" } ], "preload": false, @@ -2096,5 +2224,5 @@ "timezone": "browser", "title": "Panel tests - Gauge (new)", "uid": "panel-tests-gauge-new", - "version": 6 + "version": 9 } diff --git a/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json b/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json index 61bec02a59b..b071ddff802 100644 --- a/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json +++ b/devenv/dev-dashboards/panel-gauge/gauge_tests_old_to_new.json @@ -947,7 +947,6 @@ }, "orientation": "auto", "shape": "gauge", - "gradient": "none", "barWidthFactor": 0.5, "segmentCount": 70, "segmentSpacing": 0.3, @@ -958,7 +957,8 @@ "barGlow": false, "centerGlow": false, "rounded": false, - "spotlight": false + "spotlight": false, + "gradient": false } } }, diff --git a/devenv/scopes/scopes-config.yaml b/devenv/scopes/scopes-config.yaml index 54842e5818e..ef800415547 100644 --- a/devenv/scopes/scopes-config.yaml +++ b/devenv/scopes/scopes-config.yaml @@ -83,6 +83,12 @@ tree: nodeType: leaf linkId: test-case-2 linkType: scope + test-case-redirect: + title: Test case with redirect + nodeType: leaf + linkId: shoe-org + linkType: scope + redirectPath: /d/dcb9f5e9-8066-4397-889e-864b99555dbb #Reliability dashboard clusters: title: Clusters nodeType: container @@ -119,6 +125,7 @@ navigationTree: url: /d/_5rDmaQiz scope: shoe-org subScope: shoes + preLoadSubScopeChildren: true children: - name: shoes-overview title: Overview @@ -135,6 +142,7 @@ navigationTree: url: /d/edediimbjhdz4b scope: shoes subScope: frontend + preLoadSubScopeChildren: true children: - name: frontend-api title: API Metrics @@ -204,6 +212,7 @@ navigationTree: url: /d/UTv--wqMk scope: shoe-org subScope: apparel + disableSubScopeSelection: true children: - name: apparel-product-overview title: Product Overview diff --git a/devenv/scopes/scopes.go b/devenv/scopes/scopes.go index 1f8a698ccda..e3f4de80d21 100644 --- a/devenv/scopes/scopes.go +++ b/devenv/scopes/scopes.go @@ -67,30 +67,36 @@ type ScopeFilterConfig struct { type TreeNode struct { Title string `yaml:"title"` SubTitle string `yaml:"subTitle,omitempty"` + Description string `yaml:"description,omitempty"` NodeType string `yaml:"nodeType"` LinkID string `yaml:"linkId,omitempty"` LinkType string `yaml:"linkType,omitempty"` DisableMultiSelect bool `yaml:"disableMultiSelect,omitempty"` + RedirectPath string `yaml:"redirectPath,omitempty"` Children map[string]TreeNode `yaml:"children,omitempty"` } type NavigationConfig struct { - URL string `yaml:"url"` // URL path (e.g., /d/abc123 or /explore) - Scope string `yaml:"scope"` // Required scope - SubScope string `yaml:"subScope"` // Optional subScope for hierarchical navigation - Title string `yaml:"title"` // Display title - Groups []string `yaml:"groups"` // Optional groups for categorization + URL string `yaml:"url"` // URL path (e.g., /d/abc123 or /explore) + Scope string `yaml:"scope"` // Required scope + SubScope string `yaml:"subScope"` // Optional subScope for hierarchical navigation + Title string `yaml:"title"` // Display title + Groups []string `yaml:"groups"` // Optional groups for categorization + DisableSubScopeSelection bool `yaml:"disableSubScopeSelection"` // Makes the subscope not selectable + PreLoadSubScopeChildren bool `yaml:"preLoadSubScopeChildren"` // Preload children of subScope without updating UI } // NavigationTreeNode represents a node in the navigation tree structure type NavigationTreeNode struct { - Name string `yaml:"name"` - Title string `yaml:"title"` - URL string `yaml:"url"` - Scope string `yaml:"scope"` - SubScope string `yaml:"subScope,omitempty"` - Groups []string `yaml:"groups,omitempty"` - Children []NavigationTreeNode `yaml:"children,omitempty"` + Name string `yaml:"name"` + Title string `yaml:"title"` + URL string `yaml:"url"` + Scope string `yaml:"scope"` + SubScope string `yaml:"subScope,omitempty"` + Groups []string `yaml:"groups,omitempty"` + DisableSubScopeSelection bool `yaml:"disableSubScopeSelection,omitempty"` + PreLoadSubScopeChildren bool `yaml:"preLoadSubScopeChildren,omitempty"` // Preload children of subScope without updating UI + Children []NavigationTreeNode `yaml:"children,omitempty"` } // Helper function to convert ScopeFilterConfig to v0alpha1.ScopeFilter @@ -259,6 +265,7 @@ func (c *Client) createScopeNode(name string, node TreeNode, parentName string) spec := v0alpha1.ScopeNodeSpec{ Title: node.Title, SubTitle: node.SubTitle, + Description: node.Description, NodeType: nodeType, DisableMultiSelect: node.DisableMultiSelect, } @@ -272,6 +279,10 @@ func (c *Client) createScopeNode(name string, node TreeNode, parentName string) spec.LinkType = linkType } + if node.RedirectPath != "" { + spec.RedirectPath = node.RedirectPath + } + resource := v0alpha1.ScopeNode{ TypeMeta: metav1.TypeMeta{ APIVersion: apiVersion, @@ -306,8 +317,10 @@ func (c *Client) createScopeNavigation(name string, nav NavigationConfig) error prefixedScope := prefix + "-" + nav.Scope spec := v0alpha1.ScopeNavigationSpec{ - URL: nav.URL, - Scope: prefixedScope, + URL: nav.URL, + Scope: prefixedScope, + DisableSubScopeSelection: nav.DisableSubScopeSelection, + PreLoadSubScopeChildren: nav.PreLoadSubScopeChildren, } if nav.SubScope != "" { @@ -343,14 +356,14 @@ func (c *Client) createScopeNavigation(name string, nav NavigationConfig) error return err } + // Get the created resource to retrieve its resourceVersion for status update + createdNav, err := c.getScopeNavigation(prefixedName) + if err != nil { + return fmt.Errorf("failed to get created navigation: %w", err) + } + // Update status in a second request (status is a subresource) if nav.Title != "" || len(nav.Groups) > 0 { - // Get the created resource to retrieve its resourceVersion and existing spec - createdNav, err := c.getScopeNavigation(prefixedName) - if err != nil { - return fmt.Errorf("failed to get created navigation: %w", err) - } - statusResource := v0alpha1.ScopeNavigation{ TypeMeta: metav1.TypeMeta{ APIVersion: apiVersion, @@ -397,9 +410,11 @@ func treeToNavigations(node NavigationTreeNode, parentPath []string, dashboardCo // Create navigation for this node nav := NavigationConfig{ - URL: url, - Scope: node.Scope, - Title: node.Title, + URL: url, + Scope: node.Scope, + Title: node.Title, + DisableSubScopeSelection: node.DisableSubScopeSelection, + PreLoadSubScopeChildren: node.PreLoadSubScopeChildren, } if node.SubScope != "" { nav.SubScope = node.SubScope diff --git a/docs/Makefile b/docs/Makefile index 7bdbe026293..8202b11f826 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -7,8 +7,8 @@ MAKEFLAGS += --no-builtin-rule include docs.mk -.PHONY: sources/panels-visualizations/query-transform-data/transform-data/index.md -sources/panels-visualizations/query-transform-data/transform-data/index.md: ## Generate the Transform Data page source. +.PHONY: sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md +sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md: ## Generate the Transform Data page source. cd $(CURDIR)/.. && \ npx tsx ./scripts/docs/generate-transformations.ts && \ npx prettier -w $(CURDIR)/$@ diff --git a/docs/sources/administration/plugin-management/plugin-install.md b/docs/sources/administration/plugin-management/plugin-install.md index 18be4ea58fa..dfec5002944 100644 --- a/docs/sources/administration/plugin-management/plugin-install.md +++ b/docs/sources/administration/plugin-management/plugin-install.md @@ -21,11 +21,28 @@ weight: 120 # Install a plugin -Besides the UI, you can use alternative methods to install a plugin depending on your environment or set-up. +{{< admonition type="note" >}} + +Installing plugins from the Grafana website into a Grafana Cloud instance will be removed in February 2026. + +If you're a Grafana Cloud user, follow [Install a plugin through the Grafana UI](#install-a-plugin-through-the-grafana-uiinstall-a-plugin-through-the-grafana-ui) instead. + +{{< /admonition >}} + +## Install a plugin through the Grafana UI + +The most common way to install a plugin is through the Grafana UI. + +1. In Grafana, click **Administration > Plugins and data > Plugins** in the side navigation menu to view all plugins. +1. Browse and find a plugin. +1. Click the plugin's logo. +1. Click **Install**. + +You can use use the following alternative methods to install a plugin depending on your environment or setup. ## Install a plugin using Grafana CLI -The Grafana CLI allows you to install, upgrade, and manage your Grafana plugins using a command line tool. For more information about Grafana CLI plugin commands, refer to [Plugin commands](/docs/grafana//cli/#plugins-commands). +The Grafana CLI allows you to install, upgrade, and manage your Grafana plugins using a command line tool. For more information about Grafana CLI plugin commands, refer to [Plugin commands](https://grafana.com/docs/grafana//administration/cli/#plugins-commands). ## Install a plugin from a ZIP file diff --git a/docs/sources/administration/roles-and-permissions/access-control/custom-role-actions-scopes/index.md b/docs/sources/administration/roles-and-permissions/access-control/custom-role-actions-scopes/index.md index 641d9bb4180..5fb3705232e 100644 --- a/docs/sources/administration/roles-and-permissions/access-control/custom-role-actions-scopes/index.md +++ b/docs/sources/administration/roles-and-permissions/access-control/custom-role-actions-scopes/index.md @@ -238,6 +238,7 @@ For more information on Cloud Access Policies and how to use them, see [Access p | `alert.notifications.templates:read` | None | Read templates. | | `alert.notifications.templates:write` | None | Create new or update existing templates. | | `alert.notifications.templates:delete` | None | Delete existing templates. | +| `alert.notifications.templates.test:write` | None | Test templates with custom payloads (preview and payload editor functionality). | | `alert.notifications.routes:read` | None | Read notification policies. | | `alert.notifications.routes:write` | None | Create new, update or delete notification policies | diff --git a/docs/sources/administration/roles-and-permissions/access-control/rbac-fixed-basic-role-definitions/index.md b/docs/sources/administration/roles-and-permissions/access-control/rbac-fixed-basic-role-definitions/index.md index 43b6e9c74a1..82ebfa0c49a 100644 --- a/docs/sources/administration/roles-and-permissions/access-control/rbac-fixed-basic-role-definitions/index.md +++ b/docs/sources/administration/roles-and-permissions/access-control/rbac-fixed-basic-role-definitions/index.md @@ -44,7 +44,7 @@ refs: destination: /docs/grafana-cloud/alerting-and-irm/oncall/user-and-team-management/#available-grafana-oncall-rbac-roles--granted-actions --- -# RBAC role definitions +# Grafana RBAC role definitions {{< admonition type="note" >}} Available in [Grafana Enterprise](/docs/grafana//introduction/grafana-enterprise/) and [Grafana Cloud](/docs/grafana-cloud). @@ -59,7 +59,7 @@ The following tables list permissions associated with basic and fixed roles. Thi | Grafana Admin | `basic_grafana_admin` | | `fixed:authentication.config:writer`
`fixed:general.auth.config:writer`
`fixed:ldap:writer`
`fixed:licensing:writer`
`fixed:migrationassistant:migrator`
`fixed:org.users:writer`
`fixed:organization:maintainer`
`fixed:plugins:maintainer`
`fixed:provisioning:writer`
`fixed:roles:writer`
`fixed:settings:reader`
`fixed:settings:writer`
`fixed:stats:reader`
`fixed:support.bundles:writer`
`fixed:usagestats:reader`
`fixed:users:writer` | Default [Grafana server administrator](/docs/grafana//administration/roles-and-permissions/#grafana-server-administrators) assignments. | | Admin | `basic_admin` | All roles assigned to Editor and `fixed:reports:writer`
`fixed:datasources:writer`
`fixed:organization:writer`
`fixed:datasources.permissions:writer`
`fixed:teams:writer`
`fixed:dashboards:writer`
`fixed:dashboards.permissions:writer`
`fixed:dashboards.public:writer`
`fixed:folders:writer`
`fixed:folders.permissions:writer`
`fixed:alerting:writer`
`fixed:alerting.provisioning.secrets:reader`
`fixed:alerting.provisioning:writer`
`fixed:datasources.caching:writer`
`fixed:plugins:writer`
`fixed:library.panels:writer` | Default [Grafana organization administrator](ref:rbac-basic-roles) assignments. | -| Editor | `basic_editor` | All roles assigned to Viewer and `fixed:datasources:explorer`
`fixed:dashboards:creator`
`fixed:folders:creator`
`fixed:annotations:writer`
`fixed:alerting:writer`
`fixed:library.panels:creator`
`fixed:library.panels:general.writer`
`fixed:alerting.provisioning.status:writer` | Default [Editor](ref:rbac-basic-roles) assignments. | +| Editor | `basic_editor` | All roles assigned to Viewer and `fixed:datasources:explorer`
`fixed:dashboards:creator`
`fixed:folders:creator`
`fixed:annotations:writer`
`fixed:alerting:writer`
`fixed:library.panels:creator`
`fixed:library.panels:general.writer`
`fixed:alerting.provisioning.provenance:writer` | Default [Editor](ref:rbac-basic-roles) assignments. | | Viewer | `basic_viewer` | `fixed:datasources.id:reader`
`fixed:organization:reader`
`fixed:annotations:reader`
`fixed:annotations.dashboard:writer`
`fixed:alerting:reader`
`fixed:plugins.app:reader`
`fixed:dashboards.insights:reader`
`fixed:datasources.insights:reader`
`fixed:library.panels:general.reader`
`fixed:folders.general:reader`
`fixed:datasources.builtin:reader` | Default [Viewer](ref:rbac-basic-roles) assignments. | | No Basic Role | n/a | | Default [No Basic Role](ref:rbac-basic-roles) | @@ -74,86 +74,86 @@ These UUIDs won't be available if your instance was created before Grafana v10.2 To learn how to use the roles API to determine the role UUIDs, refer to [Manage RBAC roles](ref:rbac-manage-rbac-roles). {{< /admonition >}} -| Fixed role | UUID | Permissions | Description | -| -------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `fixed:alerting:reader` | `fixed_O2oP1_uBFozI2i93klAkcvEWR30` | All permissions from `fixed:alerting.rules:reader`
`fixed:alerting.instances:reader`
`fixed:alerting.notifications:reader` | Read-only permissions for all Grafana, Mimir, Loki and Alertmanager alert rules\*, alerts, contact points, and notification policies.[\*](#alerting-roles) | -| `fixed:alerting:writer` | `fixed_-PAZgSJsDlRD8NUg-PFSeH_BkJY` | All permissions from `fixed:alerting.rules:writer`
`fixed:alerting.instances:writer`
`fixed:alerting.notifications:writer` | Create, update, and delete Grafana, Mimir, Loki and Alertmanager alert rules\*, silences, contact points, templates, mute timings, and notification policies.[\*](#alerting-roles) | -| `fixed:alerting.instances:reader` | `fixed_ut5fVS-Ulh_ejFoskFhJT_rYg0Y` | `alert.instances:read` for organization scope
`alert.instances.external:read` for scope `datasources:*` | Read all alerts and silences in the organization produced by Grafana Alerts and Mimir and Loki alerts and silences.[\*](#alerting-roles) | -| `fixed:alerting.instances:writer` | `fixed_pKOBJE346uyqMLdgWbk1NsQfEl0` | All permissions from `fixed:alerting.instances:reader` and
`alert.instances:create`
`alert.instances:write` for organization scope
`alert.instances.external:write` for scope `datasources:*` | Create, update and expire all silences in the organization produced by Grafana, Mimir, and Loki.[\*](#alerting-roles) | -| `fixed:alerting.notifications:reader` | `fixed_hmBn0lX5h1RZXB9Vaot420EEdA0` | `alert.notifications:read` for organization scope
`alert.notifications.external:read` for scope `datasources:*` | Read all Grafana and Alertmanager contact points, templates, and notification policies.[\*](#alerting-roles) | -| `fixed:alerting.notifications:writer` | `fixed_XplK6HPNxf9AP5IGTdB5Iun4tJc` | All permissions from `fixed:alerting.notifications:reader` and
`alert.notifications:write`for organization scope
`alert.notifications.external:read` for scope `datasources:*` | Create, update, and delete contact points, templates, mute timings and notification policies for Grafana and external Alertmanager.[\*](#alerting-roles) | -| `fixed:alerting.provisioning:writer` | `fixed_y7pFjdEkxpx5ETdcxPvp0AgRuUo` | `alert.provisioning:read` and `alert.provisioning:write` | Create, update and delete Grafana alert rules, notification policies, contact points, templates, etc via provisioning API. [\*](#alerting-roles) | -| `fixed:alerting.provisioning.secrets:reader` | `fixed_9fmzXXZZG-Od0Amy2ofEG8Uk--c` | `alert.provisioning:read` and `alert.provisioning.secrets:read` | Read-only permissions for Provisioning API and let export resources with decrypted secrets [\*](#alerting-roles) | -| `fixed:alerting.provisioning.status:writer` | `fixed_eAxlzfkTuobvKEgXHveFMBZrOj8` | `alert.provisioning.provenance:write` | Set provenance status to alert rules, notification policies, contact points, etc. Should be used together with regular writer roles. [\*](#alerting-roles) | -| `fixed:alerting.rules:reader` | `fixed_fRGKL_vAqUsmUWq5EYKnOha9DcA` | `alert.rule:read`, `alert.silences:read` for scope `folders:*`
`alert.rules.external:read` for scope `datasources:*`
`alert.notifications.time-intervals:read`
`alert.notifications.receivers:list` | Read all\* Grafana, Mimir, and Loki alert rules.[\*](#alerting-roles) and read rule-specific silences | -| `fixed:alerting.rules:writer` | `fixed_YJJGwAalUwDZPrXSyFH8GfYBXAc` | All permissions from `fixed:alerting.rules:reader` and
`alert.rule:create`
`alert.rule:write`
`alert.rule:delete`
`alert.silences:create`
`alert.silences:write` for scope `folders:*`
`alert.rules.external:write` for scope `datasources:*` | Create, update, and delete all\* Grafana, Mimir, and Loki alert rules.[\*](#alerting-roles) and manage rule-specific silences | -| `fixed:annotations:reader` | `fixed_hpZnoizrfAJsrceNcNQqWYV-xNU` | `annotations:read` for scopes `annotations:type:*` | Read all annotations and annotation tags. | -| `fixed:annotations:writer` | `fixed_ZVW-Aa9Tzle6J4s2aUFcq1StKWE` | All permissions from `fixed:annotations:reader`
`annotations:write`
`annotations.create`
`annotations:delete` for scope `annotations:type:*` | Read, create, update and delete all annotations and annotation tags. | -| `fixed:annotations.dashboard:writer` | `fixed_8A775xenXeKaJk4Cr7bchP9yXOA` | `annotations:write`
`annotations.create`
`annotations:delete` for scope `annotations:type:dashboard` | Create, update and delete dashboard annotations and annotation tags. | -| `fixed:authentication.config:writer` | `fixed_0rYhZ2Qnzs8AdB1nX7gexk3fHDw` | `settings:read` for scope `settings:auth.saml:*`
`settings:write` for scope `settings:auth.saml:*` | Read and update authentication and SAML settings. | -| `fixed:general.auth.config:writer` | `fixed_QFxIT_FGtBqbIVJIwx1bLgI5z6c` | `settings:read` for scope `settings:auth:oauth_allow_insecure_email_lookup`
`settings:write` for scope `settings:auth:oauth_allow_insecure_email_lookup` | Read and update the Grafana instance's general authentication configuration settings. | -| `fixed:dashboards:creator` | `fixed_ZorKUcEPCM01A1fPakEzGBUyU64` | `dashboards:create`
`folders:read` | Create dashboards. | -| `fixed:dashboards:reader` | `fixed_Sgr67JTOhjQGFlzYRahOe45TdWM` | `dashboards:read` | Read all dashboards. | -| `fixed:dashboards:writer` | `fixed_OK2YOQGIoI1G031hVzJB6rAJQAs` | All permissions from `fixed:dashboards:reader` and
`dashboards:write`
`dashboards:delete`
`dashboards:create`
`dashboards.permissions:read`
`dashboards.permissions:write` | Read, create, update, and delete all dashboards. | -| `fixed:dashboards.insights:reader` | `fixed_JlBJ2_gizP8zhgaeGE2rjyZe2Rs` | `dashboards.insights:read` | Read dashboard insights data and see presence indicators. | -| `fixed:dashboards.permissions:reader` | `fixed_f17oxuXW_58LL8mYJsm4T_mCeIw` | `dashboards.permissions:read` | Read all dashboard permissions. | -| `fixed:dashboards.permissions:writer` | `fixed_CcznxhWX_Yqn8uWMXMQ-b5iFW9k` | All permissions from `fixed:dashboards.permissions:reader` and
`dashboards.permissions:write` | Read and update all dashboard permissions. | -| `fixed:dashboards.public:writer` | `fixed_f_GHHRBciaqESXfGz2oCcooqHxs` | `dashboards.public:write` | Create, update, delete or pause a shared dashboard. | -| `fixed:datasources:creator` | `fixed_XX8jHREgUt-wo1A-rPXIiFlX6Zw` | `datasources:create` | Create data sources. | -| `fixed:datasources:explorer` | `fixed_qDzW9mzx9yM91T5Bi8dHUM2muTw` | `datasources:explore` | Enable the Explore feature. Data source permissions still apply, you can only query data sources for which you have query permissions. | -| `fixed:datasources:reader` | `fixed_C2x8IxkiBc1KZVjyYH775T9jNMQ` | `datasources:read`
`datasources:query` | Read and query data sources. | -| `fixed:datasources:writer` | `fixed_q8HXq8kjjA5IlHHgBJlKlUyaNik` | All permissions from `fixed:datasources:reader` and
`datasources:create`
`datasources:write`
`datasources:delete` | Read, query, create, delete, or update a data source. | -| `fixed:datasources.builtin:reader` | `fixed_q8HXq8kjjA5IlHHgBJlKlUyaNik` | `datasources:read` and `datasources:query` scoped to `datasources:uid:grafana` | An internal role used to grant Viewers access to the builtin example data source in Grafana. | -| `fixed:datasources.caching:reader` | `fixed_D2ddpGxJYlw0mbsTS1ek9fj0kj4` | `datasources.caching:read` | Read data source query caching settings. | -| `fixed:datasources.caching:writer` | `fixed_JtFjHr7jd7hSqUYcktKvRvIOGRE` | `datasources.caching:read`
`datasources.caching:write` | Enable, disable, or update query caching settings. | -| `fixed:datasources.id:reader` | `fixed_entg--fHmDqWY2-69N0ocawK0Os` | `datasources.id:read` | Read the ID of a data source based on its name. | -| `fixed:datasources.insights:reader` | `fixed_EBZ3NwlfecNPp2p0XcZRC1nfEYk` | `datasources.insights:read` | Read data source insights data. | -| `fixed:datasources.permissions:reader` | `fixed_ErYA-cTN3yn4h4GxaVPcawRhiOY` | `datasources.permissions:read` | Read data source permissions. | -| `fixed:datasources.permissions:writer` | `fixed_aiQh9YDfLOKjQhYasF9_SFUjQiw` | All permissions from `fixed:datasources.permissions:reader` and
`datasources.permissions:write` | Create, read, or delete permissions of a data source. | -| `fixed:folders:creator` | `fixed_gGLRbZGAGB6n9uECqSh_W382RlQ` | `folders:create` | Create folders in the root level. | -| `fixed:folders:reader` | `fixed_yeW-5QPeo-i5PZUIUXMlAA97GnQ` | `folders:read`
`dashboards:read` | Read all folders and dashboards. | -| `fixed:folders:writer` | `fixed_wJXLoTzgE7jVuz90dryYoiogL0o` | All permissions from `fixed:dashboards:writer` and
`folders:read`
`folders:write`
`folders:create`
`folders:delete`
`folders.permissions:read`
`folders.permissions:write` | Read, update, and delete all folders and dashboards. Create folders and subfolders. | -| `fixed:folders.general:reader` | `fixed_rSASbkg8DvpG_gTX5s41d7uxRvI` | `folders:read` scoped to `folders:uid:general` | An internal role used to correctly display access to the folder tree for Viewer role. | -| `fixed:folders.permissions:reader` | `fixed_E06l4cx0JFm47EeLBE4nmv3pnSo` | `folders.permissions:read` | Read all folder permissions. | -| `fixed:folders.permissions:writer` | `fixed_3GAgpQ_hWG8o7-lwNb86_VB37eI` | All permissions from `fixed:folders.permissions:reader` and
`folders.permissions:write` | Read and update all folder permissions. | -| `fixed:ldap:reader` | `fixed_lMcOPwSkxKY-qCK8NMJc5k6izLE` | `ldap.user:read`
`ldap.status:read` | Read the LDAP configuration and LDAP status information. | -| `fixed:ldap:writer` | `fixed_p6AvnU4GCQyIh7-hbwI-bk3GYnU` | All permissions from `fixed:ldap:reader` and
`ldap.user:sync`
`ldap.config:reload` | Read and update the LDAP configuration, and read LDAP status information. | -| `fixed:library.panels:creator` | `fixed_6eX6ItfegCIY5zLmPqTDW8ZV7KY` | `library.panels:create`
`folders:read` | Create library panel at the root level. | -| `fixed:library.panels:general.reader` | `fixed_ct0DghiBWR_2BiQm3EvNPDVmpio` | `library.panels:read` | Read all library panels at the root level. | -| `fixed:library.panels:general.writer` | `fixed_DgprkmqfN_1EhZ2v1_d1fYG8LzI` | All permissions from `fixed:library.panels:general.reader` plus
`library.panels:create`
`library.panels:delete`
`library.panels:write` | Create, read, write or delete all library panels and their permissions at the root level. | -| `fixed:library.panels:reader` | `fixed_tvTr9CnZ6La5vvUO_U_X1LPnhUs` | `library.panels:read` | Read all library panels. | -| `fixed:library.panels:writer` | `fixed_JTljAr21LWLTXCkgfBC4H0lhBC8` | All permissions from `fixed:library.panels:reader` plus
`library.panels:create`
`library.panels:delete`
`library.panels:write` | Create, read, write or delete all library panels and their permissions. | -| `fixed:licensing:reader` | `fixed_OADpuXvNEylO2Kelu3GIuBXEAYE` | `licensing:read`
`licensing.reports:read` | Read licensing information and licensing reports. | -| `fixed:licensing:writer` | `fixed_gzbz3rJpQMdaKHt-E4q0PVaKMoE` | All permissions from `fixed:licensing:reader` and
`licensing:write`
`licensing:delete` | Read licensing information and licensing reports, update and delete the license token. | -| `fixed:migrationassistant:migrator` | `fixed_LLk2p7TRuBztOAksTQb1Klc8YTk` | `migrationassistant:migrate` | Execute on-prem to cloud migrations through the Migration Assistant. | -| `fixed:org.users:reader` | `fixed_oCqNwlVHLOpw7-jAlwp4HzYqwGY` | `org.users:read` | Read users within a single organization. | -| `fixed:org.users:writer` | `fixed_VERj5nayasjgf_Yh0sWqqCkxWlw` | All permissions from `fixed:org.users:reader` and
`org.users:add`
`org.users:remove`
`org.users:write` | Within a single organization, add a user, invite a new user, read information about a user and their role, remove a user from that organization, or change the role of a user. | -| `fixed:organization:maintainer` | `fixed_CMm-uuBaPUBf4r8XG3jIvxo55bg` | All permissions from `fixed:organization:reader` and
`orgs:write`
`orgs:create`
`orgs:delete`
`orgs.quotas:write` | Create, read, write, or delete an organization. Read or write its quotas. This role needs to be assigned globally. | -| `fixed:organization:reader` | `fixed_0SZPJlTHdNEe8zO91zv7Zwiwa2w` | `orgs:read`
`orgs.quotas:read` | Read an organization and its quotas. | -| `fixed:organization:writer` | `fixed_Y4jGqDd8w1yCrPwlik8z5Iu8-3M` | All permissions from `fixed:organization:reader` and
`orgs:write`
`orgs.preferences:read`
`orgs.preferences:write` | Read an organization, its quotas, or its preferences. Update organization properties, or its preferences. | -| `fixed:plugins:maintainer` | `fixed_yEOKidBcWgbm74x-nTa3lW5lOyY` | `plugins:install` | Install and uninstall plugins. Needs to be assigned globally. | -| `fixed:plugins:writer` | `fixed_MRYpGk7kpNNwt2VoVOXFiPnQziE` | `plugins:write` | Enable and disable plugins and edit plugins' settings. | -| `fixed:plugins.app:reader` | `fixed_AcZRiNYx7NueYkUqzw1o2OGGUAA` | `plugins.app:access` | Access application plugins (still enforcing the organization role). | -| `fixed:provisioning:writer` | `fixed_bgk1FCyR6OEDwhgirZlQgu5LlCA` | `provisioning:reload` | Reload provisioning. | -| `fixed:reports:reader` | `fixed_72_8LU_0ukfm6BdblOw8Z9q-GQ8` | `reports:read`
`reports:send`
`reports.settings:read` | Read all reports and shared report settings. | -| `fixed:reports:writer` | `fixed_jBW3_7g1EWOjGVBYeVRwtFxhUNw` | All permissions from `fixed:reports:reader` and
`reports:create`
`reports:write`
`reports:delete`
`reports.settings:write` | Create, read, update, or delete all reports and shared report settings. | -| `fixed:roles:reader` | `fixed_GkfG-1NSwEGb4hpK3-E3qHyNltc` | `roles:read`
`teams.roles:read`
`users.roles:read`
`users.permissions:read` | Read all access control roles, roles and permissions assigned to users, teams. | -| `fixed:roles:resetter` | `fixed_WgPpC3qJRmVpVTJavFNwfS5RuzQ` | `roles:write` with scope `permissions:type:escalate` | Reset basic roles to their default. | -| `fixed:roles:writer` | `fixed_W5aFaw8isAM27x_eWfElBhZ0iOc` | All permissions from `fixed:roles:reader` and
`roles:write`
`roles:delete`
`teams.roles:add`
`teams.roles:remove`
`users.roles:add`
`users.roles:remove` | Create, read, update, or delete all roles, assign or unassign roles to users, teams. | -| `fixed:serviceaccounts:creator` | `fixed_Ikw60fckA0MyiiZ73BawSfOULy4` | `serviceaccounts:create` | Create Grafana service accounts. | -| `fixed:serviceaccounts:reader` | `fixed_QFjJAZ88iawMLInYOxPA1DB1w6I` | `serviceaccounts:read` | Read Grafana service accounts. | -| `fixed:serviceaccounts:writer` | `fixed_iBvUNUEZBZ7PUW0vdkN5iojc2sk` | `serviceaccounts:read`
`serviceaccounts:create`
`serviceaccounts:write`
`serviceaccounts:delete`
`serviceaccounts.permissions:read`
`serviceaccounts.permissions:write` | Create, update, read and delete all Grafana service accounts and manage service account permissions. | -| `fixed:settings:reader` | `fixed_0LaUt1x6PP8hsZzEBhqPQZFUd8Q` | `settings:read` | Read Grafana instance settings. | -| `fixed:settings:writer` | `fixed_joIHDgMrGg790hMhUufVzcU4j44` | All permissions from `fixed:settings:reader` and
`settings:write` | Read and update Grafana instance settings. | -| `fixed:stats:reader` | `fixed_OnRCXxZVINWpcKvTF5A1gecJ7pA` | `server.stats:read` | Read Grafana instance statistics. | -| `fixed:support.bundles:reader` | `fixed_gcPjI3PTUJwRx-GJZwDhNa7zbos` | `support.bundles:read` | List and download support bundles. | -| `fixed:support.bundles:writer` | `fixed_dTgCv9Wxrp_WHAhwHYIgeboxKpE` | `support.bundles:read`
`support.bundles:create`
`support.bundles:delete` | Create, delete, list and download support bundles. | -| `fixed:teams:creator` | `fixed_nzVQoNSDSn0fg1MDgO6XnZX2RZI` | `teams:create`
`org.users:read` | Create a team and list organization users (required to manage the created team). | -| `fixed:teams:read` | `fixed_Z8pB0GQlrqRt8IZBCJQxPWvJPgQ` | `teams:read` | List all teams. | -| `fixed:teams:writer` | `fixed_xw1T0579h620MOYi4L96GUs7fZY` | `teams:create`
`teams:delete`
`teams:read`
`teams:write`
`teams.permissions:read`
`teams.permissions:write` | Create, read, update and delete teams and manage team memberships. | -| `fixed:usagestats:reader` | `fixed_eAM0azEvnWFCJAjNkUKnGL_1-bU` | `server.usagestats.report:read` | View usage statistics report. | -| `fixed:users:reader` | `fixed_buZastUG3reWyQpPemcWjGqPAd0` | `users:read`
`users.quotas:read`
`users.authtoken:read` | Read all users and their information, such as team memberships, authentication tokens, and quotas. | -| `fixed:users:writer` | `fixed_wjzgHHo_Ux25DJuELn_oiAdB_yM` | All permissions from `fixed:users:reader` and
`users:write`
`users:create`
`users:delete`
`users:enable`
`users:disable`
`users.password:write`
`users.permissions:write`
`users:logout`
`users.authtoken:write`
`users.quotas:write` | Read and update all attributes and settings for all users in Grafana: update user information, read user information, create or enable or disable a user, make a user a Grafana administrator, sign out a user, update a user’s authentication token, or update quotas for all users. | +| Fixed role | UUID | Permissions | Description | +| ----------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `fixed:alerting:reader` | `fixed_O2oP1_uBFozI2i93klAkcvEWR30` | All permissions from `fixed:alerting.rules:reader`
`fixed:alerting.instances:reader`
`fixed:alerting.notifications:reader` | Read-only permissions for all Grafana, Mimir, Loki and Alertmanager alert rules\*, alerts, contact points, and notification policies.[\*](#alerting-roles) | +| `fixed:alerting:writer` | `fixed_-PAZgSJsDlRD8NUg-PFSeH_BkJY` | All permissions from `fixed:alerting.rules:writer`
`fixed:alerting.instances:writer`
`fixed:alerting.notifications:writer` | Create, update, and delete Grafana, Mimir, Loki and Alertmanager alert rules\*, silences, contact points, templates, mute timings, and notification policies.[\*](#alerting-roles) | +| `fixed:alerting.instances:reader` | `fixed_ut5fVS-Ulh_ejFoskFhJT_rYg0Y` | `alert.instances:read` for organization scope
`alert.instances.external:read` for scope `datasources:*` | Read all alerts and silences in the organization produced by Grafana Alerts and Mimir and Loki alerts and silences.[\*](#alerting-roles) | +| `fixed:alerting.instances:writer` | `fixed_pKOBJE346uyqMLdgWbk1NsQfEl0` | All permissions from `fixed:alerting.instances:reader` and
`alert.instances:create`
`alert.instances:write` for organization scope
`alert.instances.external:write` for scope `datasources:*` | Create, update and expire all silences in the organization produced by Grafana, Mimir, and Loki.[\*](#alerting-roles) | +| `fixed:alerting.notifications:reader` | `fixed_hmBn0lX5h1RZXB9Vaot420EEdA0` | `alert.notifications:read` for organization scope
`alert.notifications.external:read` for scope `datasources:*` | Read all Grafana and Alertmanager contact points, templates, and notification policies.[\*](#alerting-roles) | +| `fixed:alerting.notifications:writer` | `fixed_XplK6HPNxf9AP5IGTdB5Iun4tJc` | All permissions from `fixed:alerting.notifications:reader` and
`alert.notifications:write`for organization scope
`alert.notifications.external:read` for scope `datasources:*` | Create, update, and delete contact points, templates, mute timings and notification policies for Grafana and external Alertmanager.[\*](#alerting-roles) | +| `fixed:alerting.provisioning:writer` | `fixed_y7pFjdEkxpx5ETdcxPvp0AgRuUo` | `alert.provisioning:read` and `alert.provisioning:write` | Create, update and delete Grafana alert rules, notification policies, contact points, templates, etc via provisioning API. [\*](#alerting-roles) | +| `fixed:alerting.provisioning.secrets:reader` | `fixed_9fmzXXZZG-Od0Amy2ofEG8Uk--c` | `alert.provisioning:read` and `alert.provisioning.secrets:read` | Read-only permissions for Provisioning API and let export resources with decrypted secrets [\*](#alerting-roles) | +| `fixed:alerting.provisioning.provenance:writer` | `fixed_eAxlzfkTuobvKEgXHveFMBZrOj8` | `alert.provisioning.provenance:write` | Set provenance status to alert rules, notification policies, contact points, etc. Should be used together with regular writer roles. [\*](#alerting-roles) | +| `fixed:alerting.rules:reader` | `fixed_fRGKL_vAqUsmUWq5EYKnOha9DcA` | `alert.rule:read`, `alert.silences:read` for scope `folders:*`
`alert.rules.external:read` for scope `datasources:*`
`alert.notifications.time-intervals:read`
`alert.notifications.receivers:list` | Read all\* Grafana, Mimir, and Loki alert rules.[\*](#alerting-roles) and read rule-specific silences | +| `fixed:alerting.rules:writer` | `fixed_YJJGwAalUwDZPrXSyFH8GfYBXAc` | All permissions from `fixed:alerting.rules:reader` and
`alert.rule:create`
`alert.rule:write`
`alert.rule:delete`
`alert.silences:create`
`alert.silences:write` for scope `folders:*`
`alert.rules.external:write` for scope `datasources:*` | Create, update, and delete all\* Grafana, Mimir, and Loki alert rules.[\*](#alerting-roles) and manage rule-specific silences | +| `fixed:annotations:reader` | `fixed_hpZnoizrfAJsrceNcNQqWYV-xNU` | `annotations:read` for scopes `annotations:type:*` | Read all annotations and annotation tags. | +| `fixed:annotations:writer` | `fixed_ZVW-Aa9Tzle6J4s2aUFcq1StKWE` | All permissions from `fixed:annotations:reader`
`annotations:write`
`annotations.create`
`annotations:delete` for scope `annotations:type:*` | Read, create, update and delete all annotations and annotation tags. | +| `fixed:annotations.dashboard:writer` | `fixed_8A775xenXeKaJk4Cr7bchP9yXOA` | `annotations:write`
`annotations.create`
`annotations:delete` for scope `annotations:type:dashboard` | Create, update and delete dashboard annotations and annotation tags. | +| `fixed:authentication.config:writer` | `fixed_0rYhZ2Qnzs8AdB1nX7gexk3fHDw` | `settings:read` for scope `settings:auth.saml:*`
`settings:write` for scope `settings:auth.saml:*` | Read and update authentication and SAML settings. | +| `fixed:general.auth.config:writer` | `fixed_QFxIT_FGtBqbIVJIwx1bLgI5z6c` | `settings:read` for scope `settings:auth:oauth_allow_insecure_email_lookup`
`settings:write` for scope `settings:auth:oauth_allow_insecure_email_lookup` | Read and update the Grafana instance's general authentication configuration settings. | +| `fixed:dashboards:creator` | `fixed_ZorKUcEPCM01A1fPakEzGBUyU64` | `dashboards:create`
`folders:read` | Create dashboards. | +| `fixed:dashboards:reader` | `fixed_Sgr67JTOhjQGFlzYRahOe45TdWM` | `dashboards:read` | Read all dashboards. | +| `fixed:dashboards:writer` | `fixed_OK2YOQGIoI1G031hVzJB6rAJQAs` | All permissions from `fixed:dashboards:reader` and
`dashboards:write`
`dashboards:delete`
`dashboards:create`
`dashboards.permissions:read`
`dashboards.permissions:write` | Read, create, update, and delete all dashboards. | +| `fixed:dashboards.insights:reader` | `fixed_JlBJ2_gizP8zhgaeGE2rjyZe2Rs` | `dashboards.insights:read` | Read dashboard insights data and see presence indicators. | +| `fixed:dashboards.permissions:reader` | `fixed_f17oxuXW_58LL8mYJsm4T_mCeIw` | `dashboards.permissions:read` | Read all dashboard permissions. | +| `fixed:dashboards.permissions:writer` | `fixed_CcznxhWX_Yqn8uWMXMQ-b5iFW9k` | All permissions from `fixed:dashboards.permissions:reader` and
`dashboards.permissions:write` | Read and update all dashboard permissions. | +| `fixed:dashboards.public:writer` | `fixed_f_GHHRBciaqESXfGz2oCcooqHxs` | `dashboards.public:write` | Create, update, delete or pause a shared dashboard. | +| `fixed:datasources:creator` | `fixed_XX8jHREgUt-wo1A-rPXIiFlX6Zw` | `datasources:create` | Create data sources. | +| `fixed:datasources:explorer` | `fixed_qDzW9mzx9yM91T5Bi8dHUM2muTw` | `datasources:explore` | Enable the Explore feature. Data source permissions still apply, you can only query data sources for which you have query permissions. | +| `fixed:datasources:reader` | `fixed_C2x8IxkiBc1KZVjyYH775T9jNMQ` | `datasources:read`
`datasources:query` | Read and query data sources. | +| `fixed:datasources:writer` | `fixed_q8HXq8kjjA5IlHHgBJlKlUyaNik` | All permissions from `fixed:datasources:reader` and
`datasources:create`
`datasources:write`
`datasources:delete` | Read, query, create, delete, or update a data source. | +| `fixed:datasources.builtin:reader` | `fixed_q8HXq8kjjA5IlHHgBJlKlUyaNik` | `datasources:read` and `datasources:query` scoped to `datasources:uid:grafana` | An internal role used to grant Viewers access to the builtin example data source in Grafana. | +| `fixed:datasources.caching:reader` | `fixed_D2ddpGxJYlw0mbsTS1ek9fj0kj4` | `datasources.caching:read` | Read data source query caching settings. | +| `fixed:datasources.caching:writer` | `fixed_JtFjHr7jd7hSqUYcktKvRvIOGRE` | `datasources.caching:read`
`datasources.caching:write` | Enable, disable, or update query caching settings. | +| `fixed:datasources.id:reader` | `fixed_entg--fHmDqWY2-69N0ocawK0Os` | `datasources.id:read` | Read the ID of a data source based on its name. | +| `fixed:datasources.insights:reader` | `fixed_EBZ3NwlfecNPp2p0XcZRC1nfEYk` | `datasources.insights:read` | Read data source insights data. | +| `fixed:datasources.permissions:reader` | `fixed_ErYA-cTN3yn4h4GxaVPcawRhiOY` | `datasources.permissions:read` | Read data source permissions. | +| `fixed:datasources.permissions:writer` | `fixed_aiQh9YDfLOKjQhYasF9_SFUjQiw` | All permissions from `fixed:datasources.permissions:reader` and
`datasources.permissions:write` | Create, read, or delete permissions of a data source. | +| `fixed:folders:creator` | `fixed_gGLRbZGAGB6n9uECqSh_W382RlQ` | `folders:create` | Create folders in the root level. | +| `fixed:folders:reader` | `fixed_yeW-5QPeo-i5PZUIUXMlAA97GnQ` | `folders:read`
`dashboards:read` | Read all folders and dashboards. | +| `fixed:folders:writer` | `fixed_wJXLoTzgE7jVuz90dryYoiogL0o` | All permissions from `fixed:dashboards:writer` and
`folders:read`
`folders:write`
`folders:create`
`folders:delete`
`folders.permissions:read`
`folders.permissions:write` | Read, update, and delete all folders and dashboards. Create folders and subfolders. | +| `fixed:folders.general:reader` | `fixed_rSASbkg8DvpG_gTX5s41d7uxRvI` | `folders:read` scoped to `folders:uid:general` | An internal role used to correctly display access to the folder tree for Viewer role. | +| `fixed:folders.permissions:reader` | `fixed_E06l4cx0JFm47EeLBE4nmv3pnSo` | `folders.permissions:read` | Read all folder permissions. | +| `fixed:folders.permissions:writer` | `fixed_3GAgpQ_hWG8o7-lwNb86_VB37eI` | All permissions from `fixed:folders.permissions:reader` and
`folders.permissions:write` | Read and update all folder permissions. | +| `fixed:ldap:reader` | `fixed_lMcOPwSkxKY-qCK8NMJc5k6izLE` | `ldap.user:read`
`ldap.status:read` | Read the LDAP configuration and LDAP status information. | +| `fixed:ldap:writer` | `fixed_p6AvnU4GCQyIh7-hbwI-bk3GYnU` | All permissions from `fixed:ldap:reader` and
`ldap.user:sync`
`ldap.config:reload` | Read and update the LDAP configuration, and read LDAP status information. | +| `fixed:library.panels:creator` | `fixed_6eX6ItfegCIY5zLmPqTDW8ZV7KY` | `library.panels:create`
`folders:read` | Create library panel at the root level. | +| `fixed:library.panels:general.reader` | `fixed_ct0DghiBWR_2BiQm3EvNPDVmpio` | `library.panels:read` | Read all library panels at the root level. | +| `fixed:library.panels:general.writer` | `fixed_DgprkmqfN_1EhZ2v1_d1fYG8LzI` | All permissions from `fixed:library.panels:general.reader` plus
`library.panels:create`
`library.panels:delete`
`library.panels:write` | Create, read, write or delete all library panels and their permissions at the root level. | +| `fixed:library.panels:reader` | `fixed_tvTr9CnZ6La5vvUO_U_X1LPnhUs` | `library.panels:read` | Read all library panels. | +| `fixed:library.panels:writer` | `fixed_JTljAr21LWLTXCkgfBC4H0lhBC8` | All permissions from `fixed:library.panels:reader` plus
`library.panels:create`
`library.panels:delete`
`library.panels:write` | Create, read, write or delete all library panels and their permissions. | +| `fixed:licensing:reader` | `fixed_OADpuXvNEylO2Kelu3GIuBXEAYE` | `licensing:read`
`licensing.reports:read` | Read licensing information and licensing reports. | +| `fixed:licensing:writer` | `fixed_gzbz3rJpQMdaKHt-E4q0PVaKMoE` | All permissions from `fixed:licensing:reader` and
`licensing:write`
`licensing:delete` | Read licensing information and licensing reports, update and delete the license token. | +| `fixed:migrationassistant:migrator` | `fixed_LLk2p7TRuBztOAksTQb1Klc8YTk` | `migrationassistant:migrate` | Execute on-prem to cloud migrations through the Migration Assistant. | +| `fixed:org.users:reader` | `fixed_oCqNwlVHLOpw7-jAlwp4HzYqwGY` | `org.users:read` | Read users within a single organization. | +| `fixed:org.users:writer` | `fixed_VERj5nayasjgf_Yh0sWqqCkxWlw` | All permissions from `fixed:org.users:reader` and
`org.users:add`
`org.users:remove`
`org.users:write` | Within a single organization, add a user, invite a new user, read information about a user and their role, remove a user from that organization, or change the role of a user. | +| `fixed:organization:maintainer` | `fixed_CMm-uuBaPUBf4r8XG3jIvxo55bg` | All permissions from `fixed:organization:reader` and
`orgs:write`
`orgs:create`
`orgs:delete`
`orgs.quotas:write` | Create, read, write, or delete an organization. Read or write its quotas. This role needs to be assigned globally. | +| `fixed:organization:reader` | `fixed_0SZPJlTHdNEe8zO91zv7Zwiwa2w` | `orgs:read`
`orgs.quotas:read` | Read an organization and its quotas. | +| `fixed:organization:writer` | `fixed_Y4jGqDd8w1yCrPwlik8z5Iu8-3M` | All permissions from `fixed:organization:reader` and
`orgs:write`
`orgs.preferences:read`
`orgs.preferences:write` | Read an organization, its quotas, or its preferences. Update organization properties, or its preferences. | +| `fixed:plugins:maintainer` | `fixed_yEOKidBcWgbm74x-nTa3lW5lOyY` | `plugins:install` | Install and uninstall plugins. Needs to be assigned globally. | +| `fixed:plugins:writer` | `fixed_MRYpGk7kpNNwt2VoVOXFiPnQziE` | `plugins:write` | Enable and disable plugins and edit plugins' settings. | +| `fixed:plugins.app:reader` | `fixed_AcZRiNYx7NueYkUqzw1o2OGGUAA` | `plugins.app:access` | Access application plugins (still enforcing the organization role). | +| `fixed:provisioning:writer` | `fixed_bgk1FCyR6OEDwhgirZlQgu5LlCA` | `provisioning:reload` | Reload provisioning. | +| `fixed:reports:reader` | `fixed_72_8LU_0ukfm6BdblOw8Z9q-GQ8` | `reports:read`
`reports:send`
`reports.settings:read` | Read all reports and shared report settings. | +| `fixed:reports:writer` | `fixed_jBW3_7g1EWOjGVBYeVRwtFxhUNw` | All permissions from `fixed:reports:reader` and
`reports:create`
`reports:write`
`reports:delete`
`reports.settings:write` | Create, read, update, or delete all reports and shared report settings. | +| `fixed:roles:reader` | `fixed_GkfG-1NSwEGb4hpK3-E3qHyNltc` | `roles:read`
`teams.roles:read`
`users.roles:read`
`users.permissions:read` | Read all access control roles, roles and permissions assigned to users, teams. | +| `fixed:roles:resetter` | `fixed_WgPpC3qJRmVpVTJavFNwfS5RuzQ` | `roles:write` with scope `permissions:type:escalate` | Reset basic roles to their default. | +| `fixed:roles:writer` | `fixed_W5aFaw8isAM27x_eWfElBhZ0iOc` | All permissions from `fixed:roles:reader` and
`roles:write`
`roles:delete`
`teams.roles:add`
`teams.roles:remove`
`users.roles:add`
`users.roles:remove` | Create, read, update, or delete all roles, assign or unassign roles to users, teams. | +| `fixed:serviceaccounts:creator` | `fixed_Ikw60fckA0MyiiZ73BawSfOULy4` | `serviceaccounts:create` | Create Grafana service accounts. | +| `fixed:serviceaccounts:reader` | `fixed_QFjJAZ88iawMLInYOxPA1DB1w6I` | `serviceaccounts:read` | Read Grafana service accounts. | +| `fixed:serviceaccounts:writer` | `fixed_iBvUNUEZBZ7PUW0vdkN5iojc2sk` | `serviceaccounts:read`
`serviceaccounts:create`
`serviceaccounts:write`
`serviceaccounts:delete`
`serviceaccounts.permissions:read`
`serviceaccounts.permissions:write` | Create, update, read and delete all Grafana service accounts and manage service account permissions. | +| `fixed:settings:reader` | `fixed_0LaUt1x6PP8hsZzEBhqPQZFUd8Q` | `settings:read` | Read Grafana instance settings. | +| `fixed:settings:writer` | `fixed_joIHDgMrGg790hMhUufVzcU4j44` | All permissions from `fixed:settings:reader` and
`settings:write` | Read and update Grafana instance settings. | +| `fixed:stats:reader` | `fixed_OnRCXxZVINWpcKvTF5A1gecJ7pA` | `server.stats:read` | Read Grafana instance statistics. | +| `fixed:support.bundles:reader` | `fixed_gcPjI3PTUJwRx-GJZwDhNa7zbos` | `support.bundles:read` | List and download support bundles. | +| `fixed:support.bundles:writer` | `fixed_dTgCv9Wxrp_WHAhwHYIgeboxKpE` | `support.bundles:read`
`support.bundles:create`
`support.bundles:delete` | Create, delete, list and download support bundles. | +| `fixed:teams:creator` | `fixed_nzVQoNSDSn0fg1MDgO6XnZX2RZI` | `teams:create`
`org.users:read` | Create a team and list organization users (required to manage the created team). | +| `fixed:teams:read` | `fixed_Z8pB0GQlrqRt8IZBCJQxPWvJPgQ` | `teams:read` | List all teams. | +| `fixed:teams:writer` | `fixed_xw1T0579h620MOYi4L96GUs7fZY` | `teams:create`
`teams:delete`
`teams:read`
`teams:write`
`teams.permissions:read`
`teams.permissions:write` | Create, read, update and delete teams and manage team memberships. | +| `fixed:usagestats:reader` | `fixed_eAM0azEvnWFCJAjNkUKnGL_1-bU` | `server.usagestats.report:read` | View usage statistics report. | +| `fixed:users:reader` | `fixed_buZastUG3reWyQpPemcWjGqPAd0` | `users:read`
`users.quotas:read`
`users.authtoken:read` | Read all users and their information, such as team memberships, authentication tokens, and quotas. | +| `fixed:users:writer` | `fixed_wjzgHHo_Ux25DJuELn_oiAdB_yM` | All permissions from `fixed:users:reader` and
`users:write`
`users:create`
`users:delete`
`users:enable`
`users:disable`
`users.password:write`
`users.permissions:write`
`users:logout`
`users.authtoken:write`
`users.quotas:write` | Read and update all attributes and settings for all users in Grafana: update user information, read user information, create or enable or disable a user, make a user a Grafana administrator, sign out a user, update a user’s authentication token, or update quotas for all users. | ### Alerting roles @@ -164,10 +164,20 @@ Access to Grafana alert rules is an intersection of many permissions: - Permission to read a folder. For example, the fixed role `fixed:folders:reader` includes the action `folders:read` and a folder scope `folders:id:`. - Permission to query **all** data sources that a given alert rule uses. If a user cannot query a given data source, they cannot see any alert rules that query that data source. -There is only one exclusion at this moment. Role `fixed:alerting.provisioning:writer` does not require user to have any additional permissions and provides access to all aspects of the alerting configuration via special provisioning API. +There is only one exclusion. Role `fixed:alerting.provisioning:writer` does not require user to have any additional permissions and provides access to all aspects of the alerting configuration via special provisioning API. For more information about the permissions required to access alert rules, refer to [Create a custom role to access alerts in a folder](ref:plan-rbac-rollout-strategy-create-a-custom-role-to-access-alerts-in-a-folder). +#### Alerting basic roles + +The following table lists the default RBAC alerting role assignments to the basic roles: + +| Basic role | Associated fixed roles | Description | +| ---------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| Admin | `fixed:alerting:writer`
`fixed:alerting.provisioning.secrets:reader`
`fixed:alerting.provisioning:writer` | Default [Grafana organization administrator](ref:rbac-basic-roles) assignments. | +| Editor | `fixed:alerting:writer`
`fixed:alerting.provisioning.provenance:writer` | Default [Editor](ref:rbac-basic-roles) assignments. | +| Viewer | `fixed:alerting:reader` | Default [Viewer](ref:rbac-basic-roles) assignments. | + ### Grafana OnCall roles If you are using [Grafana OnCall](ref:oncall), you can try out the integration between Grafana OnCall and RBAC. diff --git a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-alertmanager.md b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-alertmanager.md index 4cdc84ec366..f34a9eeb654 100644 --- a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-alertmanager.md +++ b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-alertmanager.md @@ -59,9 +59,9 @@ For more details on contact points, including how to test them and enable notifi ## Alertmanager settings -| Option | Description | -| ------ | ---------------------------------------------------------------------------------------------------------------------------------- | -| URL | The Alertmanager URL. This field is [protected](ref:configure-contact-points#protected-fields) from modification in Grafana Cloud. | +| Option | Description | +| ------ | ----------------------------------------------------------------------------------------------------------------- | +| URL | The Alertmanager URL. This field is [protected](ref:configure-contact-points) from modification in Grafana Cloud. | #### Optional settings diff --git a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-jira.md b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-jira.md index 659341405f1..9f68f70ae08 100644 --- a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-jira.md +++ b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-jira.md @@ -49,14 +49,14 @@ For more details on contact points, including how to test them and enable notifi ### Required Settings -| Key | Description | -| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| URL | The URL of the REST API of your Jira instance. Supported versions: `2` and `3` (e.g., `https://your-domain.atlassian.net/rest/api/3`). This field is [protected](ref:configure-contact-points#protected-fields) from modification in Grafana Cloud. | -| Basic Auth User | Username for authentication. For Jira Cloud, use your email address. | -| Basic Auth Password | Password or personal token. For Jira Cloud, you need to obtain a personal token [here](https://id.atlassian.com/manage-profile/security/api-tokens) and use it as the password. | -| API Token | An alternative to basic authentication, a bearer token is used to authorize the API requests. See [Jira documentation](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html) for more information. | -| Project Key | The project key identifying the project where issues will be created. Project keys are unique identifiers for a project. | -| Issue Type | The type of issue to create (e.g., `Task`, `Bug`, `Incident`). Make sure that you specify a type that is available in your project. | +| Key | Description | +| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| URL | The URL of the REST API of your Jira instance. Supported versions: `2` and `3` (e.g., `https://your-domain.atlassian.net/rest/api/3`). This field is [protected](ref:configure-contact-points) from modification in Grafana Cloud. | +| Basic Auth User | Username for authentication. For Jira Cloud, use your email address. | +| Basic Auth Password | Password or personal token. For Jira Cloud, you need to obtain a personal token [here](https://id.atlassian.com/manage-profile/security/api-tokens) and use it as the password. | +| API Token | An alternative to basic authentication, a bearer token is used to authorize the API requests. See [Jira documentation](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html) for more information. | +| Project Key | The project key identifying the project where issues will be created. Project keys are unique identifiers for a project. | +| Issue Type | The type of issue to create (e.g., `Task`, `Bug`, `Incident`). Make sure that you specify a type that is available in your project. | ### Optional Settings diff --git a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-mqtt.md b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-mqtt.md index 6f76a574619..3f6a403d27a 100644 --- a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-mqtt.md +++ b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-mqtt.md @@ -54,10 +54,10 @@ For more details on contact points, including how to test them and enable notifi ### Required Settings -| Option | Description | -| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| Broker URL | The URL of the MQTT broker. This field is [protected](ref:configure-contact-points#protected-fields) from modification in Grafana Cloud. | -| Topic | The topic to which the message will be sent. | +| Option | Description | +| ---------- | ----------------------------------------------------------------------------------------------------------------------- | +| Broker URL | The URL of the MQTT broker. This field is [protected](ref:configure-contact-points) from modification in Grafana Cloud. | +| Topic | The topic to which the message will be sent. | ### Optional Settings diff --git a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-slack.md b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-slack.md index 8f56174ed60..3bda324ec23 100644 --- a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-slack.md +++ b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/configure-slack.md @@ -51,8 +51,8 @@ You can customize the `title` and `body` of the Slack message using [notificatio If you are using a Slack API Token, complete the following steps. -1. Follow steps 1 and 2 of the [Slack API Quickstart](https://api.slack.com/start/quickstart). -1. Add the [chat:write.public](https://api.slack.com/scopes/chat:write.public) scope to give your app the ability to post in all public channels without joining. +1. Follow step 1 of the [Slack API Quickstart](https://docs.slack.dev/app-management/quickstart-app-settings/#creating) to create the app. +1. Continue onto the second step of the [Slack API Quickstart](https://docs.slack.dev/app-management/quickstart-app-settings/#scopes) and add the [chat:write.public](https://api.slack.com/scopes/chat:write.public) scope as described to give your app the ability to post in all public channels without joining. 1. In OAuth Tokens for Your Workspace, copy the Bot User OAuth Token. 1. Open your Slack workplace. 1. Right click the channel you want to receive notifications in. diff --git a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier.md b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier.md index 120a45be2a2..d24b54fc568 100644 --- a/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier.md +++ b/docs/sources/alerting/configure-notifications/manage-contact-points/integrations/webhook-notifier.md @@ -62,9 +62,9 @@ For more details on contact points, including how to test them and enable notifi ## Webhook settings -| Option | Description | -| ------ | ----------------------------------------------------------------------------------------------------------------------------- | -| URL | The Webhook URL. This field is [protected](ref:configure-contact-points#protected-fields) from modification in Grafana Cloud. | +| Option | Description | +| ------ | ------------------------------------------------------------------------------------------------------------ | +| URL | The Webhook URL. This field is [protected](ref:configure-contact-points) from modification in Grafana Cloud. | #### Optional settings diff --git a/docs/sources/alerting/set-up/configure-alert-state-history/index.md b/docs/sources/alerting/set-up/configure-alert-state-history/index.md index 6ab7f817d92..dfb476b69ef 100644 --- a/docs/sources/alerting/set-up/configure-alert-state-history/index.md +++ b/docs/sources/alerting/set-up/configure-alert-state-history/index.md @@ -62,6 +62,9 @@ The following steps describe a basic configuration: # The URL of the Loki server loki_remote_url = http://localhost:3100 + + [feature_toggles] + enable = alertingCentralAlertHistory ``` 1. **Configure the Loki data source in Grafana** diff --git a/docs/sources/alerting/set-up/configure-rbac/_index.md b/docs/sources/alerting/set-up/configure-rbac/_index.md index 33fb9e57dcb..6e3338bab0b 100644 --- a/docs/sources/alerting/set-up/configure-rbac/_index.md +++ b/docs/sources/alerting/set-up/configure-rbac/_index.md @@ -17,54 +17,166 @@ weight: 155 # Configure RBAC -Role-based access control (RBAC) for Grafana Enterprise and Grafana Cloud provides a standardized way of granting, changing, and revoking access, so that users can view and modify Grafana resources. +[Role-based access control (RBAC)](/docs/grafana/latest/administration/roles-and-permissions/access-control/plan-rbac-rollout-strategy/) for Grafana Enterprise and Grafana Cloud provides a standardized way of granting, changing, and revoking access, so that users can view and modify Grafana resources. -A user is any individual who can log in to Grafana. Each user is associated with a role that includes permissions. Permissions determine the tasks a user can perform in the system. +A user is any individual who can log in to Grafana. Each user has a role that includes permissions. Permissions determine the tasks a user can perform in the system. Each permission contains one or more actions and a scope. +## Role types + +Grafana has three types of roles for managing access: + +- **Basic roles**: Admin, Editor, Viewer, and No basic role. These are assigned to users and provide default access levels. +- **Fixed roles**: Predefined groups of permissions for specific use cases. Basic roles automatically include certain fixed roles. +- **Custom roles**: User-defined roles that combine specific permissions for granular access control. + +## Basic role permissions + +The following table summarizes the default alerting permissions for each basic role. + +| Capability | Admin | Editor | Viewer | +| ----------------------------------------- | :---: | :----: | :----: | +| View alert rules | ✓ | ✓ | ✓ | +| Create, edit, and delete alert rules | ✓ | ✓ | | +| View silences | ✓ | ✓ | ✓ | +| Create, edit, and expire silences | ✓ | ✓ | | +| View contact points and templates | ✓ | ✓ | ✓ | +| Create, edit, and delete contact points | ✓ | ✓ | | +| View notification policies | ✓ | ✓ | ✓ | +| Create, edit, and delete policies | ✓ | ✓ | | +| View mute timings | ✓ | ✓ | ✓ | +| Create, edit, and delete timing intervals | ✓ | ✓ | | +| Access provisioning API | ✓ | ✓ | | +| Export with decrypted secrets | ✓ | | | + +{{< admonition type="note" >}} +Access to alert rules also requires permission to read the folder containing the rules and permission to query the data sources used in the rules. +{{< /admonition >}} + ## Permissions -Grafana Alerting has the following permissions. +Grafana Alerting has the following permissions organized by resource type. -| Action | Applicable scope | Description | -| -------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `alert.instances.external:read` | `datasources:*`
`datasources:uid:*` | Read alerts and silences in data sources that support alerting. | -| `alert.instances.external:write` | `datasources:*`
`datasources:uid:*` | Manage alerts and silences in data sources that support alerting. | -| `alert.instances:create` | n/a | Create silences in the current organization. | -| `alert.instances:read` | n/a | Read alerts and silences in the current organization. | -| `alert.instances:write` | n/a | Update and expire silences in the current organization. | -| `alert.notifications.external:read` | `datasources:*`
`datasources:uid:*` | Read templates, contact points, notification policies, and mute timings in data sources that support alerting. | -| `alert.notifications.external:write` | `datasources:*`
`datasources:uid:*` | Manage templates, contact points, notification policies, and mute timings in data sources that support alerting. | -| `alert.notifications:write` | n/a | Manage templates, contact points, notification policies, and mute timings in the current organization. | -| `alert.notifications:read` | n/a | Read all templates, contact points, notification policies, and mute timings in the current organization. | -| `alert.rules.external:read` | `datasources:*`
`datasources:uid:*` | Read alert rules in data sources that support alerting (Prometheus, Mimir, and Loki) | -| `alert.rules.external:write` | `datasources:*`
`datasources:uid:*` | Create, update, and delete alert rules in data sources that support alerting (Mimir and Loki). | -| `alert.rules:create` | `folders:*`
`folders:uid:*` | Create Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder and `datasources:query` in the scope of data sources the user can query. | -| `alert.rules:delete` | `folders:*`
`folders:uid:*` | Delete Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. | -| `alert.rules:read` | `folders:*`
`folders:uid:*` | Read Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. | -| `alert.rules:write` | `folders:*`
`folders:uid:*` | Update Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. To allow query modifications add `datasources:query` in the scope of data sources the user can query. | -| `alert.silences:create` | `folders:*`
`folders:uid:*` | Create rule-specific silences in a folder and its subfolders. | -| `alert.silences:read` | `folders:*`
`folders:uid:*` | Read all general silences and rule-specific silences in a folder and its subfolders. | -| `alert.silences:write` | `folders:*`
`folders:uid:*` | Update and expire rule-specific silences in a folder and its subfolders. | -| `alert.provisioning:read` | n/a | Read all Grafana alert rules, notification policies, etc via provisioning API. Permissions to folders and data source are not required. | -| `alert.provisioning.secrets:read` | n/a | Same as `alert.provisioning:read` plus ability to export resources with decrypted secrets. | -| `alert.provisioning:write` | n/a | Update all Grafana alert rules, notification policies, etc via provisioning API. Permissions to folders and data source are not required. | -| `alert.provisioning.provenance:write` | n/a | Set provisioning status for alerting resources. Cannot be used alone. Requires user to have permissions to access resources | -| `alert.notifications.receivers:read` | `receivers:*`
`receivers:uid:*` | Read contact points. | -| `alert.notifications.receivers.secrets:read` | `receivers:*`
`receivers:uid:*` | Export contact points with decrypted secrets. | -| `alert.notifications.receivers:create` | n/a | Create a new contact points. The creator is automatically granted full access to the created contact point. | -| `alert.notifications.receivers:write` | `receivers:*`
`receivers:uid:*` | Update existing contact points. | -| `alert.notifications.receivers:delete` | `receivers:*`
`receivers:uid:*` | Update and delete existing contact points. | -| `receivers.permissions:read` | `receivers:*`
`receivers:uid:*` | Read permissions for contact points. | -| `receivers.permissions:write` | `receivers:*`
`receivers:uid:*` | Manage permissions for contact points. | -| `alert.notifications.time-intervals:read` | n/a | Read mute time intervals. | -| `alert.notifications.time-intervals:write` | n/a | Create new or update existing mute time intervals. | -| `alert.notifications.time-intervals:delete` | n/a | Delete existing time intervals. | -| `alert.notifications.templates:read` | n/a | Read templates. | -| `alert.notifications.templates:write` | n/a | Create new or update existing templates. | -| `alert.notifications.templates:delete` | n/a | Delete existing templates. | -| `alert.notifications.routes:read` | n/a | Read notification policies. | -| `alert.notifications.routes:write` | n/a | Create new, update and update notification policies. | +### Alert rules + +Permissions for managing Grafana-managed alert rules. + +| Action | Applicable scope | Description | +| -------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `alert.rules:create` | `folders:*`
`folders:uid:*` | Create Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder and `datasources:query` in the scope of data sources the user can query. | +| `alert.rules:read` | `folders:*`
`folders:uid:*` | Read Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. | +| `alert.rules:write` | `folders:*`
`folders:uid:*` | Update Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. To allow query modifications add `datasources:query` in the scope of data sources the user can query. | +| `alert.rules:delete` | `folders:*`
`folders:uid:*` | Delete Grafana alert rules in a folder and its subfolders. Combine this permission with `folders:read` in a scope that includes the folder. | + +### External alert rules + +Permissions for managing alert rules in external data sources that support alerting. + +| Action | Applicable scope | Description | +| ---------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `alert.rules.external:read` | `datasources:*`
`datasources:uid:*` | Read alert rules in data sources that support alerting (Prometheus, Mimir, and Loki). | +| `alert.rules.external:write` | `datasources:*`
`datasources:uid:*` | Create, update, and delete alert rules in data sources that support alerting (Mimir and Loki). | + +### Alert instances and silences + +Permissions for managing alert instances and silences in Grafana. + +| Action | Applicable scope | Description | +| ------------------------ | ------------------------------ | ------------------------------------------------------------------------------------ | +| `alert.instances:read` | n/a | Read alerts and silences in the current organization. | +| `alert.instances:create` | n/a | Create silences in the current organization. | +| `alert.instances:write` | n/a | Update and expire silences in the current organization. | +| `alert.silences:read` | `folders:*`
`folders:uid:*` | Read all general silences and rule-specific silences in a folder and its subfolders. | +| `alert.silences:create` | `folders:*`
`folders:uid:*` | Create rule-specific silences in a folder and its subfolders. | +| `alert.silences:write` | `folders:*`
`folders:uid:*` | Update and expire rule-specific silences in a folder and its subfolders. | + +### External alert instances + +Permissions for managing alert instances in external data sources. + +| Action | Applicable scope | Description | +| -------------------------------- | -------------------------------------- | ----------------------------------------------------------------- | +| `alert.instances.external:read` | `datasources:*`
`datasources:uid:*` | Read alerts and silences in data sources that support alerting. | +| `alert.instances.external:write` | `datasources:*`
`datasources:uid:*` | Manage alerts and silences in data sources that support alerting. | + +### Contact points + +Permissions for managing contact points (notification receivers). + +| Action | Applicable scope | Description | +| -------------------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| `alert.notifications.receivers:list` | n/a | List contact points in the current organization. | +| `alert.notifications.receivers:read` | `receivers:*`
`receivers:uid:*` | Read contact points. | +| `alert.notifications.receivers.secrets:read` | `receivers:*`
`receivers:uid:*` | Export contact points with decrypted secrets. | +| `alert.notifications.receivers:create` | n/a | Create a new contact points. The creator is automatically granted full access to the created contact point. | +| `alert.notifications.receivers:write` | `receivers:*`
`receivers:uid:*` | Update existing contact points. | +| `alert.notifications.receivers:delete` | `receivers:*`
`receivers:uid:*` | Update and delete existing contact points. | +| `alert.notifications.receivers:test` | `receivers:*`
`receivers:uid:*` | Test contact points to verify their configuration. | +| `receivers.permissions:read` | `receivers:*`
`receivers:uid:*` | Read permissions for contact points. | +| `receivers.permissions:write` | `receivers:*`
`receivers:uid:*` | Manage permissions for contact points. | + +### Notification policies + +Permissions for managing notification policies (routing rules). + +| Action | Applicable scope | Description | +| ---------------------------------- | ---------------- | ----------------------------------------------------- | +| `alert.notifications.routes:read` | n/a | Read notification policies. | +| `alert.notifications.routes:write` | n/a | Create new, update, and delete notification policies. | + +### Time intervals + +Permissions for managing mute time intervals. + +| Action | Applicable scope | Description | +| ------------------------------------------- | ---------------- | -------------------------------------------------- | +| `alert.notifications.time-intervals:read` | n/a | Read mute time intervals. | +| `alert.notifications.time-intervals:write` | n/a | Create new or update existing mute time intervals. | +| `alert.notifications.time-intervals:delete` | n/a | Delete existing time intervals. | + +### Templates + +Permissions for managing notification templates. + +| Action | Applicable scope | Description | +| ------------------------------------------ | ---------------- | ------------------------------------------------------------------------------- | +| `alert.notifications.templates:read` | n/a | Read templates. | +| `alert.notifications.templates:write` | n/a | Create new or update existing templates. | +| `alert.notifications.templates:delete` | n/a | Delete existing templates. | +| `alert.notifications.templates.test:write` | n/a | Test templates with custom payloads (preview and payload editor functionality). | + +### General notifications + +Legacy permissions for managing all notification resources. + +| Action | Applicable scope | Description | +| --------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------- | +| `alert.notifications:read` | n/a | Read all templates, contact points, notification policies, and mute timings in the current organization. | +| `alert.notifications:write` | n/a | Manage templates, contact points, notification policies, and mute timings in the current organization. | + +### External notifications + +Permissions for managing notification resources in external data sources. + +| Action | Applicable scope | Description | +| ------------------------------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| `alert.notifications.external:read` | `datasources:*`
`datasources:uid:*` | Read templates, contact points, notification policies, and mute timings in data sources that support alerting. | +| `alert.notifications.external:write` | `datasources:*`
`datasources:uid:*` | Manage templates, contact points, notification policies, and mute timings in data sources that support alerting. | + +### Provisioning + +Permissions for managing alerting resources via the provisioning API. + +| Action | Applicable scope | Description | +| ---------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `alert.provisioning:read` | n/a | Read all Grafana alert rules, notification policies, etc via provisioning API. Permissions to folders and data source are not required. | +| `alert.provisioning.secrets:read` | n/a | Same as `alert.provisioning:read` plus ability to export resources with decrypted secrets. | +| `alert.provisioning:write` | n/a | Update all Grafana alert rules, notification policies, etc via provisioning API. Permissions to folders and data source are not required. | +| `alert.rules.provisioning:read` | n/a | Read Grafana alert rules via provisioning API. More specific than `alert.provisioning:read`. | +| `alert.rules.provisioning:write` | n/a | Create, update, and delete Grafana alert rules via provisioning API. More specific than `alert.provisioning:write`. | +| `alert.notifications.provisioning:read` | n/a | Read notification resources (contact points, notification policies, templates, time intervals) via provisioning API. More specific than `alert.provisioning:read`. | +| `alert.notifications.provisioning:write` | n/a | Create, update, and delete notification resources via provisioning API. More specific than `alert.provisioning:write`. | +| `alert.provisioning.provenance:write` | n/a | Set provisioning status for alerting resources. Cannot be used alone. Requires user to have permissions to access resources. | To help plan your RBAC rollout strategy, refer to [Plan your RBAC rollout strategy](https://grafana.com/docs/grafana/next/administration/roles-and-permissions/access-control/plan-rbac-rollout-strategy/). diff --git a/docs/sources/alerting/set-up/configure-rbac/access-folders/index.md b/docs/sources/alerting/set-up/configure-rbac/access-folders/index.md index 10fb63385ff..825629089cb 100644 --- a/docs/sources/alerting/set-up/configure-rbac/access-folders/index.md +++ b/docs/sources/alerting/set-up/configure-rbac/access-folders/index.md @@ -16,7 +16,7 @@ title: Manage access using folders or data sources weight: 200 --- -## Manage access using folders or data sources +# Manage access using folders or data sources You can extend the access provided by a role to alert rules and rule-specific silences by assigning permissions to individual folders or data sources. diff --git a/docs/sources/alerting/set-up/configure-rbac/access-roles/index.md b/docs/sources/alerting/set-up/configure-rbac/access-roles/index.md index 668e84c41cb..b3c51d4f866 100644 --- a/docs/sources/alerting/set-up/configure-rbac/access-roles/index.md +++ b/docs/sources/alerting/set-up/configure-rbac/access-roles/index.md @@ -55,16 +55,16 @@ Details of the fixed roles and the access they provide for Grafana Alerting are | Full read-only access: `fixed:alerting:reader` | All permissions from `fixed:alerting.rules:reader`
`fixed:alerting.instances:reader`
`fixed:alerting.notifications:reader` | Read alert rules, alert instances, silences, contact points, and notification policies in Grafana and external providers. | | Read via Provisioning API + Export Secrets: `fixed:alerting.provisioning.secrets:reader` | `alert.provisioning:read` and `alert.provisioning.secrets:read` | Read alert rules, alert instances, silences, contact points, and notification policies using the provisioning API and use export with decrypted secrets. | | Access to alert rules provisioning API: `fixed:alerting.provisioning:writer` | `alert.provisioning:read` and `alert.provisioning:write` | Manage all alert rules, notification policies, contact points, templates, in the organization using the provisioning API. | -| Set provisioning status: `fixed:alerting.provisioning.status:writer` | `alert.provisioning.provenance:write` | Set provisioning rules for Alerting resources. Should be used together with other regular roles (Notifications Writer and/or Rules Writer.) | +| Set provisioning status: `fixed:alerting.provisioning.provenance:writer` | `alert.provisioning.provenance:write` | Set provisioning rules for Alerting resources. Should be used together with other regular roles (Notifications Writer and/or Rules Writer.) | | Contact Point Reader: `fixed:alerting.receivers:reader` | `alert.notifications.receivers:read` for scope `receivers:*` | Read all contact points. | | Contact Point Creator: `fixed:alerting.receivers:creator` | `alert.notifications.receivers:create` | Create a new contact point. The user is automatically granted full access to the created contact point. | | Contact Point Writer: `fixed:alerting.receivers:writer` | `alert.notifications.receivers:read`, `alert.notifications.receivers:write`, `alert.notifications.receivers:delete` for scope `receivers:*` and
`alert.notifications.receivers:create` | Create a new contact point and manage all existing contact points. | | Templates Reader: `fixed:alerting.templates:reader` | `alert.notifications.templates:read` | Read all notification templates. | -| Templates Writer: `fixed:alerting.templates:writer` | `alert.notifications.templates:read`, `alert.notifications.templates:write`, `alert.notifications.templates:delete` | Create new and manage existing notification templates. | +| Templates Writer: `fixed:alerting.templates:writer` | `alert.notifications.templates:read`, `alert.notifications.templates:write`, `alert.notifications.templates:delete`, `alert.notifications.templates.test:write` | Create new and manage existing notification templates. Test templates with custom payloads. | | Time Intervals Reader: `fixed:alerting.time-intervals:reader` | `alert.notifications.time-intervals:read` | Read all time intervals. | | Time Intervals Writer: `fixed:alerting.time-intervals:writer` | `alert.notifications.time-intervals:read`, `alert.notifications.time-intervals:write`, `alert.notifications.time-intervals:delete` | Create new and manage existing time intervals. | -| Notification Policies Reader: `fixed:alerting.routes:reader` | `alert.notifications.routes:read` | Read all time intervals. | -| Notification Policies Writer: `fixed:alerting.routes:writer` | `alert.notifications.routes:read` `alert.notifications.routes:write` | Create new and manage existing time intervals. | +| Notification Policies Reader: `fixed:alerting.routes:reader` | `alert.notifications.routes:read` | Read all notification policies. | +| Notification Policies Writer: `fixed:alerting.routes:writer` | `alert.notifications.routes:read`
`alert.notifications.routes:write` | Create new and manage existing notification policies. | ## Create custom roles diff --git a/docs/sources/alerting/set-up/configure-roles/index.md b/docs/sources/alerting/set-up/configure-roles/index.md index 36adb865ab3..091d11de7bf 100644 --- a/docs/sources/alerting/set-up/configure-roles/index.md +++ b/docs/sources/alerting/set-up/configure-roles/index.md @@ -16,25 +16,27 @@ weight: 150 # Configure roles and permissions +This guide explains how to configure roles and permissions for Grafana Alerting for Grafana OSS users. You'll learn how to manage access using roles, folder permissions, and contact point permissions. + A user is any individual who can log in to Grafana. Each user is associated with a role that includes permissions. Permissions determine the tasks a user can perform in the system. For example, the Admin role includes permissions for an administrator to create and delete users. For more information, refer to [Organization roles](https://grafana.com/docs/grafana//administration/roles-and-permissions/#organization-roles). ## Manage access using roles -For Grafana OSS, there are three roles: Admin, Editor, and Viewer. +Grafana OSS has three roles: Admin, Editor, and Viewer. -Details of the roles and the access they provide for Grafana Alerting are below. +The following table describes the access each role provides for Grafana Alerting. -| Role | Access | -| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Admin | Write access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences), and provisioning. | -| Editor | Write access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences), and provisioning. | -| Viewer | Read access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences). | +| Role | Access | +| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Viewer | Read access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences). | +| Editor | Write access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences), and provisioning. | +| Admin | Write access to alert rules, notification resources (notification API, contact points, templates, time intervals, notification policies, and silences), and provisioning, as well as assign roles. | ## Assign roles -To assign roles, admins need to complete the following steps. +To assign roles, an admin needs to complete the following steps. 1. Navigate to **Administration** > **Users and access** > **Users, Teams, or Service Accounts**. 1. Search for the user, team or service account you want to add a role for. @@ -58,32 +60,30 @@ Refer to the following table for details on the additional access provided by fo You can't use folders to customize access to notification resources. {{< /admonition >}} -To manage folder permissions, complete the following steps. +To manage folder permissions, complete the following steps: 1. In the left-side menu, click **Dashboards**. 1. Hover your mouse cursor over a folder and click **Go to folder**. 1. Click **Manage permissions** from the Folder actions menu. 1. Update or add permissions as required. -## Manage access using contact point permissions +## Manage access to contact points -### Before you begin - -Extend or limit the access provided by a role to contact points by assigning permissions to individual contact point. +Extend or limit the access provided by a role to contact points by assigning permissions to individual contact points. This allows different users, teams, or service accounts to have customized access to read or modify specific contact points. Refer to the following table for details on the additional access provided by contact point permissions. -| Folder permission | Additional Access | -| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| View | View and export contact point as well as select it on the Alert rule edit page | -| Edit | Update or delete the contact point | -| Admin | Same additional access as Edit and manage permissions for the contact point. User should have additional permissions to read users and teams. | +| Contact point permission | Additional Access | +| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | +| View | View and export contact point as well as select it on the Alert rule edit page | +| Edit | Update or delete the contact point | +| Admin | Same additional access as Edit and manage permissions for the contact point. User should have additional permissions to read users and teams. | -### Steps +### Assign contact point permissions -To contact point permissions, complete the following steps. +To manage contact point permissions, complete the following steps: 1. In the left-side menu, click **Contact points**. 1. Hover your mouse cursor over a contact point and click **More**. diff --git a/docs/sources/as-code/infrastructure-as-code/grafana-operator/manage-dashboards-argocd.md b/docs/sources/as-code/infrastructure-as-code/grafana-operator/manage-dashboards-argocd.md index 0531a0c803f..bfc369222c8 100644 --- a/docs/sources/as-code/infrastructure-as-code/grafana-operator/manage-dashboards-argocd.md +++ b/docs/sources/as-code/infrastructure-as-code/grafana-operator/manage-dashboards-argocd.md @@ -81,7 +81,7 @@ Replace the placeholders with your values: In your `grafana` directory, create a sub-folder called `dashboards`. -This guide shows you how to creates three separate dashboards. For all dashboard configurations, replace the placeholders with your values: +This guide shows you how to create three separate dashboards. For all dashboard configurations, replace the placeholders with your values: - _``_: Name of your Grafana Cloud Stack - _``_: Namespace where the `grafana-operator` is deployed in your Kubernetes cluster diff --git a/docs/sources/as-code/infrastructure-as-code/terraform/terraform-plugins.md b/docs/sources/as-code/infrastructure-as-code/terraform/terraform-plugins.md index f0626540ca3..eea698aace1 100644 --- a/docs/sources/as-code/infrastructure-as-code/terraform/terraform-plugins.md +++ b/docs/sources/as-code/infrastructure-as-code/terraform/terraform-plugins.md @@ -24,7 +24,7 @@ Before you begin, you should have the following available: - Administrator permissions in your Grafana instance; for more information on assigning Grafana RBAC roles, refer to [Assign RBAC roles](/docs/grafana-cloud/security-and-account-management/authentication-and-permissions/access-control/assign-rbac-roles/). {{< admonition type="note" >}} -All of the following Terraform configuration files should be saved in the same directory. +Save all of the following Terraform configuration files in the same directory. {{< /admonition >}} ## Configure the Grafana provider diff --git a/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md b/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md index f2cd24a46b1..d071ccca0de 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/file-path-setup.md @@ -54,7 +54,7 @@ For production systems, use the `folderFromFilesStructure` capability instead of ## Before you begin {{< admonition type="note" >}} -Enable the `provisioning` and `kubernetesDashboards` feature toggles in Grafana to use this feature. +Enable the `provisioning` feature toggle in Grafana to use this feature. {{< /admonition >}} To set up file provisioning, you need: @@ -67,7 +67,7 @@ To set up file provisioning, you need: ## Enable required feature toggles and configure permitted paths -To activate local file provisioning in Grafana, you need to enable the `provisioning` and `kubernetesDashboards` feature toggles. +To activate local file provisioning in Grafana, you need to enable the `provisioning` feature toggle. For additional information about feature toggles, refer to [Configure feature toggles](https://grafana.com/docs/grafana//setup-grafana/configure-grafana/feature-toggles). The local setting must be a relative path and its relative path must be configured in the `permitted_provisioned_paths` configuration option. @@ -82,12 +82,11 @@ Any subdirectories are automatically included. The values that you enter for the `permitted_provisioning_paths` become the base paths for those entered when you enter a local path in the **Connect to local storage** wizard. 1. Open your Grafana configuration file, either `grafana.ini` or `custom.ini`. For file location based on operating system, refer to [Configuration file location](https://grafana.com/docs/grafana//setup-grafana/configure-grafana/feature-toggles/#experimental-feature-toggles). -1. Locate or add a `[feature_toggles]` section. Add these values: +1. Locate or add a `[feature_toggles]` section. Add this value: ```ini [feature_toggles] provisioning = true - kubernetesDashboards = true ; use k8s from browser ``` 1. Locate or add a `[paths]` section. To add more than one location, use the pipe character (`|`) to separate the paths. The list should not include empty paths or trailing pipes. Add these values: diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/_index.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/_index.md new file mode 100644 index 00000000000..4e4e523bf35 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/_index.md @@ -0,0 +1,147 @@ +--- +title: Git Sync deployment scenarios +menuTitle: Deployment scenarios +description: Learn about common Git Sync deployment patterns and configurations for different organizational needs +weight: 450 +keywords: + - git sync + - deployment patterns + - scenarios + - multi-environment + - teams +--- + +# Git Sync deployment scenarios + +This guide shows practical deployment scenarios for Grafana’s Git Sync. Learn how to configure bidirectional synchronization between Grafana and Git repositories for teams, environments, and regions. + +{{< admonition type="caution" >}} +Git Sync is an experimental feature. It reflects Grafana’s approach to Observability as Code and might include limitations or breaking changes. For current status and known limitations, refer to the [Git Sync introduction](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/intro-git-sync/). +{{< /admonition >}} + +## Understand the relationship between key Git Sync components + +Before you explore the scenarios, understand how the key Git Sync components relate: + +- [Grafana instance](#grafana-instance) +- [Git repository structure](#git-repository-structure) +- [Git Sync repository resource](#git-sync-repository-resource) + +### Grafana instance + +A Grafana instance is a running Grafana server. Multiple instances can: + +- Connect to the same Git repository using different Repository configurations. +- Sync from different branches of the same repository. +- Sync from different paths within the same repository. +- Sync from different repositories. + +### Git repository structure + +You can organize your Git repository in several ways: + +- Single branch, multiple paths: Use different directories for different purposes (for example, `dev/`, `prod/`, `team-a/`). +- Multiple branches: Use different branches for different environments or teams (for example, `main`, `develop`, `team-a`). +- Multiple repositories: Use separate repositories for different teams or environments. + +### Git Sync repository resource + +A repository resource is a Grafana configuration object that defines: + +- Which Git repository to sync with. +- Which branch to use. +- Which directory path to synchronize. +- Sync behavior and workflows. + +Each repository resource creates bidirectional synchronization between a Grafana instance and a specific location in Git. + +## How does repository sync behave? + +With Git Sync you configure a repository resource to sync with your Grafana instance: + +1. Grafana monitors the specified Git location (repository, branch, and path). +2. Grafana creates a folder in Dashboards (typically named after the repository). +3. Grafana creates dashboards from dashboard JSON files in Git within this folder. +4. Grafana commits dashboard changes made in the UI back to Git. +5. Grafana pulls dashboard changes made in Git and updates dashboards in the UI. +6. Synchronization occurs at regular intervals (configurable), or instantly if you use webhooks. + +You can find the provisioned dashboards organized in folders under **Dashboards**. + +## Example: Relationship between repository, branch, and path + +Here's a concrete example showing how the three parameters work together: + +**Configuration:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `team-platform/grafana/` + +**In Git (on branch `main`):** + +``` +your-org/grafana-manifests/ +├── .git/ +├── README.md +├── team-platform/ +│ └── grafana/ +│ ├── cpu-metrics.json ← Synced +│ ├── memory-usage.json ← Synced +│ └── disk-io.json ← Synced +├── team-data/ +│ └── grafana/ +│ └── pipeline-stats.json ← Not synced (different path) +└── other-files.txt ← Not synced (outside path) +``` + +**In Grafana Dashboards view:** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── CPU Metrics Dashboard + ├── Memory Usage Dashboard + └── Disk I/O Dashboard +``` + +**Key points:** + +- Grafana only synchronizes files within the specified path (`team-platform/grafana/`). +- Grafana ignores files in other paths or at the repository root. +- The folder name in Grafana comes from the repository name. +- Dashboard titles come from the JSON file content, not the filename. + +## Repository configuration flexibility + +Git Sync repositories support different combinations of repository URL, branch, and path: + +- Different Git repositories: Each environment or team can use its own repository. + - Instance A: `repository: your-org/grafana-prod`. + - Instance B: `repository: your-org/grafana-dev`. +- Different branches: Use separate branches within the same repository. + - Instance A: `repository: your-org/grafana-manifests, branch: main`. + - Instance B: `repository: your-org/grafana-manifests, branch: develop`. +- Different paths: Use different directory paths within the same repository. + - Instance A: `repository: your-org/grafana-manifests, branch: main, path: production/`. + - Instance B: `repository: your-org/grafana-manifests, branch: main, path: development/`. +- Any combination: Mix and match based on your workflow requirements. + +## Scenarios + +Use these deployment scenarios to plan your Git Sync setup: + +- [Single instance](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/single-instance/) +- [Git Sync for development and production environments](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/dev-prod/) +- [Git Sync with regional replication](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-region/) +- [High availability](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/high-availability/) +- [Git Sync in a shared Grafana instance](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-team/) + +## Learn more + +Refer to the following documents to learn more: + +- [Git Sync introduction](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/intro-git-sync/) +- [Git Sync setup guide](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-setup/) +- [Dashboard provisioning](https://grafana.com/docs/grafana//administration/provisioning/) +- [Observability as Code](https://grafana.com/docs/grafana//as-code/observability-as-code/) diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/dev-prod.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/dev-prod.md new file mode 100644 index 00000000000..3433c713024 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/dev-prod.md @@ -0,0 +1,147 @@ +--- +title: Git Sync for development and production environments +menuTitle: Across environments +description: Use separate Grafana instances for development and production with Git-controlled promotion +weight: 20 +--- + +# Git Sync for development and production environments + +Use separate Grafana instances for development and production. Each syncs with different Git locations to test dashboards before production. + +## Use it for + +- **Staged deployments**: You need to test dashboard changes before production deployment. +- **Change control**: You require approvals before dashboards reach production. +- **Quality assurance**: You verify dashboard functionality in a non-production environment. +- **Risk mitigation**: You minimize the risk of breaking production dashboards. + +## Architecture + +``` +┌────────────────────────────────────────────────────────────┐ +│ GitHub Repository │ +│ Repository: your-org/grafana-manifests │ +│ Branch: main │ +│ │ +│ grafana-manifests/ │ +│ ├── dev/ │ +│ │ ├── dashboard-new.json ← Development dashboards │ +│ │ └── dashboard-test.json │ +│ │ │ +│ └── prod/ │ +│ ├── dashboard-stable.json ← Production dashboards │ +│ └── dashboard-approved.json │ +└────────────────────────────────────────────────────────────┘ + ↕ ↕ + Git Sync (dev/) Git Sync (prod/) + ↕ ↕ +┌─────────────────────┐ ┌─────────────────────┐ +│ Dev Grafana │ │ Prod Grafana │ +│ │ │ │ +│ Repository: │ │ Repository: │ +│ - path: dev/ │ │ - path: prod/ │ +│ │ │ │ +│ Creates folder: │ │ Creates folder: │ +│ "grafana-manifests"│ │ "grafana-manifests"│ +└─────────────────────┘ └─────────────────────┘ +``` + +## Repository structure + +**In Git:** + +``` +your-org/grafana-manifests +├── dev/ +│ ├── dashboard-new.json +│ └── dashboard-test.json +└── prod/ + ├── dashboard-stable.json + └── dashboard-approved.json +``` + +**In Grafana Dashboards view:** + +**Dev instance:** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── New Dashboard + └── Test Dashboard +``` + +**Prod instance:** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── Stable Dashboard + └── Approved Dashboard +``` + +- Both instances create a folder named "grafana-manifests" (from repository name) +- Each instance only shows dashboards from its configured path (`dev/` or `prod/`) +- Dashboards appear with their titles from the JSON files + +## Configuration parameters + +Development: + +- Repository: `your-org/grafana-manifests` +- Branch: `main` +- Path: `dev/` + +Production: + +- Repository: `your-org/grafana-manifests` +- Branch: `main` +- Path: `prod/` + +## How it works + +1. Developers create and modify dashboards in development. +2. Git Sync commits changes to `dev/`. +3. You review changes in Git. +4. You promote approved dashboards from `dev/` to `prod/`. +5. Production syncs from `prod/`. +6. Production dashboards update. + +## Alternative: Use branches + +Instead of using different paths, you can configure instances to use different branches: + +**Development instance:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `develop` +- **Path**: `grafana/` + +**Production instance:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `grafana/` + +With this approach: + +- Development changes go to the `develop` branch +- Use Git merge or pull request workflows to promote changes from `develop` to `main` +- Production automatically syncs from the `main` branch + +## Alternative: Use separate repositories for stricter isolation + +For stricter isolation, use completely separate repositories: + +**Development instance:** + +- **Repository**: `your-org/grafana-manifests-dev` +- **Branch**: `main` +- **Path**: `grafana/` + +**Production instance:** + +- **Repository**: `your-org/grafana-manifests-prod` +- **Branch**: `main` +- **Path**: `grafana/` diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/high-availability.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/high-availability.md new file mode 100644 index 00000000000..04575574ed4 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/high-availability.md @@ -0,0 +1,217 @@ +--- +title: Git Sync for high availability environments +menuTitle: High availability +description: Run multiple Grafana instances serving traffic simultaneously, synchronized via Git Sync +weight: 50 +--- + +# Git Sync for high availability environments + +## Primary–replica scenario + +Use a primary Grafana instance and one or more replicas synchronized with the same Git location to enable failover. + +### Use it for + +- **Automatic failover**: You need service continuity when the primary instance fails. +- **High availability**: Your organization requires guaranteed dashboard availability. +- **Simple HA setup**: You want high availability without the complexity of active–active. +- **Maintenance windows**: You perform updates while another instance serves traffic. +- **Business continuity**: Dashboard access can't tolerate downtime. + +### Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ GitHub Repository │ +│ Repository: your-org/grafana-manifests │ +│ Branch: main │ +│ │ +│ grafana-manifests/ │ +│ └── shared/ │ +│ ├── dashboard-metrics.json │ +│ ├── dashboard-alerts.json │ +│ └── dashboard-logs.json │ +└─────────────────────────────────────────────────────┘ + ↕ ↕ + Git Sync (shared/) Git Sync (shared/) + ↕ ↕ +┌────────────────────┐ ┌────────────────────┐ +│ Master Grafana │ │ Replica Grafana │ +│ (Active) │ │ (Standby) │ +│ │ │ │ +│ Repository: │ │ Repository: │ +│ - path: shared/ │ │ - path: shared/ │ +└────────────────────┘ └────────────────────┘ + │ │ + └───────────┬───────────────────┘ + ↓ + ┌──────────────────────┐ + │ Reverse Proxy │ + │ (Failover) │ + └──────────────────────┘ +``` + +### Repository structure + +**In Git:** + +``` +your-org/grafana-manifests +└── shared/ + ├── dashboard-metrics.json + ├── dashboard-alerts.json + └── dashboard-logs.json +``` + +**In Grafana Dashboards view (both instances):** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── Metrics Dashboard + ├── Alerts Dashboard + └── Logs Dashboard +``` + +- Master and replica instances show identical folder structure. +- Both sync from the same `shared/` path. +- Reverse proxy routes traffic to master (active) instance. +- If master fails, proxy automatically fails over to replica (standby). +- Users see the same dashboards regardless of which instance is serving traffic. + +### Configuration parameters + +Both master and replica instances use identical parameters: + +**Master instance:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `shared/` + +**Replica instance:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `shared/` + +### How it works + +1. Both instances stay synchronized through Git. +2. Reverse proxy routes traffic to primary. +3. Users edit on primary. Git Sync commits changes. +4. Both instances pull latest changes to keep replica in sync. +5. On primary failure, proxy fails over to replica. + +### Failover considerations + +- Health checks and monitoring. +- Continuous syncing to minimize data loss. +- Plan failback (automatic or manual). + +## Load balancer scenario + +Run multiple active Grafana instances behind a load balancer. All instances sync from the same Git location. + +### Use it for + +- **High traffic**: Your deployment needs to handle significant user load. +- **Load distribution**: You want to distribute user requests across instances. +- **Maximum availability**: You need service continuity during maintenance or failures. +- **Scalability**: You want to add instances as load increases. +- **Performance**: Users need fast response times under heavy load. + +### Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ GitHub Repository │ +│ Repository: your-org/grafana-manifests │ +│ Branch: main │ +│ │ +│ grafana-manifests/ │ +│ └── shared/ │ +│ ├── dashboard-metrics.json │ +│ ├── dashboard-alerts.json │ +│ └── dashboard-logs.json │ +└─────────────────────────────────────────────────────┘ + ↕ ↕ + Git Sync (shared/) Git Sync (shared/) + ↕ ↕ +┌────────────────────┐ ┌────────────────────┐ +│ Grafana Instance 1│ │ Grafana Instance 2│ +│ (Active) │ │ (Active) │ +│ │ │ │ +│ Repository: │ │ Repository: │ +│ - path: shared/ │ │ - path: shared/ │ +└────────────────────┘ └────────────────────┘ + │ │ + └───────────┬───────────────────┘ + ↓ + ┌──────────────────────┐ + │ Load Balancer │ + │ (Round Robin) │ + └──────────────────────┘ +``` + +### Repository structure + +**In Git:** + +``` +your-org/grafana-manifests +└── shared/ + ├── dashboard-metrics.json + ├── dashboard-alerts.json + └── dashboard-logs.json +``` + +**In Grafana Dashboards view (all instances):** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── Metrics Dashboard + ├── Alerts Dashboard + └── Logs Dashboard +``` + +- All instances show identical folder structure. +- All instances sync from the same `shared/` path. +- Load balancer distributes requests across all active instances. +- Any instance can serve read requests. +- Any instance can accept dashboard modifications. +- Changes propagate to all instances through Git. + +### Configuration parameters + +All instances use identical parameters: + +**Instance 1:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `shared/` + +**Instance 2:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `shared/` + +### How it works + +1. All instances stay synchronized through Git. +2. Load balancer distributes incoming traffic across all active instances. +3. Users can view dashboards from any instance. +4. When a user modifies a dashboard on any instance, Git Sync commits the change. +5. All other instances pull the updated dashboard during their next sync cycle, or instantly if webhooks are configured. +6. If one instance fails, load balancer stops routing traffic to it and remaining instances continue serving. + +### Important considerations + +- **Eventually consistent**: Due to sync intervals, instances may briefly have different dashboard versions. +- **Concurrent edits**: Multiple users editing the same dashboard on different instances can cause conflicts. +- **Database sharing**: Instances should share the same backend database for user sessions, preferences, and annotations. +- **Stateless design**: Design for stateless operation where possible to maximize load balancing effectiveness. diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-region.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-region.md new file mode 100644 index 00000000000..ee699719560 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-region.md @@ -0,0 +1,93 @@ +--- +title: Git Sync with regional replication +menuTitle: Regional replication +description: Synchronize multiple regional Grafana instances from a shared Git location +weight: 30 +--- + +# Git Sync with regional replication + +Deploy multiple Grafana instances across regions. Synchronize them with the same Git location to ensure consistent dashboards everywhere. + +## Use it for + +- **Geographic distribution**: You deploy Grafana close to users in different regions. +- **Latency reduction**: Users need fast dashboard access from their location. +- **Data sovereignty**: You keep dashboard data in specific regions. +- **High availability**: You need dashboard availability across regions. +- **Consistent experience**: All users see the same dashboards regardless of region. + +## Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ GitHub Repository │ +│ Repository: your-org/grafana-manifests │ +│ Branch: main │ +│ │ +│ grafana-manifests/ │ +│ └── shared/ │ +│ ├── dashboard-global.json │ +│ ├── dashboard-metrics.json │ +│ └── dashboard-logs.json │ +└─────────────────────────────────────────────────────┘ + ↕ ↕ + Git Sync (shared/) Git Sync (shared/) + ↕ ↕ +┌────────────────────┐ ┌────────────────────┐ +│ US Region │ │ EU Region │ +│ Grafana │ │ Grafana │ +│ │ │ │ +│ Repository: │ │ Repository: │ +│ - path: shared/ │ │ - path: shared/ │ +└────────────────────┘ └────────────────────┘ +``` + +## Repository structure + +**In Git:** + +``` +your-org/grafana-manifests +└── shared/ + ├── dashboard-global.json + ├── dashboard-metrics.json + └── dashboard-logs.json +``` + +**In Grafana Dashboards view (all regions):** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── Global Dashboard + ├── Metrics Dashboard + └── Logs Dashboard +``` + +- All regional instances (US, EU, etc.) show identical folder structure +- Same folder name "grafana-manifests" in every region +- Same dashboards synced from the `shared/` path appear everywhere +- Users in any region see the exact same dashboards with the same titles + +## Configuration parameters + +All regions: + +- Repository: `your-org/grafana-manifests` +- Branch: `main` +- Path: `shared/` + +## How it works + +1. All regional instances pull dashboards from `shared/`. +2. Any region’s change commits to Git. +3. Other regions pull updates during the next sync (or via webhooks). +4. Changes propagate across regions per sync interval. + +## Considerations + +- **Write conflicts**: If users in different regions modify the same dashboard simultaneously, Git uses last-write-wins. +- **Primary region**: Consider designating one region as the primary location for making dashboard changes. +- **Propagation time**: Changes propagate to all regions within the configured sync interval, or instantly if webhooks are configured. +- **Network reliability**: Ensure all regions have reliable connectivity to the Git repository. diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-team.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-team.md new file mode 100644 index 00000000000..4f5ecc85fd2 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/multi-team.md @@ -0,0 +1,169 @@ +--- +title: Multiple team Git Sync +menuTitle: Shared instance +description: Use multiple Git repositories with one Grafana instance, one repository per team +weight: 60 +--- + +# Git Sync in a Grafana instance shared by multiple teams + +Use a single Grafana instance with multiple Repository resources, one per team. Each team manages its own dashboards while sharing Grafana. + +## Use it for + +- **Team autonomy**: Different teams manage their own dashboards independently. +- **Organizational structure**: Dashboard organization aligns with team structure. +- **Resource efficiency**: Multiple teams share Grafana infrastructure. +- **Cost optimization**: You reduce infrastructure costs while maintaining team separation. +- **Collaboration**: Teams can view each other’s dashboards while managing their own. + +## Architecture + +``` +┌─────────────────────────┐ ┌─────────────────────────┐ +│ Platform Team Repo │ │ Data Team Repo │ +│ platform-dashboards │ │ data-dashboards │ +│ │ │ │ +│ platform-dashboards/ │ │ data-dashboards/ │ +│ └── grafana/ │ │ └── grafana/ │ +│ ├── k8s.json │ │ ├── pipeline.json │ +│ └── infra.json │ │ └── analytics.json │ +└─────────────────────────┘ └─────────────────────────┘ + ↕ ↕ + Git Sync (grafana/) Git Sync (grafana/) + ↕ ↕ + ┌──────────────────────────────────────┐ + │ Grafana Instance │ + │ │ + │ Repository 1: │ + │ - repo: platform-dashboards │ + │ → Creates "platform-dashboards" │ + │ │ + │ Repository 2: │ + │ - repo: data-dashboards │ + │ → Creates "data-dashboards" │ + └──────────────────────────────────────┘ +``` + +## Repository structure + +**In Git (separate repositories):** + +**Platform team repository:** + +``` +your-org/platform-dashboards +└── grafana/ + ├── dashboard-k8s.json + └── dashboard-infra.json +``` + +**Data team repository:** + +``` +your-org/data-dashboards +└── grafana/ + ├── dashboard-pipeline.json + └── dashboard-analytics.json +``` + +**In Grafana Dashboards view:** + +``` +Dashboards +├── 📁 platform-dashboards/ +│ ├── Kubernetes Dashboard +│ └── Infrastructure Dashboard +└── 📁 data-dashboards/ + ├── Pipeline Dashboard + └── Analytics Dashboard +``` + +- Two separate folders created (one per Repository resource). +- Folder names derived from repository names. +- Each team has complete control over their own repository. +- Teams can independently manage permissions, branches, and workflows in their repos. +- All teams can view each other's dashboards in Grafana but manage only their own. + +## Configuration parameters + +**Platform team repository:** + +- **Repository**: `your-org/platform-dashboards` +- **Branch**: `main` +- **Path**: `grafana/` + +**Data team repository:** + +- **Repository**: `your-org/data-dashboards` +- **Branch**: `main` +- **Path**: `grafana/` + +## How it works + +1. Each team has their own Git repository for complete autonomy. +2. Each repository resource in Grafana creates a separate folder. +3. Platform team dashboards sync from `your-org/platform-dashboards` repository. +4. Data team dashboards sync from `your-org/data-dashboards` repository. +5. Teams can independently manage their repository settings, access controls, and workflows. +6. All teams can view each other's dashboards in Grafana but edit only their own. + +## Scale to more teams + +Adding additional teams is straightforward. For a third team, create a new repository and configure: + +- **Repository**: `your-org/security-dashboards` +- **Branch**: `main` +- **Path**: `grafana/` + +This creates a new "security-dashboards" folder in the same Grafana instance. + +## Alternative: Shared repository with different paths + +For teams that prefer sharing a single repository, use different paths to separate team dashboards: + +**In Git:** + +``` +your-org/grafana-manifests +├── team-platform/ +│ ├── dashboard-k8s.json +│ └── dashboard-infra.json +└── team-data/ + ├── dashboard-pipeline.json + └── dashboard-analytics.json +``` + +**Configuration:** + +**Platform team:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `team-platform/` + +**Data team:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `team-data/` + +This approach provides simpler repository management but less isolation between teams. + +## Alternative: Different branches per team + +For teams wanting their own branch in a shared repository: + +**Platform team:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `team-platform` +- **Path**: `grafana/` + +**Data team:** + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `team-data` +- **Path**: `grafana/` + +This allows teams to use Git branch workflows for collaboration while sharing the same repository. diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/single-instance.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/single-instance.md new file mode 100644 index 00000000000..39371f7e7d6 --- /dev/null +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios/single-instance.md @@ -0,0 +1,86 @@ +--- +title: Single instance Git Sync +menuTitle: Single instance +description: Synchronize a single Grafana instance with a Git repository +weight: 10 +--- + +# Single instance Git Sync + +Use a single Grafana instance synchronized with a Git repository. This is the foundation for Git Sync and helps you understand bidirectional synchronization. + +## Use it for + +- **Getting started**: You want to learn how Git Sync works before implementing complex scenarios. +- **Personal projects**: Individual developers manage their own dashboards. +- **Small teams**: You have a simple setup without multiple environments or complex workflows. +- **Development environments**: You need quick prototyping and testing. + +## Architecture + +``` +┌─────────────────────────────────────────────────────┐ +│ GitHub Repository │ +│ Repository: your-org/grafana-manifests │ +│ Branch: main │ +│ │ +│ grafana-manifests/ │ +│ └── grafana/ │ +│ ├── dashboard-1.json │ +│ ├── dashboard-2.json │ +│ └── dashboard-3.json │ +└─────────────────────────────────────────────────────┘ + ↕ + Git Sync (bidirectional) + ↕ + ┌─────────────────────────────┐ + │ Grafana Instance │ + │ │ + │ Repository Resource: │ + │ - url: grafana-manifests │ + │ - branch: main │ + │ - path: grafana/ │ + │ │ + │ Creates folder: │ + │ "grafana-manifests" │ + └─────────────────────────────┘ +``` + +## Repository structure + +**In Git:** + +``` +your-org/grafana-manifests +└── grafana/ + ├── dashboard-1.json + ├── dashboard-2.json + └── dashboard-3.json +``` + +**In Grafana Dashboards view:** + +``` +Dashboards +└── 📁 grafana-manifests/ + ├── Dashboard 1 + ├── Dashboard 2 + └── Dashboard 3 +``` + +- A folder named "grafana-manifests" (from repository name) contains all synced dashboards. +- Each JSON file becomes a dashboard with its title displayed in the folder. +- Users browse dashboards organized under this folder structure. + +## Configuration parameters + +Configure your Grafana instance to synchronize with: + +- **Repository**: `your-org/grafana-manifests` +- **Branch**: `main` +- **Path**: `grafana/` + +## How it works + +1. **From Grafana to Git**: When users create or modify dashboards in Grafana, Git Sync commits changes to the `grafana/` directory on the `main` branch. +2. **From Git to Grafana**: When dashboard JSON files are added or modified in the `grafana/` directory, Git Sync pulls these changes into Grafana. diff --git a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md index f6113fe428d..cd07c532dae 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/git-sync-setup.md @@ -29,76 +29,70 @@ You can sign up to the private preview using the [Git Sync early access form](ht {{< /admonition >}} -Git Sync lets you manage Grafana dashboards as code by storing dashboard JSON files and folders in a remote GitHub repository. - -To set up Git Sync and synchronize with a GitHub repository follow these steps: - -1. [Enable feature toggles in Grafana](#enable-required-feature-toggles) (first time set up). -1. [Create a GitHub access token](#create-a-github-access-token). -1. [Configure a connection to your GitHub repository](#set-up-the-connection-to-github). -1. [Choose what content to sync with Grafana](#choose-what-to-synchronize). - -Optionally, you can [extend Git Sync](#configure-webhooks-and-image-rendering) by enabling pull request notifications and image previews of dashboard changes. - -| Capability | Benefit | Requires | -| ----------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------- | -| Adds a table summarizing changes to your pull request | Provides a convenient way to save changes back to GitHub. | Webhooks configured | -| Add a dashboard preview image to a PR | View a snapshot of dashboard changes to a pull request without opening Grafana. | Image renderer and webhooks configured | - -{{< admonition type="note" >}} - -Alternatively, you can configure a local file system instead of using GitHub. Refer to [Set up file provisioning](https://grafana.com/docs/grafana//observability-as-code/provision-resources/file-path-setup/) for more information. - -{{< /admonition >}} - -## Performance impacts of enabling Git Sync - -Git Sync is an experimental feature and is under continuous development. Reporting any issues you encounter can help us improve Git Sync. - -When Git Sync is enabled, the database load might increase, especially for instances with a lot of folders and nested folders. Evaluate the performance impact, if any, in a non-production environment. +This guide shows you how to set up Git Sync to synchronize your Grafana dashboards and folders with a GitHub repository. You'll set up Git Sync to enable version-controlled dashboard management either [using the UI](#set-up-git-sync-using-grafana-ui) or [as code](#set-up-git-sync-as-code). ## Before you begin -{{< admonition type="caution" >}} +Before you begin, ensure you have the following: -Refer to [Known limitations](https://grafana.com/docs/grafana//observability-as-code/provision-resources/intro-git-sync#known-limitations/) before using Git Sync. +- A Grafana instance (Cloud, OSS, or Enterprise). +- If you're [using webhooks or image rendering](#extend-git-sync-for-real-time-notification-and-image-rendering), a public instance with external access +- Administration rights in your Grafana organization +- A [GitHub private access token](#create-a-github-access-token) +- A GitHub repository to store your dashboards in +- Optional: The [Image Renderer service](https://github.com/grafana/grafana-image-renderer) to save image previews with your PRs + +### Known limitations + +Refer to [Known limitations](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/intro-git-sync#known-limitations) before using Git Sync. + +Refer to [Supported resources](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/intro-git-sync#supported-resources) for details about which resources you can sync. + +### Performance considerations + +When Git Sync is enabled, the database load might increase, especially for instances with many folders and nested folders. Evaluate the performance impact, if any, in a non-production environment. + +Git Sync is under continuous development. [Report any issues](https://grafana.com/help/) you encounter to help us improve Git Sync. + +## Set up Git Sync + +To set up Git Sync and synchronize with a GitHub repository, follow these steps: + +1. [Enable feature toggles in Grafana](#enable-required-feature-toggles) (first time setup) +1. [Create a GitHub access token](#create-a-github-access-token) +1. Set up Git Sync [using the UI](#set-up-git-sync-using-grafana-ui) or [as code](#set-up-git-sync-as-code) + +After setup, you can [verify your dashboards](#verify-your-dashboards-in-grafana). + +Optionally, you can also [extend Git Sync with webhooks and image rendering](#extend-git-sync-for-real-time-notification-and-image-rendering). + +{{< admonition type="note" >}} + +Alternatively, you can configure a local file system instead of using GitHub. Refer to [Set up file provisioning](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/file-path-setup/) for more information. {{< /admonition >}} -### Requirements - -To set up Git Sync, you need: - -- Administration rights in your Grafana organization. -- Enable the required feature toggles in your Grafana instance. Refer to [Enable required feature toggles](#enable-required-feature-toggles) for instructions. -- A GitHub repository to store your dashboards in. - - If you want to use a local file path, refer to [the local file path guide](https://grafana.com/docs/grafana//observability-as-code/provision-resources/file-path-setup/). -- A GitHub access token. The Grafana UI will prompt you during setup. -- Optional: A public Grafana instance. -- Optional: The [Image Renderer service](https://github.com/grafana/grafana-image-renderer) to save image previews with your PRs. - ## Enable required feature toggles -To activate Git Sync in Grafana, you need to enable the `provisioning` and `kubernetesDashboards` feature toggles. -For additional information about feature toggles, refer to [Configure feature toggles](https://grafana.com/docs/grafana//setup-grafana/configure-grafana/feature-toggles). +To activate Git Sync in Grafana, you need to enable the `provisioning` feature toggle. For more information about feature toggles, refer to [Configure feature toggles](https://grafana.com/docs/grafana//setup-grafana/configure-grafana/feature-toggles/#experimental-feature-toggles). -To enable the required feature toggles, add them to your Grafana configuration file: +To enable the required feature toggle: 1. Open your Grafana configuration file, either `grafana.ini` or `custom.ini`. For file location based on operating system, refer to [Configuration file location](https://grafana.com/docs/grafana//setup-grafana/configure-grafana/feature-toggles/#experimental-feature-toggles). -1. Locate or add a `[feature_toggles]` section. Add these values: +1. Locate or add a `[feature_toggles]` section. Add this value: ```ini [feature_toggles] provisioning = true - kubernetesDashboards = true ; use k8s from browser ``` 1. Save the changes to the file and restart Grafana. ## Create a GitHub access token -Whenever you connect to a GitHub repository, you need to create a GitHub access token with specific repository permissions. -This token needs to be added to your Git Sync configuration to enable read and write permissions between Grafana and GitHub repository. +Whenever you connect to a GitHub repository, you need to create a GitHub access token with specific repository permissions. This token needs to be added to your Git Sync configuration to enable read and write permissions between Grafana and GitHub repository. + +To create a GitHub access token: 1. Create a new token using [Create new fine-grained personal access token](https://github.com/settings/personal-access-tokens/new). Refer to [Managing your personal access tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) for instructions. 1. Under **Permissions**, expand **Repository permissions**. @@ -112,19 +106,23 @@ This token needs to be added to your Git Sync configuration to enable read and w 1. Verify the options and select **Generate token**. 1. Copy the access token. Leave the browser window available with the token until you've completed configuration. -GitHub Apps are not currently supported. +GitHub Apps aren't currently supported. -## Set up the connection to GitHub +## Set up Git Sync using Grafana UI -Use **Provisioning** to guide you through setting up Git Sync to use a GitHub repository. +1. [Configure a connection to your GitHub repository](#set-up-the-connection-to-github) +1. [Choose what content to sync with Grafana](#choose-what-to-synchronize) +1. [Choose additional settings](#choose-additional-settings) + +### Set up the connection to GitHub + +Use **Provisioning** to guide you through setting up Git Sync to use a GitHub repository: 1. Log in to your Grafana server with an account that has the Grafana Admin flag set. 1. Select **Administration** in the left-side menu and then **Provisioning**. 1. Select **Configure Git Sync**. -### Connect to external storage - -To connect your GitHub repository, follow these steps: +To connect your GitHub repository: 1. Paste your GitHub personal access token into **Enter your access token**. Refer to [Create a GitHub access token](#create-a-github-access-token) for instructions. 1. Paste the **Repository URL** for your GitHub repository into the text box. @@ -134,32 +132,12 @@ To connect your GitHub repository, follow these steps: ### Choose what to synchronize -In this step you can decide which elements to synchronize. Keep in mind the available options depend on the status of your Grafana instance. +In this step, you can decide which elements to synchronize. The available options depend on the status of your Grafana instance: - If the instance contains resources in an incompatible data format, you'll have to migrate all the data using instance sync. Folder sync won't be supported. -- If there is already another connection using folder sync, instance sync won't be offered. +- If there's already another connection using folder sync, instance sync won't be offered. -#### Synchronization limitations - -Git Sync only supports dashboards and folders. Alerts, panels, and other resources are not supported yet. - -{{< admonition type="caution" >}} - -Refer to [Known limitations](https://grafana.com/docs/grafana//observability-as-code/provision-resources/intro-git-sync#known-limitations/) before using Git Sync. Refer to [Supported resources](/docs/grafana//observability-as-code/provision-resources/intro-git-sync#supported-resources) for details about which resources you can sync. - -{{< /admonition >}} - -Full instance sync is not available in Grafana Cloud. - -In Grafana OSS/Enterprise: - -- If you try to perform a full instance sync with resources that contain alerts or panels, Git Sync will block the connection. -- You won't be able to create new alerts or library panels after the setup is completed. -- If you opted for full instance sync and want to use alerts and library panels, you'll have to delete the synced repository and connect again with folder sync. - -#### Set up synchronization - -To set up synchronization, choose to either sync your entire organization resources with external storage, or to sync certain resources to a new Grafana folder (with up to 10 connections). +To set up synchronization: - Choose **Sync all resources with external storage** if you want to sync and manage your entire Grafana instance through external storage. With this option, all of your dashboards are synced to that one repository. You can only have one provisioned connection with this selection, and you won't have the option of setting up additional repositories to connect to. - Choose **Sync external storage to new Grafana folder** to sync external resources into a new folder without affecting the rest of your instance. You can repeat this process for up to 10 connections. @@ -170,20 +148,183 @@ Next, enter a **Display name** for the repository connection. Resources stored i Finally, you can set up how often your configured storage is polled for updates. +To configure additional settings: + 1. For **Update instance interval (seconds)**, enter how often you want the instance to pull updates from GitHub. The default value is 60 seconds. 1. Optional: Select **Read only** to ensure resources can't be modified in Grafana. -1. Optional: If you have the Grafana Image Renderer plugin configured, you can **Enable dashboards previews in pull requests**. If image rendering is not available, then you can't select this option. For more information, refer to the [Image Renderer service](https://github.com/grafana/grafana-image-renderer). +1. Optional: If you have the Grafana Image Renderer plugin configured, you can **Enable dashboards previews in pull requests**. If image rendering isn't available, then you can't select this option. For more information, refer to the [Image Renderer service](https://github.com/grafana/grafana-image-renderer). 1. Select **Finish** to proceed. +### Modify your configuration after setup is complete + +To update your repository configuration after you've completed setup: + +1. Log in to your Grafana server with an account that has the Grafana Admin flag set. +1. Select **Administration** in the left-side menu and then **Provisioning**. +1. Select **Settings** for the repository you wish to modify. +1. Use the **Configure repository** screen to update any of the settings. +1. Select **Save** to preserve the updates. + +## Set up Git Sync as code + +Alternatively, you can also configure Git Sync using `grafanactl`. Since Git Sync configuration is managed as code using Custom Resource Definitions (CRDs), you can create a Repository CRD in a YAML file and use `grafanactl` to push it to Grafana. This approach enables automated, GitOps-style workflows for managing Git Sync configuration instead of using the Grafana UI. + +To set up Git Sync with `grafanactl`, follow these steps: + +1. [Create the repository CRD](#create-the-repository-crd) +1. [Push the repository CRD to Grafana](#push-the-repository-crd-to-grafana) +1. [Manage repository resources](#manage-repository-resources) +1. [Verify setup](#verify-setup) + +For more information, refer to the following documents: + +- [grafanactl Documentation](https://grafana.github.io/grafanactl/) +- [Repository CRD Reference](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-setup/) +- [Dashboard CRD Format](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/export-resources/) + +### Create the repository CRD + +Create a `repository.yaml` file defining your Git Sync configuration: + +```yaml +apiVersion: provisioning.grafana.app/v0alpha1 +kind: Repository +metadata: + name: +spec: + title: + type: github + github: + url: + branch: + path: grafana/ + generateDashboardPreviews: true + sync: + enabled: true + intervalSeconds: 60 + target: folder + workflows: + - write + - branch +secure: + token: + create: +``` + +Replace the placeholders with your values: + +- _``_: Unique identifier for this repository resource +- _``_: Human-readable name displayed in Grafana UI +- _``_: GitHub repository URL +- _``_: Branch to sync +- _``_: GitHub Personal Access Token + +{{< admonition type="note" >}} + +Only `target: folder` is currently supported for Git Sync. + +{{< /admonition >}} + +#### Configuration parameters + +The following configuration parameters are available: + +| Field | Description | +| --------------------------------------- | ----------------------------------------------------------- | +| `metadata.name` | Unique identifier for this repository resource | +| `spec.title` | Human-readable name displayed in Grafana UI | +| `spec.type` | Repository type (`github`) | +| `spec.github.url` | GitHub repository URL | +| `spec.github.branch` | Branch to sync | +| `spec.github.path` | Directory path containing dashboards | +| `spec.github.generateDashboardPreviews` | Generate preview images (true/false) | +| `spec.sync.enabled` | Enable synchronization (true/false) | +| `spec.sync.intervalSeconds` | Sync interval in seconds | +| `spec.sync.target` | Where to place synced dashboards (`folder`) | +| `spec.workflows` | Enabled workflows: `write` (direct commits), `branch` (PRs) | +| `secure.token.create` | GitHub Personal Access Token | + +### Push the repository CRD to Grafana + +Before pushing any resources, configure `grafanactl` with your Grafana instance details. Refer to the [grafanactl configuration documentation](https://grafana.github.io/grafanactl/) for setup instructions. + +Push the repository configuration: + +```sh +grafanactl resources push --path +``` + +The `--path` parameter has to point to the directory containing your `repository.yaml` file. + +After pushing, Grafana will: + +1. Create the repository resource +1. Connect to your GitHub repository +1. Pull dashboards from the specified path +1. Begin syncing at the configured interval + +### Manage repository resources + +#### List repositories + +To list all repositories: + +```sh +grafanactl resources get repositories +``` + +#### Get repository details + +To get details for a specific repository: + +```sh +grafanactl resources get repository/ +grafanactl resources get repository/ -o json +grafanactl resources get repository/ -o yaml +``` + +#### Update the repository + +To update a repository: + +```sh +grafanactl resources edit repository/ +``` + +#### Delete the repository + +To delete a repository: + +```sh +grafanactl resources delete repository/ +``` + +### Verify setup + +Check that Git Sync is working: + +```sh +# List repositories +grafanactl resources get repositories + +# Check Grafana UI +# Navigate to: Administration → Provisioning → Git Sync +``` + ## Verify your dashboards in Grafana To verify that your dashboards are available at the location that you specified, click **Dashboards**. The name of the dashboard is listed in the **Name** column. -Now that your dashboards have been synced from a repository, you can customize the name, change the branch, and create a pull request (PR) for it. Refer to [Manage provisioned repositories with Git Sync](https://grafana.com/docs/grafana//observability-as-code/provision-resources/use-git-sync/) for more information. +Now that your dashboards have been synced from a repository, you can customize the name, change the branch, and create a pull request (PR) for it. Refer to [Manage provisioned repositories with Git Sync](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/use-git-sync/) for more information. -## Configure webhooks and image rendering +## Extend Git Sync for real-time notification and image rendering -You can extend Git Sync by getting instant updates and pull requests using webhooks and add dashboard previews in pull requests. +Optionally, you can extend Git Sync by enabling pull request notifications and image previews of dashboard changes. + +| Capability | Benefit | Requires | +| ----------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | +| Adds a table summarizing changes to your pull request | Provides a convenient way to save changes back to GitHub | Webhooks configured | +| Add a dashboard preview image to a PR | View a snapshot of dashboard changes to a pull request without opening Grafana | Image renderer and webhooks configured | ### Set up webhooks for realtime notification and pull request integration @@ -191,25 +332,26 @@ When connecting to a GitHub repository, Git Sync uses webhooks to enable real-ti You can set up webhooks with whichever service or tooling you prefer. You can use Cloudflare Tunnels with a Cloudflare-managed domain, port-forwarding and DNS options, or a tool such as `ngrok`. -To set up webhooks you need to expose your Grafana instance to the public Internet. You can do this via port forwarding and DNS, a tool such as `ngrok`, or any other method you prefer. The permissions set in your GitHub access token provide the authorization for this communication. +To set up webhooks, you need to expose your Grafana instance to the public Internet. You can do this via port forwarding and DNS, a tool such as `ngrok`, or any other method you prefer. The permissions set in your GitHub access token provide the authorization for this communication. After you have the public URL, you can add it to your Grafana configuration file: -```yaml +```ini [server] -root_url = https://PUBLIC_DOMAIN.HERE +root_url = https:// ``` +Replace _``_ with your public domain. + To check the configured webhooks, go to **Administration** > **Provisioning** and click the **View** link for your GitHub repository. #### Expose necessary paths only -If your security setup does not permit publicly exposing the Grafana instance, you can either choose to `allowlist` the GitHub IP addresses, or expose only the necessary paths. +If your security setup doesn't permit publicly exposing the Grafana instance, you can either choose to allowlist the GitHub IP addresses, or expose only the necessary paths. The necessary paths required to be exposed are, in RegExp: - `/apis/provisioning\.grafana\.app/v0(alpha1)?/namespaces/[^/]+/repositories/[^/]+/(webhook|render/.*)$` - ### Set up image rendering for dashboard previews @@ -217,12 +359,14 @@ Set up image rendering to add visual previews of dashboard updates directly in p To enable this capability, install the Grafana Image Renderer in your Grafana instance. For more information and installation instructions, refer to the [Image Renderer service](https://github.com/grafana/grafana-image-renderer). -## Modify configurations after set up is complete +## Next steps -To update your repository configuration after you've completed set up: +You've successfully set up Git Sync to manage your Grafana dashboards through version control. Your dashboards are now synchronized with a GitHub repository, enabling collaborative development and change tracking. -1. Log in to your Grafana server with an account that has the Grafana Admin flag set. -1. Select **Administration** in the left-side menu and then **Provisioning**. -1. Select **Settings** for the repository you wish to modify. -1. Use the **Configure repository** screen to update any of the settings. -1. Select **Save** to preserve the updates. +To learn more about using Git Sync: + +- [Work with provisioned dashboards](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/provisioned-dashboards/) +- [Manage provisioned repositories with Git Sync](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/use-git-sync/) +- [Git Sync deployment scenarios](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios) +- [Export resources](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/export-resources/) +- [grafanactl documentation](https://grafana.github.io/grafanactl/) diff --git a/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md b/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md index 4d9bda529a3..9e32ce32e8a 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/intro-git-sync.md @@ -127,7 +127,13 @@ An instance can be in one of the following Git Sync states: ## Common use cases -You can use Git Sync in the following scenarios. +{{< admonition type="note" >}} + +Refer to [Git Sync deployment scenarios](https://grafana.com/docs/grafana//as-code/observability-as-code/provision-resources/git-sync-deployment-scenarios) for sample scenarios, including architecture and configuration details. + +{{< /admonition >}} + +You can use Git Sync for the following use cases: ### Version control and auditing diff --git a/docs/sources/as-code/observability-as-code/provision-resources/use-git-sync.md b/docs/sources/as-code/observability-as-code/provision-resources/use-git-sync.md index f7d37d4b94e..11ce2aee0aa 100644 --- a/docs/sources/as-code/observability-as-code/provision-resources/use-git-sync.md +++ b/docs/sources/as-code/observability-as-code/provision-resources/use-git-sync.md @@ -14,7 +14,7 @@ labels: - cloud title: Manage provisioned repositories with Git Sync menuTitle: Manage repositories with Git Sync -weight: 120 +weight: 400 canonical: https://grafana.com/docs/grafana/latest/as-code/observability-as-code/provision-resources/use-git-sync/ aliases: - ../../../observability-as-code/provision-resources/use-git-sync/ # /docs/grafana/next/observability-as-code/provision-resources/use-git-sync/ diff --git a/docs/sources/as-code/observability-as-code/schema-v2/links-schema.md b/docs/sources/as-code/observability-as-code/schema-v2/links-schema.md index 9598477354f..0ddc50376de 100644 --- a/docs/sources/as-code/observability-as-code/schema-v2/links-schema.md +++ b/docs/sources/as-code/observability-as-code/schema-v2/links-schema.md @@ -62,5 +62,6 @@ The table includes default and other fields: | targetBlank | bool. If true, the link will be opened in a new tab. Default is `false`. | | includeVars | bool. If true, includes current template variables values in the link as query params. Default is `false`. | | keepTime | bool. If true, includes current time range in the link as query params. Default is `false`. | +| placement? | string. Use placement to display the link somewhere else on the dashboard other than above the visualizations. Use the `inControlsMenu` parameter to render the link in the dashboard controls dropdown menu. | diff --git a/docs/sources/datasources/azure-monitor/_index.md b/docs/sources/datasources/azure-monitor/_index.md index 90452f4cc52..d66b19efdff 100644 --- a/docs/sources/datasources/azure-monitor/_index.md +++ b/docs/sources/datasources/azure-monitor/_index.md @@ -3,7 +3,6 @@ aliases: - ../data-sources/azure-monitor/ - ../features/datasources/azuremonitor/ - azuremonitor/ - - azuremonitor/deprecated-application-insights/ description: Guide for using Azure Monitor in Grafana keywords: - grafana @@ -23,6 +22,7 @@ labels: menuTitle: Azure Monitor title: Azure Monitor data source weight: 300 +last_reviewed: 2025-12-04 refs: configure-grafana-feature-toggles: - pattern: /docs/grafana/ @@ -49,6 +49,11 @@ refs: destination: /docs/grafana//dashboards/build-dashboards/ - pattern: /docs/grafana-cloud/ destination: /docs/grafana//dashboards/build-dashboards/ + transform-data: + - pattern: /docs/grafana/ + destination: /docs/grafana//panels-visualizations/query-transform-data/transform-data/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//panels-visualizations/query-transform-data/transform-data/ configure-grafana-azure: - pattern: /docs/grafana/ destination: /docs/grafana//setup-grafana/configure-grafana/#azure @@ -63,295 +68,98 @@ refs: - pattern: /docs/grafana/ destination: /docs/grafana//setup-grafana/configure-access/configure-authentication/azuread/#enable-azure-ad-oauth-in-grafana - pattern: /docs/grafana-cloud/ - destination: /docs/grafana//setup-grafana/configure-access/configure-authentication/azuread/#enable-azure-ad-oauth-in-grafana + destination: /docs/grafana//setup-grafana/configure-security/configure-authentication/azuread/#enable-azure-ad-oauth-in-grafana + configure-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + query-editor-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + template-variables-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + alerting-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/alerting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/alerting/ + troubleshooting-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ + annotations-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/annotations/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/annotations/ --- # Azure Monitor data source -Grafana ships with built-in support for Azure Monitor, the Azure service to maximize the availability and performance of applications and services in the Azure Cloud. -This topic explains configuring and querying specific to the Azure Monitor data source. +The Azure Monitor data source plugin allows you to query and visualize data from Azure Monitor, the Azure service to maximize the availability and performance of applications and services in the Azure Cloud. -For instructions on how to add a data source to Grafana, refer to the [administration documentation](ref:data-source-management). -Only users with the organization administrator role can add data sources. +## Supported Azure clouds -Once you've added the Azure Monitor data source, you can [configure it](#configure-the-data-source) so that your Grafana instance's users can create queries in its [query editor](query-editor/) when they [build dashboards](ref:build-dashboards) and use [Explore](ref:explore). +The Azure Monitor data source supports the following Azure cloud environments: -The Azure Monitor data source supports visualizing data from four Azure services: +- **Azure** - Azure public cloud (default) +- **Azure US Government** - Azure Government cloud +- **Azure China** - Azure China cloud operated by 21Vianet -- **Azure Monitor Metrics:** Collect numeric data from resources in your Azure account. -- **Azure Monitor Logs:** Collect log and performance data from your Azure account, and query using the Kusto Query Language (KQL). -- **Azure Resource Graph:** Query your Azure resources across subscriptions. -- **Azure Monitor Application Insights:** Collect trace logging data and other application performance metrics. +## Supported Azure services -## Configure the data source +The Azure Monitor data source supports the following Azure services: -**To access the data source configuration page:** +| Service | Description | +| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| **Azure Monitor Metrics** | Collect numeric data from resources in your Azure account. Supports dimensions, aggregations, and time grain configuration. | +| **Azure Monitor Logs** | Collect log and performance data from your Azure account using the Kusto Query Language (KQL). | +| **Azure Resource Graph** | Query your Azure resources across subscriptions using KQL. Useful for inventory, compliance, and resource management. | +| **Application Insights Traces** | Collect distributed trace data and correlate requests across your application components. | -1. Click **Connections** in the left-side menu. -1. Under Your connections, click **Data sources**. -1. Enter `Azure Monitor` in the search bar. -1. Click **Azure Monitor**. +## Get started - The **Settings** tab of the data source is displayed. +The following documents will help you get started with the Azure Monitor data source: -### Configure Azure Active Directory (AD) authentication +- [Configure the Azure Monitor data source](ref:configure-azure-monitor) - Set up authentication and connect to Azure +- [Azure Monitor query editor](ref:query-editor-azure-monitor) - Create and edit queries for Metrics, Logs, Traces, and Resource Graph +- [Template variables](ref:template-variables-azure-monitor) - Create dynamic dashboards with Azure Monitor variables +- [Alerting](ref:alerting-azure-monitor) - Create alert rules using Azure Monitor data +- [Troubleshooting](ref:troubleshooting-azure-monitor) - Solve common configuration and query errors -You must create an app registration and service principal in Azure AD to authenticate the data source. -For configuration details, refer to the [Azure documentation for service principals](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#get-tenant-and-app-id-values-for-signing-in). +## Additional features -The app registration you create must have the `Reader` role assigned on the subscription. -For more information, refer to [Azure documentation for role assignments](https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?tabs=current). +After you have configured the Azure Monitor data source, you can: -If you host Grafana in Azure, such as in App Service or Azure Virtual Machines, you can configure the Azure Monitor data source to use Managed Identity for secure authentication without entering credentials into Grafana. -For details, refer to [Configuring using Managed Identity](#configuring-using-managed-identity). +- Add [Annotations](ref:annotations-azure-monitor) to overlay Azure log events on your graphs. +- Configure and use [Template variables](ref:template-variables-azure-monitor) for dynamic dashboards. +- Add [Transformations](ref:transform-data) to manipulate query results. +- Set up [Alerting](ref:alerting-azure-monitor) and recording rules using Metrics, Logs, Traces, and Resource Graph queries. +- Use [Explore](ref:explore) to investigate your Azure data without building a dashboard. -You can configure the Azure Monitor data source to use Workload Identity for secure authentication without entering credentials into Grafana if you host Grafana in a Kubernetes environment, such as AKS, and require access to Azure resources. -For details, refer to [Configuring using Workload Identity](#configuring-using-workload-identity). +## Pre-built dashboards -| Name | Description | -| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Authentication** | Enables Managed Identity. Selecting Managed Identity hides many of the other fields. For details, see [Configuring using Managed Identity](#configuring-using-managed-identity). | -| **Azure Cloud** | Sets the national cloud for your Azure account. For most users, this is the default "Azure". For details, see the [Azure documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/authentication-national-cloud). | -| **Directory (tenant) ID** | Sets the directory/tenant ID for the Azure AD app registration to use for authentication. For details, see the [Azure tenant and app ID docs](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#get-tenant-and-app-id-values-for-signing-in). | -| **Application (client) ID** | Sets the application/client ID for the Azure AD app registration to use for authentication. | -| **Client secret** | Sets the application client secret for the Azure AD app registration to use for authentication. For details, see the [Azure application secret docs](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret). | -| **Default subscription** | _(Optional)_ Sets a default subscription for template variables to use. | -| **Enable Basic Logs** | Allows this data source to execute queries against [Basic Logs tables](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/basic-logs-query?tabs=portal-1) in supported Log Analytics Workspaces. These queries may incur additional costs. | +The Azure Monitor plugin includes the following pre-built dashboards: -### Provision the data source +- **Azure Monitor Overview** - Displays key metrics across your Azure subscriptions and resources. +- **Azure Storage Account** - Shows storage account metrics including availability, latency, and transactions. -You can define and configure the data source in YAML files as part of Grafana's provisioning system. -For more information about provisioning, and for available configuration options, refer to [Provisioning Grafana](ref:provisioning-data-sources). +To import a pre-built dashboard: -#### Provisioning examples +1. Go to **Connections** > **Data sources**. +1. Select your Azure Monitor data source. +1. Click the **Dashboards** tab. +1. Click **Import** next to the dashboard you want to use. -**Azure AD App Registration (client secret):** +## Related resources -```yaml -apiVersion: 1 # config file version - -datasources: - - name: Azure Monitor - type: grafana-azure-monitor-datasource - access: proxy - jsonData: - azureAuthType: clientsecret - cloudName: azuremonitor # See table below - tenantId: - clientId: - subscriptionId: # Optional, default subscription - secureJsonData: - clientSecret: - version: 1 -``` - -**Managed Identity:** - -```yaml -apiVersion: 1 # config file version - -datasources: - - name: Azure Monitor - type: grafana-azure-monitor-datasource - access: proxy - jsonData: - azureAuthType: msi - subscriptionId: # Optional, default subscription - version: 1 -``` - -**Workload Identity:** - -```yaml -apiVersion: 1 # config file version - -datasources: - - name: Azure Monitor - type: grafana-azure-monitor-datasource - access: proxy - jsonData: - azureAuthType: workloadidentity - subscriptionId: # Optional, default subscription - version: 1 -``` - -**Current User:** - -{{< admonition type="note" >}} -The `oauthPassThru` property is required for current user authentication to function. -Additionally, `disableGrafanaCache` is necessary to prevent the data source returning cached responses for resources users don't have access to. -{{< /admonition >}} - -```yaml -apiVersion: 1 # config file version - -datasources: - - name: Azure Monitor - type: grafana-azure-monitor-datasource - access: proxy - jsonData: - azureAuthType: currentuser - oauthPassThru: true - disableGrafanaCache: true - subscriptionId: # Optional, default subscription - version: 1 -``` - -#### Supported cloud names - -| Azure Cloud | `cloudName` Value | -| ------------------------------------ | -------------------------- | -| **Microsoft Azure public cloud** | `azuremonitor` (_Default_) | -| **Microsoft Chinese national cloud** | `chinaazuremonitor` | -| **US Government cloud** | `govazuremonitor` | - -{{< admonition type="note" >}} -Cloud names for current user authentication differ to the `cloudName` values in the preceding table. -The public cloud name is `AzureCloud`, the Chinese national cloud name is `AzureChinaCloud`, and the US Government cloud name is `AzureUSGovernment`. -{{< /admonition >}} - -### Configure Managed Identity - -{{< admonition type="note" >}} -Managed Identity is available only in [Azure Managed Grafana](https://azure.microsoft.com/en-us/products/managed-grafana) or Grafana OSS/Enterprise when deployed in Azure. It is not available in Grafana Cloud. -{{< /admonition >}} - -You can use managed identity to configure Azure Monitor in Grafana if you host Grafana in Azure (such as an App Service or with Azure Virtual Machines) and have managed identity enabled on your VM. -This lets you securely authenticate data sources without manually configuring credentials via Azure AD App Registrations. -For details on Azure managed identities, refer to the [Azure documentation](https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview). - -**To enable managed identity for Grafana:** - -1. Set the `managed_identity_enabled` flag in the `[azure]` section of the [Grafana server configuration](ref:configure-grafana-azure). - - ```ini - [azure] - managed_identity_enabled = true - ``` - -2. In the Azure Monitor data source configuration, set **Authentication** to **Managed Identity**. - - This hides the directory ID, application ID, and client secret fields, and the data source uses managed identity to authenticate to Azure Monitor Metrics and Logs, and Azure Resource Graph. - - {{< figure src="/media/docs/grafana/data-sources/screenshot-managed-identity-2.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor screenshot showing Managed Identity authentication" >}} - -3. You can set the `managed_identity_client_id` field in the `[azure]` section of the [Grafana server configuration](ref:configure-grafana-azure) to allow a user-assigned managed identity to be used instead of the default system-assigned identity. - -```ini -[azure] -managed_identity_enabled = true -managed_identity_client_id = USER_ASSIGNED_IDENTITY_CLIENT_ID -``` - -### Configure Workload Identity - -You can use workload identity to configure Azure Monitor in Grafana if you host Grafana in a Kubernetes environment, such as AKS, in conjunction with managed identities. -This lets you securely authenticate data sources without manually configuring credentials via Azure AD App Registrations. -For details on workload identity, refer to the [Azure workload identity documentation](https://azure.github.io/azure-workload-identity/docs/). - -**To enable workload identity for Grafana:** - -1. Set the `workload_identity_enabled` flag in the `[azure]` section of the [Grafana server configuration](ref:configure-grafana-azure). - - ```ini - [azure] - workload_identity_enabled = true - ``` - -2. In the Azure Monitor data source configuration, set **Authentication** to **Workload Identity**. - - This hides the directory ID, application ID, and client secret fields, and the data source uses workload identity to authenticate to Azure Monitor Metrics and Logs, and Azure Resource Graph. - - {{< figure src="/media/docs/grafana/data-sources/screenshot-workload-identity.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor screenshot showing Workload Identity authentication" >}} - -3. There are additional configuration variables that can control the authentication method.`workload_identity_tenant_id` represents the Azure AD tenant that contains the managed identity, `workload_identity_client_id` represents the client ID of the managed identity if it differs from the default client ID, `workload_identity_token_file` represents the path to the token file. Refer to the [documentation](https://azure.github.io/azure-workload-identity/docs/) for more information on what values these variables should use, if any. - - ```ini - [azure] - workload_identity_enabled = true - workload_identity_tenant_id = IDENTITY_TENANT_ID - workload_identity_client_id = IDENTITY_CLIENT_ID - workload_identity_token_file = TOKEN_FILE_PATH - ``` - -### Configure Current User authentication - -{{< admonition type="note" >}} -Current user authentication is an [experimental feature](/docs/release-life-cycle). Engineering and on-call support is not available. Documentation is either limited or not provided outside of code comments. No SLA is provided. Contact Grafana Support to enable this feature in Grafana Cloud. Aspects of Grafana may not work as expected when using this authentication method. -{{< /admonition >}} - -If your Grafana instance is configured with Azure Entra (formerly Active Directory) authentication for login, this authentication method can be used to forward the currently logged in user's credentials to the data source. The users credentials will then be used when requesting data from the data source. For details on how to configure your Grafana instance using Azure Entra refer to the [documentation](ref:configure-grafana-azure-auth). - -{{< admonition type="note" >}} -Additional configuration is required to ensure that the App Registration used to login a user via Azure provides an access token with the permissions required by the data source. - -The App Registration must be configured to issue both **Access Tokens** and **ID Tokens**. - -1. In the Azure Portal, open the App Registration that requires configuration. -2. Select **Authentication** in the side menu. -3. Under **Implicit grant and hybrid flows** check both the **Access tokens** and **ID tokens** boxes. -4. Save the changes to ensure the App Registration is updated. - -The App Registration must also be configured with additional **API Permissions** to provide authenticated users with access to the APIs utilised by the data source. - -1. In the Azure Portal, open the App Registration that requires configuration. -1. Select **API Permissions** in the side menu. -1. Ensure the `openid`, `profile`, `email`, and `offline_access` permissions are present under the **Microsoft Graph** section. If not, they must be added. -1. Select **Add a permission** and choose the following permissions. They must be added individually. Refer to the [Azure documentation](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-configure-app-access-web-apis) for more information. - - Select **Azure Service Management** > **Delegated permissions** > `user_impersonation` > **Add permissions** - - Select **APIs my organization uses** > Search for **Log Analytics API** and select it > **Delegated permissions** > `Date.Read` > **Add permissions** - -Once all permissions have been added, the Azure authentication section in Grafana must be updated. The `scopes` section must be updated to include the `.default` scope to ensure that a token with access to all APIs declared on the App Registration is requested by Grafana. Once updated the scopes value should equal: `.default openid email profile`. -{{< /admonition >}} - -This method of authentication doesn't inherently support all backend functionality as a user's credentials won't be in scope. -Affected functionality includes alerting, reporting, and recorded queries. -In order to support backend queries when using a data source configured with current user authentication, you can configure service credentials. -Also, note that query and resource caching is disabled by default for data sources using current user authentication. - -{{< admonition type="note" >}} -To configure fallback service credentials the [feature toggle](ref:configure-grafana-feature-toggles) `idForwarding` must be set to `true` and `user_identity_fallback_credentials_enabled` must be enabled in the [Azure configuration section](ref:configure-grafana-azure) (enabled by default when `user_identity_enabled` is set to `true`). -{{< /admonition >}} - -Permissions for fallback credentials may need to be broad to appropriately support backend functionality. -For example, an alerting query created by a user is dependent on their permissions. -If a user tries to create an alert for a resource that the fallback credentials can't access, the alert will fail. - -**To enable current user authentication for Grafana:** - -1. Set the `user_identity_enabled` flag in the `[azure]` section of the [Grafana server configuration](ref:configure-grafana-azure). - By default this will also enable fallback service credentials. - If you want to disable service credentials at the instance level set `user_identity_fallback_credentials_enabled` to false. - - ```ini - [azure] - user_identity_enabled = true - ``` - -1. In the Azure Monitor data source configuration, set **Authentication** to **Current User**. - If fallback service credentials are enabled at the instance level, an additional configuration section is visible that you can use to enable or disable using service credentials for this data source. - {{< figure src="/media/docs/grafana/data-sources/screenshot-current-user.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor screenshot showing Current User authentication" >}} - -1. If you want backend functionality to work with this data source, enable service credentials and configure the data source using the most applicable credentials for your circumstances. - -## Query the data source - -The Azure Monitor data source can query data from Azure Monitor Metrics and Logs, the Azure Resource Graph, and Application Insights Traces. Each source has its own specialized query editor. - -For details, see the [query editor documentation](query-editor/). - -## Use template variables - -Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables. -Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard. -Grafana refers to such variables as template variables. - -For details, see the [template variables documentation](template-variables/). - -## Application Insights and Insights Analytics (removed) - -Until Grafana v8.0, you could query the same Azure Application Insights data using Application Insights and Insights Analytics. - -These queries were deprecated in Grafana v7.5. In Grafana v8.0, Application Insights and Insights Analytics were made read-only in favor of querying this data through Metrics and Logs. These query methods were completely removed in Grafana v9.0. - -If you're upgrading from a Grafana version prior to v9.0 and relied on Application Insights and Analytics queries, refer to the [Grafana v9.0 documentation](/docs/grafana/v9.0/datasources/azuremonitor/deprecated-application-insights/) for help migrating these queries to Metrics and Logs queries. +- [Azure Monitor documentation](https://docs.microsoft.com/en-us/azure/azure-monitor/) +- [Kusto Query Language (KQL) reference](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/) +- [Grafana community forum](https://community.grafana.com/) diff --git a/docs/sources/datasources/azure-monitor/alerting/index.md b/docs/sources/datasources/azure-monitor/alerting/index.md new file mode 100644 index 00000000000..860c1d343a4 --- /dev/null +++ b/docs/sources/datasources/azure-monitor/alerting/index.md @@ -0,0 +1,262 @@ +--- +aliases: + - ../../data-sources/azure-monitor/alerting/ +description: Set up alerts using Azure Monitor data in Grafana +keywords: + - grafana + - azure + - monitor + - alerting + - alerts + - metrics + - logs +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Alerting +title: Azure Monitor alerting +weight: 500 +refs: + alerting: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//alerting/ + alerting-fundamentals: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/fundamentals/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//alerting/fundamentals/ + create-alert-rule: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/alerting-rules/create-grafana-managed-rule/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//alerting/alerting-rules/create-grafana-managed-rule/ + grafana-managed-recording-rules: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/alerting-rules/create-recording-rules/create-grafana-managed-recording-rules/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//alerting/alerting-rules/create-recording-rules/create-grafana-managed-recording-rules/ + configure-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + query-editor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + troubleshoot: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ +--- + +# Azure Monitor alerting + +The Azure Monitor data source supports [Grafana Alerting](ref:alerting) and [Grafana-managed recording rules](ref:grafana-managed-recording-rules), allowing you to create alert rules based on Azure metrics, logs, traces, and resource data. You can monitor your Azure environment and receive notifications when specific conditions are met. + +## Before you begin + +- Ensure you have the appropriate permissions to create alert rules in Grafana. +- Verify your Azure Monitor data source is configured and working correctly. +- Familiarize yourself with [Grafana Alerting concepts](ref:alerting-fundamentals). +- **Important**: Verify your data source uses a supported authentication method. Refer to [Authentication requirements](#authentication-requirements). + +## Supported query types for alerting + +All Azure Monitor query types support alerting and recording rules: + +| Query type | Use case | Notes | +| -------------------- | -------------------------------------------------- | -------------------------------------------------------- | +| Metrics | Threshold-based alerts on Azure resource metrics | Best suited for alerting; returns time-series data | +| Logs | Alert on log patterns, error counts, or thresholds | Use KQL to aggregate data into numeric values | +| Azure Resource Graph | Alert on resource state or configuration changes | Use count aggregations to return numeric data | +| Traces | Alert on trace data and application performance | Use aggregations to return numeric values for evaluation | + +{{< admonition type="note" >}} +Alert queries must return numeric data that Grafana can evaluate against a threshold. Queries that return only text or non-numeric data cannot be used directly for alerting. +{{< /admonition >}} + +## Authentication requirements + +Alerting and recording rules run as background processes without a user context. This means they require service-level authentication and don't work with all authentication methods. + +| Authentication method | Supported | +| -------------------------------- | ------------------------------------- | +| App Registration (client secret) | ✓ | +| Managed Identity | ✓ | +| Workload Identity | ✓ | +| Current User | ✓ (with fallback service credentials) | + +{{< admonition type="note" >}} +If you use **Current User** authentication, you must configure **fallback service credentials** for alerting and recording rules to function. User credentials aren't available for background operations, so Grafana uses the fallback credentials instead. Refer to [configure the data source](ref:configure-azure-monitor) for details on setting up fallback credentials. +{{< /admonition >}} + +## Create an alert rule + +To create an alert rule using Azure Monitor data: + +1. Go to **Alerting** > **Alert rules**. +1. Click **New alert rule**. +1. Enter a name for your alert rule. +1. In the **Define query and alert condition** section: + - Select your Azure Monitor data source. + - Configure your query (for example, a Metrics query for CPU usage or a Logs query using KQL). + - Add a **Reduce** expression if your query returns multiple series. + - Add a **Threshold** expression to define the alert condition. +1. Configure the **Set evaluation behavior**: + - Select or create a folder and evaluation group. + - Set the evaluation interval (how often the alert is checked). + - Set the pending period (how long the condition must be true before firing). +1. Add labels and annotations to provide context for notifications. +1. Click **Save rule**. + +For detailed instructions, refer to [Create a Grafana-managed alert rule](ref:create-alert-rule). + +## Example: VM CPU usage alert + +This example creates an alert that fires when virtual machine CPU usage exceeds 80%: + +1. Create a new alert rule. +1. Configure the query: + - **Service**: Metrics + - **Resource**: Select your virtual machine + - **Metric namespace**: `Microsoft.Compute/virtualMachines` + - **Metric**: `Percentage CPU` + - **Aggregation**: `Average` +1. Add expressions: + - **Reduce**: Last (to get the most recent data point) + - **Threshold**: Is above 80 +1. Set evaluation to run every 1 minute with a 5-minute pending period. +1. Save the rule. + +## Example: Error log count alert + +This example alerts when error logs exceed a threshold using a KQL query: + +1. Create a new alert rule. +1. Configure the query: + - **Service**: Logs + - **Resource**: Select your Log Analytics workspace + - **Query**: + ```kusto + AppExceptions + | where TimeGenerated > ago(5m) + | summarize ErrorCount = count() by bin(TimeGenerated, 1m) + ``` +1. Add expressions: + - **Reduce**: Max (to get the highest count in the period) + - **Threshold**: Is above 10 +1. Set evaluation to run every 5 minutes. +1. Save the rule. + +## Example: Resource count alert + +This example alerts when the number of running virtual machines drops below a threshold using Azure Resource Graph: + +1. Create a new alert rule. +1. Configure the query: + - **Service**: Azure Resource Graph + - **Subscriptions**: Select your subscriptions + - **Query**: + + ```kusto + resources + | where type == "microsoft.compute/virtualmachines" + | where properties.extended.instanceView.powerState.displayStatus == "VM running" + | summarize RunningVMs = count() + ``` + +1. Add expressions: + - **Reduce**: Last + - **Threshold**: Is below 3 +1. Set evaluation to run every 5 minutes. +1. Save the rule. + +## Best practices + +Follow these recommendations to create reliable and efficient alerts with Azure Monitor data. + +### Use appropriate query intervals + +- Set the alert evaluation interval to be greater than or equal to the minimum data resolution from Azure Monitor. +- Azure Monitor Metrics typically have 1-minute granularity at minimum. +- Avoid very short intervals (less than 1 minute) as they may cause evaluation timeouts or miss data points. + +### Reduce multiple series + +When your Azure Monitor query returns multiple time series (for example, CPU usage across multiple VMs), use the **Reduce** expression to aggregate them: + +- **Last**: Use the most recent value +- **Mean**: Average across all series +- **Max/Min**: Use the highest or lowest value +- **Sum**: Total across all series + +### Optimize Log Analytics queries + +For Logs queries used in alerting: + +- Use `summarize` to aggregate data into numeric values. +- Include appropriate time filters using `ago()` or `TimeGenerated`. +- Avoid returning large result sets; aggregate data in the query. +- Test queries in Explore before using them in alert rules. + +### Handle no data conditions + +Configure what happens when no data is returned: + +1. In the alert rule, find **Configure no data and error handling**. +1. Choose an appropriate action: + - **No Data**: Keep the alert in its current state + - **Alerting**: Treat no data as an alert condition + - **OK**: Treat no data as a healthy state + +### Test queries before alerting + +Always verify your query returns expected data before creating an alert: + +1. Go to **Explore**. +1. Select your Azure Monitor data source. +1. Run the query you plan to use for alerting. +1. Confirm the data format and values are correct. +1. Verify the query returns numeric data suitable for threshold evaluation. + +## Troubleshooting + +If your Azure Monitor alerts aren't working as expected, use the following sections to diagnose and resolve common issues. + +### Alerts not firing + +- Verify the data source uses a supported authentication method. If using Current User authentication, ensure fallback service credentials are configured. +- Check that the query returns numeric data in Explore. +- Ensure the evaluation interval allows enough time for data to be available. +- Review the alert rule's health and any error messages in the Alerting UI. + +### Authentication errors in alert evaluation + +If you see authentication errors when alerts evaluate: + +- Confirm the data source is configured with App Registration, Managed Identity, Workload Identity, or Current User with fallback service credentials. +- If using App Registration, verify the client secret hasn't expired. +- If using Current User, verify that fallback service credentials are configured and valid. +- Check that the service principal has appropriate permissions on Azure resources. + +### Query timeout errors + +- Simplify complex KQL queries. +- Reduce the time range in Log Analytics queries. +- Add more specific filters to narrow result sets. + +For additional troubleshooting help, refer to [Troubleshoot Azure Monitor](ref:troubleshoot). + +## Additional resources + +- [Grafana Alerting documentation](ref:alerting) +- [Create alert rules](ref:create-alert-rule) +- [Azure Monitor query editor](ref:query-editor) +- [Grafana-managed recording rules](ref:grafana-managed-recording-rules) diff --git a/docs/sources/datasources/azure-monitor/annotations/index.md b/docs/sources/datasources/azure-monitor/annotations/index.md new file mode 100644 index 00000000000..43fbb914a9d --- /dev/null +++ b/docs/sources/datasources/azure-monitor/annotations/index.md @@ -0,0 +1,218 @@ +--- +aliases: + - ../../data-sources/azure-monitor/annotations/ +description: Use annotations with the Azure Monitor data source in Grafana +keywords: + - grafana + - azure + - monitor + - annotations + - events + - logs +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Annotations +title: Azure Monitor annotations +weight: 450 +refs: + annotate-visualizations: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/build-dashboards/annotate-visualizations/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//dashboards/build-dashboards/annotate-visualizations/ + query-editor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ +--- + +# Azure Monitor annotations + +[Annotations](ref:annotate-visualizations) overlay rich event information on top of graphs. You can use Azure Monitor Log Analytics queries to create annotations that mark important events, deployments, alerts, or other significant occurrences on your dashboards. + +## Before you begin + +- Ensure you have configured the Azure Monitor data source. +- You need access to a Log Analytics workspace containing the data you want to use for annotations. +- Annotations use Log Analytics (KQL) queries only. Metrics, Traces, and Azure Resource Graph queries are not supported for annotations. + +## Create an annotation query + +To add an Azure Monitor annotation to a dashboard: + +1. Open the dashboard where you want to add annotations. +1. Click **Dashboard settings** (gear icon) in the top navigation. +1. Select **Annotations** in the left menu. +1. Click **Add annotation query**. +1. Enter a **Name** for the annotation (e.g., "Azure Activity", "Deployments"). +1. Select your **Azure Monitor** data source. +1. Choose the **Logs** service. +1. Select a **Resource** (Log Analytics workspace or Application Insights resource). +1. Write a KQL query that returns the annotation data. +1. Click **Apply** to save. + +## Query requirements + +Your KQL query should return columns that Grafana can use to create annotations: + +| Column | Required | Description | +| ------------------ | ----------- | ------------------------------------------------------------------------------------------------ | +| `TimeGenerated` | Yes | The timestamp for the annotation. Grafana uses this to position the annotation on the time axis. | +| `Text` | Recommended | The annotation text displayed when you hover over or click the annotation. | +| Additional columns | Optional | Any other columns returned become annotation tags. | + +{{< admonition type="note" >}} +Always include a time filter in your query to limit results to the dashboard's time range. Use the `$__timeFilter()` macro. +{{< /admonition >}} + +## Annotation query examples + +The following examples demonstrate common annotation use cases. + +### Azure Activity Log events + +Display Azure Activity Log events such as resource modifications, deployments, and administrative actions: + +```kusto +AzureActivity +| where $__timeFilter(TimeGenerated) +| where Level == "Error" or Level == "Warning" or CategoryValue == "Administrative" +| project TimeGenerated, Text=OperationNameValue, Level, ResourceGroup, Caller +| order by TimeGenerated desc +| take 100 +``` + +### Deployment events + +Show deployment-related activity: + +```kusto +AzureActivity +| where $__timeFilter(TimeGenerated) +| where OperationNameValue contains "deployments" +| project TimeGenerated, Text=strcat("Deployment: ", OperationNameValue), Status=ActivityStatusValue, ResourceGroup +| order by TimeGenerated desc +``` + +### Application Insights exceptions + +Mark application exceptions as annotations: + +```kusto +AppExceptions +| where $__timeFilter(TimeGenerated) +| project TimeGenerated, Text=strcat(ProblemId, ": ", OuterMessage), SeverityLevel, AppRoleName +| order by TimeGenerated desc +| take 50 +``` + +### Custom events from Application Insights + +Display custom events logged by your application: + +```kusto +AppEvents +| where $__timeFilter(TimeGenerated) +| where Name == "DeploymentStarted" or Name == "DeploymentCompleted" +| project TimeGenerated, Text=Name, AppRoleName +| order by TimeGenerated desc +``` + +### Security alerts + +Show security-related alerts: + +```kusto +SecurityAlert +| where $__timeFilter(TimeGenerated) +| project TimeGenerated, Text=AlertName, Severity=AlertSeverity, Description +| order by TimeGenerated desc +| take 50 +``` + +### Resource health events + +Display resource health status changes: + +```kusto +AzureActivity +| where $__timeFilter(TimeGenerated) +| where CategoryValue == "ResourceHealth" +| project TimeGenerated, Text=OperationNameValue, Status=ActivityStatusValue, ResourceId +| order by TimeGenerated desc +``` + +### VM start and stop events + +Mark virtual machine state changes: + +```kusto +AzureActivity +| where $__timeFilter(TimeGenerated) +| where OperationNameValue has_any ("start", "deallocate", "restart") +| where ResourceProviderValue == "MICROSOFT.COMPUTE" +| project TimeGenerated, Text=OperationNameValue, VM=Resource, Status=ActivityStatusValue +| order by TimeGenerated desc +``` + +### Autoscale events + +Show autoscale operations: + +```kusto +AzureActivity +| where $__timeFilter(TimeGenerated) +| where OperationNameValue contains "autoscale" +| project TimeGenerated, Text=strcat("Autoscale: ", OperationNameValue), Status=ActivityStatusValue, ResourceGroup +| order by TimeGenerated desc +``` + +## Customize annotation appearance + +After creating an annotation query, you can customize its appearance: + +| Setting | Description | +| ------------- | -------------------------------------------------------------------------------------------------------- | +| **Color** | Choose a color for the annotation markers. Use different colors to distinguish between annotation types. | +| **Show in** | Select which panels display the annotations. | +| **Filter by** | Add filters to limit when annotations appear. | + +## Best practices + +Follow these recommendations when creating annotations: + +1. **Limit results**: Always use `take` or `limit` to restrict the number of annotations. Too many annotations can clutter your dashboard and impact performance. + +2. **Use time filters**: Include `$__timeFilter()` to ensure queries only return data within the dashboard's time range. + +3. **Create meaningful text**: Use `strcat()` or `project` to create descriptive annotation text that provides context at a glance. + +4. **Add relevant tags**: Include columns like `ResourceGroup`, `Severity`, or `Status` that become clickable tags for filtering. + +5. **Use descriptive names**: Name your annotations clearly (e.g., "Production Deployments", "Critical Alerts") so dashboard users understand what they represent. + +## Troubleshoot annotations + +If annotations aren't appearing as expected, try the following solutions. + +### Annotations don't appear + +- Verify the query returns data in the selected time range. +- Check that the query includes a `TimeGenerated` column. +- Test the query in the Azure Portal Log Analytics query editor. +- Ensure the annotation is enabled (toggle is on). + +### Too many annotations + +- Add more specific filters to your query. +- Use `take` to limit results. +- Narrow the time range. + +### Annotations appear at wrong times + +- Verify the `TimeGenerated` column contains the correct timestamp. +- Check your dashboard's timezone settings. diff --git a/docs/sources/datasources/azure-monitor/configure/index.md b/docs/sources/datasources/azure-monitor/configure/index.md new file mode 100644 index 00000000000..cef21b08744 --- /dev/null +++ b/docs/sources/datasources/azure-monitor/configure/index.md @@ -0,0 +1,605 @@ +--- +aliases: + - ../../data-sources/azure-monitor/configure/ +description: Guide for configuring the Azure Monitor data source in Grafana. +keywords: + - grafana + - microsoft + - azure + - monitor + - application + - insights + - log + - analytics + - guide +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Configure +title: Configure the Azure Monitor data source +weight: 200 +last_reviewed: 2025-12-04 +refs: + configure-grafana-feature-toggles: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-grafana/#feature_toggles + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-grafana/#feature_toggles + provisioning-data-sources: + - pattern: /docs/grafana/ + destination: /docs/grafana//administration/provisioning/#data-sources + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//administration/provisioning/#data-sources + explore: + - pattern: /docs/grafana/ + destination: /docs/grafana//explore/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//explore/ + configure-grafana-azure-auth: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-security/configure-authentication/azuread/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-security/configure-authentication/azuread/ + build-dashboards: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/build-dashboards/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//dashboards/build-dashboards/ + configure-grafana-azure: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-grafana/#azure + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-grafana/#azure + data-source-management: + - pattern: /docs/grafana/ + destination: /docs/grafana//administration/data-source-management/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//administration/data-source-management/ + configure-grafana-azure-auth-scopes: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-security/configure-authentication/azuread/#enable-azure-ad-oauth-in-grafana + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-security/configure-authentication/azuread/#enable-azure-ad-oauth-in-grafana + data-sources: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/ + private-data-source-connect: + - pattern: /docs/grafana/ + destination: docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/ + - pattern: /docs/grafana-cloud/ + destination: docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/ + configure-pdc: + - pattern: /docs/grafana/ + destination: /docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/configure-pdc/#configure-grafana-private-data-source-connect-pdc + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/configure-pdc/#configure-grafana-private-data-source-connect-pdc +--- + +# Configure the Azure Monitor data source + +This document explains how to configure the Azure Monitor data source and the available configuration options. +For general information about data sources, refer to [Grafana data sources](ref:data-sources) and [Data source management](ref:data-source-management). + +## Before you begin + +Before configuring the Azure Monitor data source, ensure you have the following: + +- **Grafana permissions:** You must have the `Organization administrator` role to configure data sources. + Organization administrators can also [configure the data source via YAML](#provision-the-data-source) with the Grafana provisioning system or [using Terraform](#configure-with-terraform). + +- **Azure prerequisites:** Depending on your chosen authentication method, you may need: + - A Microsoft Entra ID (formerly Azure AD) app registration with a service principal (for App Registration authentication) + - A Managed Identity enabled on your Azure VM or App Service (for Managed Identity authentication) + - Workload identity configured in your Kubernetes cluster (for Workload Identity authentication) + - Microsoft Entra ID authentication configured for Grafana login (for Current User authentication) + +{{< admonition type="note" >}} +**Grafana Cloud users:** Managed Identity and Workload Identity authentication methods are not available in Grafana Cloud because they require Grafana to run on your Azure infrastructure. Use **App Registration** authentication instead. +{{< /admonition >}} + +- **Azure RBAC permissions:** The identity used to authenticate must have the `Reader` role on the Azure subscription containing the resources you want to monitor. + For Log Analytics queries, the identity also needs appropriate permissions on the Log Analytics workspaces to be queried. + Refer to the [Azure documentation for role assignments](https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?tabs=current). + +{{< admonition type="note" >}} +The Azure Monitor data source plugin is built into Grafana. No additional installation is required. +{{< /admonition >}} + +## Add the data source + +To add the Azure Monitor data source: + +1. Click **Connections** in the left-side menu. +1. Click **Add new connection**. +1. Type `Azure Monitor` in the search bar. +1. Select **Azure Monitor**. +1. Click **Add new data source** in the upper right. + +You're taken to the **Settings** tab where you can configure the data source. + +## Choose an authentication method + +The Azure Monitor data source supports four authentication methods. Choose based on where Grafana is hosted and your security requirements: + +| Authentication method | Best for | Requirements | +| --------------------- | ------------------------------------------ | -------------------------------------------------------------- | +| **App Registration** | Any Grafana deployment | Microsoft Entra ID app registration with client secret | +| **Managed Identity** | Grafana hosted in Azure (VMs, App Service) | Managed identity enabled on the Azure resource | +| **Workload Identity** | Grafana in Kubernetes (AKS) | Workload identity federation configured | +| **Current User** | User-level access control | Microsoft Entra ID authentication configured for Grafana login | + +## Configure authentication + +Select one of the following authentication methods and complete the configuration. + +### App Registration + +Use a Microsoft Entra ID app registration (service principal) to authenticate. This method works with any Grafana deployment. + +#### App Registration prerequisites + +1. Create an app registration in Microsoft Entra ID. + Refer to the [Azure documentation for creating a service principal](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#get-tenant-and-app-id-values-for-signing-in). + +1. Create a client secret for the app registration. + Refer to the [Azure documentation for creating a client secret](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret). + +1. Assign the `Reader` role to the app registration on the subscription or resources you want to monitor. + Refer to the [Azure documentation for role assignments](https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?tabs=current). + +#### App Registration UI configuration + +| Setting | Description | +| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| **Authentication** | Select **App Registration**. | +| **Azure Cloud** | The Azure environment to connect to. Select **Azure** for the public cloud, or choose Azure Government or Azure China for national clouds. | +| **Directory (tenant) ID** | The GUID that identifies your Microsoft Entra ID tenant. | +| **Application (client) ID** | The GUID for the app registration you created. | +| **Client secret** | The secret key for the app registration. Keep this secure and rotate periodically. | +| **Default Subscription** | Click **Load Subscriptions** to populate available subscriptions, then select your default. | + +#### Provision App Registration with YAML + +```yaml +apiVersion: 1 + +datasources: + - name: Azure Monitor + type: grafana-azure-monitor-datasource + access: proxy + jsonData: + azureAuthType: clientsecret + cloudName: azuremonitor # See supported cloud names below + tenantId: + clientId: + subscriptionId: # Optional, default subscription + secureJsonData: + clientSecret: + version: 1 +``` + +### Managed Identity + +Use Azure Managed Identity for secure, credential-free authentication when Grafana is hosted in Azure. + +{{< admonition type="note" >}} +Managed Identity is available in [Azure Managed Grafana](https://azure.microsoft.com/en-us/products/managed-grafana) or self-hosted Grafana deployed in Azure. It is not available in Grafana Cloud. +{{< /admonition >}} + +#### Managed Identity prerequisites + +- Grafana must be hosted in Azure (App Service, Azure VMs, or Azure Managed Grafana). +- Managed identity must be enabled on the Azure resource hosting Grafana. +- The managed identity must have the `Reader` role on the subscription or resources you want to monitor. + +For details on Azure managed identities, refer to the [Azure documentation](https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview). + +#### Managed Identity Grafana server configuration + +Enable managed identity in the Grafana server configuration: + +```ini +[azure] +managed_identity_enabled = true +``` + +To use a user-assigned managed identity instead of the system-assigned identity, also set: + +```ini +[azure] +managed_identity_enabled = true +managed_identity_client_id = +``` + +Refer to [Grafana Azure configuration](ref:configure-grafana-azure) for more details. + +#### Managed Identity UI configuration + +| Setting | Description | +| ------------------------ | --------------------------------------------------------------------------------------------------- | +| **Authentication** | Select **Managed Identity**. The directory ID, application ID, and client secret fields are hidden. | +| **Default Subscription** | Click **Load Subscriptions** to populate available subscriptions, then select your default. | + +{{< figure src="/media/docs/grafana/data-sources/screenshot-managed-identity-2.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor data source configured with Managed Identity" >}} + +#### Provision Managed Identity with YAML + +```yaml +apiVersion: 1 + +datasources: + - name: Azure Monitor + type: grafana-azure-monitor-datasource + access: proxy + jsonData: + azureAuthType: msi + subscriptionId: # Optional, default subscription + version: 1 +``` + +### Workload Identity + +Use Azure Workload Identity for secure authentication in Kubernetes environments like AKS. + +#### Workload Identity prerequisites + +- Grafana must be running in a Kubernetes environment with workload identity federation configured. +- The workload identity must have the `Reader` role on the subscription or resources you want to monitor. + +For details, refer to the [Azure workload identity documentation](https://azure.github.io/azure-workload-identity/docs/). + +#### Workload Identity Grafana server configuration + +Enable workload identity in the Grafana server configuration: + +```ini +[azure] +workload_identity_enabled = true +``` + +Optional configuration variables: + +```ini +[azure] +workload_identity_enabled = true +workload_identity_tenant_id = # Microsoft Entra ID tenant containing the managed identity +workload_identity_client_id = # Client ID if different from default +workload_identity_token_file = # Path to the token file +``` + +Refer to [Grafana Azure configuration](ref:configure-grafana-azure) and the [Azure workload identity documentation](https://azure.github.io/azure-workload-identity/docs/) for more details. + +#### Workload Identity UI configuration + +| Setting | Description | +| ------------------------ | ---------------------------------------------------------------------------------------------------- | +| **Authentication** | Select **Workload Identity**. The directory ID, application ID, and client secret fields are hidden. | +| **Default Subscription** | Click **Load Subscriptions** to populate available subscriptions, then select your default. | + +{{< figure src="/media/docs/grafana/data-sources/screenshot-workload-identity.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor data source configured with Workload Identity" >}} + +#### Provision Workload Identity with YAML + +```yaml +apiVersion: 1 + +datasources: + - name: Azure Monitor + type: grafana-azure-monitor-datasource + access: proxy + jsonData: + azureAuthType: workloadidentity + subscriptionId: # Optional, default subscription + version: 1 +``` + +### Current User + +Forward the logged-in Grafana user's Azure credentials to the data source for user-level access control. + +{{< admonition type="warning" >}} +Current User authentication is an [experimental feature](/docs/release-life-cycle/). Engineering and on-call support is not available. Documentation is limited. No SLA is provided. Contact Grafana Support to enable this feature in Grafana Cloud. +{{< /admonition >}} + +#### Current User prerequisites + +Your Grafana instance must be configured with Microsoft Entra ID authentication. Refer to the [Microsoft Entra ID authentication documentation](ref:configure-grafana-azure-auth). + +#### Configure your Azure App Registration + +The App Registration used for Grafana login requires additional configuration: + +**Enable token issuance:** + +1. In the Azure Portal, open your App Registration. +1. Select **Authentication** in the side menu. +1. Under **Implicit grant and hybrid flows**, check both **Access tokens** and **ID tokens**. +1. Save your changes. + +**Add API permissions:** + +1. In the Azure Portal, open your App Registration. +1. Select **API Permissions** in the side menu. +1. Ensure these permissions are present under **Microsoft Graph**: `openid`, `profile`, `email`, and `offline_access`. +1. Add the following permissions: + - **Azure Service Management** > **Delegated permissions** > `user_impersonation` + - **APIs my organization uses** > Search for **Log Analytics API** > **Delegated permissions** > `Data.Read` + +Refer to the [Azure documentation](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-configure-app-access-web-apis) for more information. + +**Update Grafana scopes:** + +Update the `scopes` section in your Grafana Azure authentication configuration to include the `.default` scope: + +``` +.default openid email profile +``` + +#### Current User Grafana server configuration + +Enable current user authentication in the Grafana server configuration: + +```ini +[azure] +user_identity_enabled = true +``` + +By default, this also enables fallback service credentials. To disable fallback credentials at the instance level: + +```ini +[azure] +user_identity_enabled = true +user_identity_fallback_credentials_enabled = false +``` + +{{< admonition type="note" >}} +To use fallback service credentials, the [feature toggle](ref:configure-grafana-feature-toggles) `idForwarding` must be set to `true`. +{{< /admonition >}} + +#### Limitations and fallback credentials + +Current User authentication doesn't support backend functionality like alerting, reporting, and recorded queries because user credentials aren't available for background operations. + +To support these features, configure **fallback service credentials**. When enabled, Grafana uses the fallback credentials for backend operations. Note that operations using fallback credentials are limited to the permissions of those credentials, not the user's permissions. + +{{< admonition type="note" >}} +Query and resource caching is disabled by default for data sources using Current User authentication. +{{< /admonition >}} + +#### Current User UI configuration + +| Setting | Description | +| -------------------------------- | ------------------------------------------------------------------------------------------- | +| **Authentication** | Select **Current User**. | +| **Default Subscription** | Click **Load Subscriptions** to populate available subscriptions, then select your default. | +| **Fallback Service Credentials** | Enable and configure credentials for backend features like alerting. | + +{{< figure src="/media/docs/grafana/data-sources/screenshot-current-user.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor data source configured with Current User authentication" >}} + +#### Provision Current User with YAML + +{{< admonition type="note" >}} +The `oauthPassThru` property is required for Current User authentication. The `disableGrafanaCache` property prevents returning cached responses for resources users don't have access to. +{{< /admonition >}} + +```yaml +apiVersion: 1 + +datasources: + - name: Azure Monitor + type: grafana-azure-monitor-datasource + access: proxy + jsonData: + azureAuthType: currentuser + oauthPassThru: true + disableGrafanaCache: true + subscriptionId: # Optional, default subscription + version: 1 +``` + +## Additional configuration options + +These settings apply to all authentication methods. + +### General settings + +| Setting | Description | +| ----------- | ------------------------------------------------------------------------------- | +| **Name** | The data source name used in panels and queries. Example: `azure-monitor-prod`. | +| **Default** | Toggle to make this the default data source for new panels. | + +### Enable Basic Logs + +Toggle **Enable Basic Logs** to allow queries against [Basic Logs tables](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/basic-logs-query?tabs=portal-1) in supported Log Analytics Workspaces. + +{{< admonition type="note" >}} +Querying Basic Logs tables incurs additional costs on a per-query basis. +{{< /admonition >}} + +### Private data source connect (Grafana Cloud only) + +If you're using Grafana Cloud and need to connect to Azure resources in a private network, use Private Data Source Connect (PDC). + +1. Click the **Private data source connect** dropdown to select your PDC configuration. +1. Click **Manage private data source connect** to view your PDC connection details. + +For more information, refer to [Private data source connect](ref:private-data-source-connect) and [Configure PDC](ref:configure-pdc). + +## Supported cloud names + +When provisioning the data source, use the following `cloudName` values: + +| Azure Cloud | `cloudName` value | +| -------------------------------- | ------------------------ | +| Microsoft Azure public cloud | `azuremonitor` (default) | +| Microsoft Chinese national cloud | `chinaazuremonitor` | +| US Government cloud | `govazuremonitor` | + +{{< admonition type="note" >}} +For Current User authentication, the cloud names differ: use `AzureCloud` for public cloud, `AzureChinaCloud` for the Chinese national cloud, and `AzureUSGovernment` for the US Government cloud. +{{< /admonition >}} + +## Verify the connection + +After configuring the data source, click **Save & test**. A successful connection displays a message confirming that the credentials are valid and have access to the configured default subscription. + +If the test fails, verify: + +- Your credentials are correct (tenant ID, client ID, client secret) +- The identity has the required Azure RBAC permissions +- For Managed Identity or Workload Identity, that the Grafana server configuration is correct +- Network connectivity to Azure endpoints + +## Provision the data source + +You can define and configure the Azure Monitor data source in YAML files as part of the Grafana provisioning system. +For more information about provisioning, refer to [Provisioning Grafana](ref:provisioning-data-sources). + +### Provision quick reference + +| Authentication method | `azureAuthType` value | Required fields | +| --------------------- | --------------------- | -------------------------------------------------- | +| App Registration | `clientsecret` | `tenantId`, `clientId`, `clientSecret` | +| Managed Identity | `msi` | None (uses VM identity) | +| Workload Identity | `workloadidentity` | None (uses pod identity) | +| Current User | `currentuser` | `oauthPassThru: true`, `disableGrafanaCache: true` | + +All methods support the optional `subscriptionId` field to set a default subscription. + +For complete YAML examples, see the [authentication method sections](#configure-authentication) above. + +## Configure with Terraform + +You can configure the Azure Monitor data source using the [Grafana Terraform provider](https://registry.terraform.io/providers/grafana/grafana/latest/docs). This approach enables infrastructure-as-code workflows and version control for your Grafana configuration. + +### Terraform prerequisites + +- [Terraform](https://www.terraform.io/downloads) installed +- Grafana Terraform provider configured with appropriate credentials +- For Grafana Cloud: A [Cloud Access Policy token](https://grafana.com/docs/grafana-cloud/account-management/authentication-and-permissions/access-policies/) with data source permissions + +### Provider configuration + +Configure the Grafana provider to connect to your Grafana instance: + +```hcl +terraform { + required_providers { + grafana = { + source = "grafana/grafana" + version = ">= 2.0.0" + } + } +} + +# For Grafana Cloud +provider "grafana" { + url = "" + auth = "" +} + +# For self-hosted Grafana +# provider "grafana" { +# url = "http://localhost:3000" +# auth = "" +# } +``` + +### Terraform examples + +The following examples show how to configure the Azure Monitor data source for each authentication method. + +**App Registration (client secret):** + +```hcl +resource "grafana_data_source" "azure_monitor" { + type = "grafana-azure-monitor-datasource" + name = "Azure Monitor" + + json_data_encoded = jsonencode({ + azureAuthType = "clientsecret" + cloudName = "azuremonitor" + tenantId = "" + clientId = "" + subscriptionId = "" + }) + + secure_json_data_encoded = jsonencode({ + clientSecret = "" + }) +} +``` + +**Managed Identity:** + +```hcl +resource "grafana_data_source" "azure_monitor" { + type = "grafana-azure-monitor-datasource" + name = "Azure Monitor" + + json_data_encoded = jsonencode({ + azureAuthType = "msi" + subscriptionId = "" + }) +} +``` + +**Workload Identity:** + +```hcl +resource "grafana_data_source" "azure_monitor" { + type = "grafana-azure-monitor-datasource" + name = "Azure Monitor" + + json_data_encoded = jsonencode({ + azureAuthType = "workloadidentity" + subscriptionId = "" + }) +} +``` + +**Current User:** + +```hcl +resource "grafana_data_source" "azure_monitor" { + type = "grafana-azure-monitor-datasource" + name = "Azure Monitor" + + json_data_encoded = jsonencode({ + azureAuthType = "currentuser" + oauthPassThru = true + disableGrafanaCache = true + subscriptionId = "" + }) +} +``` + +**With Basic Logs enabled:** + +Add `enableBasicLogs = true` to any of the above configurations: + +```hcl +resource "grafana_data_source" "azure_monitor" { + type = "grafana-azure-monitor-datasource" + name = "Azure Monitor" + + json_data_encoded = jsonencode({ + azureAuthType = "clientsecret" + cloudName = "azuremonitor" + tenantId = "" + clientId = "" + subscriptionId = "" + enableBasicLogs = true + }) + + secure_json_data_encoded = jsonencode({ + clientSecret = "" + }) +} +``` + +For more information about the Grafana Terraform provider, refer to the [provider documentation](https://registry.terraform.io/providers/grafana/grafana/latest/docs) and the [grafana_data_source resource](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/data_source). diff --git a/docs/sources/datasources/azure-monitor/query-editor/index.md b/docs/sources/datasources/azure-monitor/query-editor/index.md index 6415be1281c..a8c763d9280 100644 --- a/docs/sources/datasources/azure-monitor/query-editor/index.md +++ b/docs/sources/datasources/azure-monitor/query-editor/index.md @@ -21,6 +21,7 @@ labels: menuTitle: Query editor title: Azure Monitor query editor weight: 300 +last_reviewed: 2025-12-04 refs: query-transform-data-query-options: - pattern: /docs/grafana/ @@ -32,30 +33,85 @@ refs: destination: /docs/grafana//panels-visualizations/query-transform-data/ - pattern: /docs/grafana-cloud/ destination: /docs/grafana//panels-visualizations/query-transform-data/ + configure-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + explore: + - pattern: /docs/grafana/ + destination: /docs/grafana//explore/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//explore/ + troubleshoot-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/troubleshooting/ + configure-grafana-feature-toggles: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-grafana/feature-toggles/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-grafana/feature-toggles/ + template-variables: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + alerting-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/alerting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/alerting/ + annotations-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/annotations/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/annotations/ --- # Azure Monitor query editor -This topic explains querying specific to the Azure Monitor data source. -For general documentation on querying data sources in Grafana, see [Query and transform data](ref:query-transform-data). +Grafana provides a query editor for the Azure Monitor data source, which is located on the [Explore page](ref:explore). You can also access the Azure Monitor query editor from a dashboard panel. Click the menu in the upper right of the panel and select **Edit**. -## Choose a query editing mode +This document explains querying specific to the Azure Monitor data source. +For general documentation on querying data sources in Grafana, refer to [Query and transform data](ref:query-transform-data). -The Azure Monitor data source's query editor has three modes depending on which Azure service you want to query: +The Azure Monitor data source can query data from Azure Monitor Metrics and Logs, the Azure Resource Graph, and Application Insights Traces. Each source has its own specialized query editor. + +## Before you begin + +- Ensure you have [configured the Azure Monitor data source](ref:configure-azure-monitor). +- Verify your credentials have appropriate permissions for the resources you want to query. + +## Key concepts + +If you're new to Azure Monitor, here are some key terms used throughout this documentation: + +| Term | Description | +| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **KQL (Kusto Query Language)** | The query language used for Azure Monitor Logs and Azure Resource Graph. KQL uses a pipe-based syntax similar to Unix commands and is optimized for read-only data exploration. If you know SQL, the [SQL to Kusto cheat sheet](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/sqlcheatsheet) can help you get started. | +| **Log Analytics workspace** | An Azure resource that collects and stores log data from your Azure resources, applications, and services. You query this data using KQL. | +| **Application Insights** | Azure's application performance monitoring (APM) service. It collects telemetry data like requests, exceptions, and traces from your applications. | +| **Metrics vs. Logs** | **Metrics** are lightweight numeric values collected at regular intervals (e.g., CPU percentage). **Logs** are detailed records of events with varying schemas (e.g., request logs, error messages). Metrics use a visual query builder; Logs require KQL. | + +## Choose a query editor mode + +The Azure Monitor data source's query editor has four modes depending on which Azure service you want to query: - **Metrics** for [Azure Monitor Metrics](#query-azure-monitor-metrics) - **Logs** for [Azure Monitor Logs](#query-azure-monitor-logs) -- [**Azure Resource Graph**](#query-azure-resource-graph) - **Traces** for [Application Insights Traces](#query-application-insights-traces) +- **Azure Resource Graph** for [Azure Resource Graph](#query-azure-resource-graph) ## Query Azure Monitor Metrics -Azure Monitor Metrics collects numeric data from [supported resources](https://docs.microsoft.com/en-us/azure/azure-monitor/monitor-reference), and you can query them to investigate your resources' health and usage and maximise availability and performance. +Azure Monitor Metrics collects numeric data from [supported resources](https://docs.microsoft.com/en-us/azure/azure-monitor/monitor-reference), and you can query them to investigate your resources' health and usage and maximize availability and performance. Monitor Metrics use a lightweight format that stores only numeric data in a specific structure and supports near real-time scenarios, making it useful for fast detection of issues. In contrast, Azure Monitor Logs can store a variety of data types, each with their own structure. -{{< figure src="/static/img/docs/azure-monitor/query-editor-metrics.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Logs Metrics sample query visualizing CPU percentage over time" >}} +{{< figure src="/static/img/docs/azure-monitor/query-editor-metrics.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor Metrics sample query visualizing CPU percentage over time" >}} ### Create a Metrics query @@ -85,7 +141,7 @@ Optionally, you can apply further aggregations or filter by dimensions. The available options change depending on what is relevant to the selected metric. -You can also augment queries by using [template variables](../template-variables/). +You can also augment queries by using [template variables](ref:template-variables). ### Format legend aliases @@ -109,7 +165,7 @@ For example: | `{{ dimensionname }}` | _(Legacy for backward compatibility)_ Replaced with the name of the first dimension. | | `{{ dimensionvalue }}` | _(Legacy for backward compatibility)_ Replaced with the value of the first dimension. | -### Filter using dimensions +### Filter with dimensions Some metrics also have dimensions, which associate additional metadata. Dimensions are represented as key-value pairs assigned to each value of a metric. @@ -121,7 +177,7 @@ For more information on multi-dimensional metrics, refer to the [Azure Monitor d ## Query Azure Monitor Logs -Azure Monitor Logs collects and organises log and performance data from [supported resources](https://docs.microsoft.com/en-us/azure/azure-monitor/monitor-reference), and makes many sources of data available to query together with the [Kusto Query Language (KQL)](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/). +Azure Monitor Logs collects and organizes log and performance data from [supported resources](https://docs.microsoft.com/en-us/azure/azure-monitor/monitor-reference), and makes many sources of data available to query together with the [Kusto Query Language (KQL)](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/). While Azure Monitor Metrics stores only simplified numerical data, Logs can store different data types, each with their own structure. You can also perform complex analysis of Logs data by using KQL. @@ -130,6 +186,32 @@ The Azure Monitor data source also supports querying of [Basic Logs](https://lea {{< figure src="/static/img/docs/azure-monitor/query-editor-logs.png" max-width="800px" class="docs-image--no-shadow" caption="Azure Monitor Logs sample query comparing successful requests to failed requests" >}} +### Logs query builder (public preview) + +{{< admonition type="note" >}} +The Logs query builder is a [public preview feature](/docs/release-life-cycle/). It may not be enabled in all Grafana environments. +{{< /admonition >}} + +The Logs query builder provides a visual interface for building Azure Monitor Logs queries without writing KQL. This is helpful if you're new to KQL or want to quickly build simple queries. + +**To enable the Logs query builder:** + +1. Enable the `azureMonitorLogsBuilderEditor` [feature toggle](ref:configure-grafana-feature-toggles) in your Grafana configuration. +1. Restart Grafana for the change to take effect. + +**To switch between Builder and Code modes:** + +When the feature is enabled, a **Builder / Code** toggle appears in the Logs query editor: + +- **Builder**: Use the visual interface to select tables, columns, filters, and aggregations. The builder generates the KQL query for you. +- **Code**: Write KQL queries directly. Use this mode for complex queries that require full KQL capabilities. + +New queries default to Builder mode. Existing queries that were created with raw KQL remain in Code mode. + +{{< admonition type="note" >}} +You can switch from Builder to Code mode at any time to view or edit the generated KQL. However, switching from Code to Builder mode may not preserve complex queries that can't be represented in the builder interface. +{{< /admonition >}} + ### Create a Logs query **To create a Logs query:** @@ -140,13 +222,13 @@ The Azure Monitor data source also supports querying of [Basic Logs](https://lea Alternatively, you can dynamically query all resources under a single resource group or subscription. {{< admonition type="note" >}} - If a timespan is specified in the query, the overlap of the timespan between the query and the dashboard will be used as the query timespan. See the [API documentation for + If a time span is specified in the query, the overlap between the query time span and the dashboard time range will be used. See the [API documentation for details.](https://learn.microsoft.com/en-us/rest/api/loganalytics/dataaccess/query/get?tabs=HTTP#uri-parameters) {{< /admonition >}} 1. Enter your KQL query. -You can also augment queries by using [template variables](../template-variables/). +You can also augment queries by using [template variables](ref:template-variables). **To create a Basic Logs query:** @@ -161,7 +243,7 @@ You can also augment queries by using [template variables](../template-variables {{< /admonition >}} 1. Enter your KQL query. -You can also augment queries by using [template variables](https://grafana.com/docs/grafana//datasources/azure-monitor/template-variables/). +You can also augment queries by using [template variables](ref:template-variables). ### Logs query examples @@ -174,24 +256,28 @@ The Azure documentation includes resources to help you learn KQL: - [Tutorial: Use Kusto queries in Azure Monitor](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/tutorial?pivots=azuremonitor) - [SQL to Kusto cheat sheet](https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/sqlcheatsheet) -> **Time-range:** The time-range that will be used for the query can be modified via the time-range switch. Selecting `Query` will only make use of time-ranges specified within the query. -> Specifying `Dashboard` will only make use of the Grafana time-range. -> If there are no time-ranges specified within the query, the default Log Analytics time-range will apply. -> For more details on this change, refer to the [Azure Monitor Logs API documentation](https://learn.microsoft.com/en-us/rest/api/loganalytics/dataaccess/query/get?tabs=HTTP#uri-parameters). -> If the `Intersection` option was previously chosen it will be migrated by default to `Dashboard`. +{{< admonition type="note" >}} +**Time-range:** The time-range used for the query can be modified via the time-range switch: -This example query returns a virtual machine's CPU performance, averaged over 5ms time grains: +- Selecting **Query** uses only time-ranges specified within the query. +- Selecting **Dashboard** uses only the Grafana dashboard time-range. +- If no time-range is specified in the query, the default Log Analytics time-range applies. + +For more details, refer to the [Azure Monitor Logs API documentation](https://learn.microsoft.com/en-us/rest/api/loganalytics/dataaccess/query/get?tabs=HTTP#uri-parameters). If you previously used the `Intersection` option, it has been migrated to `Dashboard`. +{{< /admonition >}} + +This example query returns a virtual machine's CPU performance, averaged over 5-minute time grains: ```kusto Perf -# $__timeFilter is a special Grafana macro that filters the results to the time span of the dashboard +// $__timeFilter is a special Grafana macro that filters the results to the time span of the dashboard | where $__timeFilter(TimeGenerated) | where CounterName == "% Processor Time" | summarize avg(CounterValue) by bin(TimeGenerated, 5m), Computer | order by TimeGenerated asc ``` -Use time series queries for values that change over time, usually for graph visualisations such as the Time series panel. +Use time series queries for values that change over time, usually for graph visualizations such as the Time series panel. Each query should return at least a datetime column and numeric value column. The result must also be sorted in ascending order by the datetime column. @@ -357,21 +443,33 @@ Application Insights stores trace data in an underlying Log Analytics workspace This query type only supports Application Insights resources. {{< /admonition >}} -Running a query of this kind will return all trace data within the timespan specified by the panel/dashboard. +1. (Optional) Specify an **Operation ID** value to filter traces. +1. (Optional) Specify **event types** to filter by. +1. (Optional) Specify **event properties** to filter by. +1. (Optional) Change the **Result format** to switch between tabular format and trace format. -Optionally, you can apply further filtering or select a specific Operation ID to query. The result format can also be switched between a tabular format or the trace format which will return the data in a format that can be used with the Trace visualization. + {{< admonition type="note" >}} + Selecting the trace format filters events to only the `trace` type. Use this format with the Trace visualization. + {{< /admonition >}} -{{< admonition type="note" >}} -Selecting the trace format will filter events with the `trace` type. -{{< /admonition >}} +Running a query returns all trace data within the time span specified by the panel or dashboard time range. -1. Specify an Operation ID value. -1. Specify event types to filter by. -1. Specify event properties to filter by. +You can also augment queries by using [template variables](ref:template-variables). -You can also augment queries by using [template variables](../template-variables/). +## Use queries for alerting and recording rules -## Working with large Azure resource data sets +All Azure Monitor query types (Metrics, Logs, Azure Resource Graph, and Traces) can be used with Grafana Alerting and recording rules. + +For detailed information about creating alert rules, supported query types, authentication requirements, and examples, refer to [Azure Monitor alerting](ref:alerting-azure-monitor). + +## Work with large Azure resource datasets If a request exceeds the [maximum allowed value of records](https://docs.microsoft.com/en-us/azure/governance/resource-graph/concepts/work-with-data#paging-results), the result is paginated and only the first page of results are returned. You can use filters to reduce the amount of records returned under that value. + +## Next steps + +- [Use template variables](../template-variables/) to create dynamic, reusable dashboards +- [Add annotations](ref:annotations-azure-monitor) to overlay events on your graphs +- [Set up alerting](ref:alerting-azure-monitor) to create alert rules based on Azure Monitor data +- [Troubleshoot](ref:troubleshoot-azure-monitor) common query and configuration issues diff --git a/docs/sources/datasources/azure-monitor/template-variables/index.md b/docs/sources/datasources/azure-monitor/template-variables/index.md index 1db472a4251..3cedadef9b5 100644 --- a/docs/sources/datasources/azure-monitor/template-variables/index.md +++ b/docs/sources/datasources/azure-monitor/template-variables/index.md @@ -23,6 +23,7 @@ labels: menuTitle: Template variables title: Azure Monitor template variables weight: 400 +last_reviewed: 2025-12-04 refs: variables: - pattern: /docs/grafana/ @@ -34,6 +35,11 @@ refs: destination: /docs/grafana//dashboards/variables/add-template-variables/ - pattern: /docs/grafana-cloud/ destination: /docs/grafana//dashboards/variables/add-template-variables/ + configure-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/configure/ --- # Azure Monitor template variables @@ -42,58 +48,173 @@ Instead of hard-coding details such as resource group or resource name values in This helps you create more interactive, dynamic, and reusable dashboards. Grafana refers to such variables as template variables. -For an introduction to templating and template variables, refer to the [Templating](ref:variables) and [Add and manage variables](ref:add-template-variables) documentation. +For an introduction to templating and template variables, refer to the [Templating](ref:variables) and [Add and manage variables](ref:add-template-variables). -## Use query variables +## Before you begin -You can specify these Azure Monitor data source queries in the Variable edit view's **Query Type** field. +- Ensure you have [configured the Azure Monitor data source](ref:configure-azure-monitor). +- If you want template variables to auto-populate subscriptions, set a **Default Subscription** in the data source configuration. -| Name | Description | -| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| **Subscriptions** | Returns subscriptions. | -| **Resource Groups** | Returns resource groups for a specified subscription. Supports multi-value. | -| **Namespaces** | Returns metric namespaces for the specified subscription. If a resource group is provided, only the namespaces within that group are returned. | -| **Regions** | Returns regions for the specified subscription | -| **Resource Names** | Returns a list of resource names for a specified subscription, resource group and namespace. Supports multi-value. | -| **Metric Names** | Returns a list of metric names for a resource. | -| **Workspaces** | Returns a list of workspaces for the specified subscription. | -| **Logs** | Use a KQL query to return values. | -| **Custom Namespaces** | Returns metric namespaces for the specified resource. | -| **Custom Metric Names** | Returns a list of custom metric names for the specified resource. | +## Create a template variable + +To create a template variable for Azure Monitor: + +1. Open the dashboard where you want to add the variable. +1. Click **Dashboard settings** (gear icon) in the top navigation. +1. Select **Variables** in the left menu. +1. Click **Add variable**. +1. Enter a **Name** for your variable (e.g., `subscription`, `resourceGroup`, `resource`). +1. In the **Type** dropdown, select **Query**. +1. In the **Data source** dropdown, select your Azure Monitor data source. +1. In the **Query Type** dropdown, select the appropriate query type (see [Available query types](#available-query-types)). +1. Configure any additional fields required by the selected query type. +1. Click **Run query** to preview the variable values. +1. Configure display options such as **Multi-value** or **Include All option** as needed. +1. Click **Apply** to save the variable. + +## Available query types + +The Azure Monitor data source provides the following query types for template variables: + +| Query type | Description | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| **Subscriptions** | Returns a list of Azure subscriptions accessible to the configured credentials. | +| **Resource Groups** | Returns resource groups for a specified subscription. Supports multi-value selection. | +| **Namespaces** | Returns metric namespaces for the specified subscription. If a resource group is specified, returns only namespaces within that group. | +| **Regions** | Returns Azure regions available for the specified subscription. | +| **Resource Names** | Returns resource names for a specified subscription, resource group, and namespace. Supports multi-value selection. | +| **Metric Names** | Returns available metric names for a specified resource. | +| **Workspaces** | Returns Log Analytics workspaces for the specified subscription. | +| **Logs** | Executes a KQL query and returns the results as variable values. See [Create a Logs variable](#create-a-logs-variable). | +| **Custom Namespaces** | Returns custom metric namespaces for a specified resource. | +| **Custom Metric Names** | Returns custom metric names for a specified resource. | {{< admonition type="note" >}} -Custom metrics cannot be emitted against a subscription or resource group. Select resources only when you need to retrieve custom metric namespaces or custom metric names associated with a specific resource. +Custom metrics cannot be emitted against a subscription or resource group. Select specific resources when retrieving custom metric namespaces or custom metric names. {{< /admonition >}} -You can use any Log Analytics Kusto Query Language (KQL) query that returns a single list of values in the `Query` field. -For example: +## Create cascading variables -| Query | List of values returned | -| ----------------------------------------------------------------------------------------- | --------------------------------------- | -| `workspace("myWorkspace").Heartbeat \| distinct Computer` | Virtual machines | -| `workspace("$workspace").Heartbeat \| distinct Computer` | Virtual machines with template variable | -| `workspace("$workspace").Perf \| distinct ObjectName` | Objects from the Perf table | -| `workspace("$workspace").Perf \| where ObjectName == "$object"` `\| distinct CounterName` | Metric names from the Perf table | +Cascading variables (also called dependent or chained variables) allow you to create dropdown menus that filter based on previous selections. This is useful for drilling down from subscription to resource group to specific resource. -### Query variable example +### Example: Subscription → Resource Group → Resource Name -This time series query uses query variables: +**Step 1: Create a Subscription variable** + +1. Create a variable named `subscription`. +1. Set **Query Type** to **Subscriptions**. + +**Step 2: Create a Resource Group variable** + +1. Create a variable named `resourceGroup`. +1. Set **Query Type** to **Resource Groups**. +1. In the **Subscription** field, select `$subscription`. + +**Step 3: Create a Resource Name variable** + +1. Create a variable named `resource`. +1. Set **Query Type** to **Resource Names**. +1. In the **Subscription** field, select `$subscription`. +1. In the **Resource Group** field, select `$resourceGroup`. +1. Select the appropriate **Namespace** for your resources (e.g., `Microsoft.Compute/virtualMachines`). + +Now when you change the subscription, the resource group dropdown updates automatically, and when you change the resource group, the resource name dropdown updates. + +## Create a Logs variable + +The **Logs** query type lets you use a KQL query to populate variable values. The query must return a single column of values. + +**To create a Logs variable:** + +1. Create a new variable with **Query Type** set to **Logs**. +1. Select a **Resource** (Log Analytics workspace or Application Insights resource). +1. Enter a KQL query that returns a single column. + +### Logs variable query examples + +| Query | Returns | +| ----------------------------------------- | ------------------------------------- | +| `Heartbeat \| distinct Computer` | List of virtual machine names | +| `Perf \| distinct ObjectName` | List of performance object names | +| `AzureActivity \| distinct ResourceGroup` | List of resource groups with activity | +| `AppRequests \| distinct Name` | List of application request names | + +You can reference other variables in your Logs query: + +```kusto +workspace("$workspace").Heartbeat | distinct Computer +``` + +```kusto +workspace("$workspace").Perf +| where ObjectName == "$object" +| distinct CounterName +``` + +## Variable refresh options + +Control when your variables refresh by setting the **Refresh** option: + +| Option | Behavior | +| ------------------------ | ----------------------------------------------------------------------------------------- | +| **On dashboard load** | Variables refresh each time the dashboard loads. Best for data that changes infrequently. | +| **On time range change** | Variables refresh when the dashboard time range changes. Use for time-sensitive queries. | + +For dashboards with many variables or complex queries, use **On dashboard load** to improve performance. + +## Use variables in queries + +After you create template variables, you can use them in your Azure Monitor queries by referencing them with the `$` prefix. + +### Metrics query example + +In a Metrics query, select your variables in the resource picker fields: + +- **Subscription**: `$subscription` +- **Resource Group**: `$resourceGroup` +- **Resource Name**: `$resource` + +### Logs query example + +Reference variables directly in your KQL queries: ```kusto Perf | where ObjectName == "$object" and CounterName == "$metric" | where TimeGenerated >= $__timeFrom() and TimeGenerated <= $__timeTo() -| where $__contains(Computer, $computer) +| where $__contains(Computer, $computer) | summarize avg(CounterValue) by bin(TimeGenerated, $__interval), Computer | order by TimeGenerated asc ``` -### Multi-value variables +## Multi-value variables -It is possible to select multiple values for **Resource Groups** and **Resource Names** and use a single metrics query pointing to those values as long as they: +You can enable **Multi-value** selection for **Resource Groups** and **Resource Names** variables. When using multi-value variables in a Metrics query, all selected resources must: -- Belong to the same subscription. -- Are in the same region. -- Are of the same type (namespace). +- Belong to the same subscription +- Be in the same Azure region +- Be of the same resource type (namespace) -Also, note that if a template variable pointing to multiple resource groups or names is used in another template variable as a parameter (e.g. to retrieve metric names), only the first value will be used. This means that the combination of the first resource group and name selected should be valid. +{{< admonition type="note" >}} +When a multi-value variable is used as a parameter in another variable query (for example, to retrieve metric names), only the first selected value is used. Ensure the first resource group and resource name combination is valid. +{{< /admonition >}} + +## Troubleshoot template variables + +If you encounter issues with template variables, try the following solutions. + +### Variable returns no values + +- Verify the Azure Monitor data source is configured correctly and can connect to Azure. +- Check that the credentials have appropriate permissions to list the requested resources. +- For cascading variables, ensure parent variables have valid selections. + +### Variable values are outdated + +- Check the **Refresh** setting and adjust if needed. +- Click the refresh icon next to the variable dropdown to manually refresh. + +### Multi-value selection not working in queries + +- Ensure the resources meet the requirements (same subscription, region, and type). +- For Logs queries, use the `$__contains()` macro to handle multi-value variables properly. diff --git a/docs/sources/datasources/azure-monitor/troubleshooting/index.md b/docs/sources/datasources/azure-monitor/troubleshooting/index.md new file mode 100644 index 00000000000..b2d5a9efc32 --- /dev/null +++ b/docs/sources/datasources/azure-monitor/troubleshooting/index.md @@ -0,0 +1,320 @@ +--- +aliases: + - ../../data-sources/azure-monitor/troubleshooting/ +description: Troubleshooting guide for the Azure Monitor data source in Grafana +keywords: + - grafana + - azure + - monitor + - troubleshooting + - errors + - authentication + - query +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Troubleshoot +title: Troubleshoot Azure Monitor data source issues +weight: 500 +last_reviewed: 2025-12-04 +refs: + configure-azure-monitor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/configure/ + template-variables: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/template-variables/ + query-editor: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//datasources/azure-monitor/query-editor/ +--- + +# Troubleshoot Azure Monitor data source issues + +This document provides solutions to common issues you may encounter when configuring or using the Azure Monitor data source. + +## Configuration and authentication errors + +These errors typically occur when setting up the data source or when authentication credentials are invalid. + +### "Authorization failed" or "Access denied" + +**Symptoms:** + +- Save & test fails with "Authorization failed" +- Queries return "Access denied" errors +- Subscriptions don't load when clicking **Load Subscriptions** + +**Possible causes and solutions:** + +| Cause | Solution | +| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| App registration doesn't have required permissions | Assign the `Reader` role to the app registration on the subscription or resource group you want to monitor. Refer to the [Azure documentation for role assignments](https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?tabs=current). | +| Incorrect tenant ID, client ID, or client secret | Verify the credentials in the Azure Portal under **App registrations** > your app > **Overview** (for IDs) and **Certificates & secrets** (for secret). | +| Client secret has expired | Create a new client secret in Azure and update the data source configuration. | +| Managed Identity not enabled on the Azure resource | For VMs, enable managed identity in the Azure Portal under **Identity**. For App Service, enable it under **Identity** in the app settings. | +| Managed Identity not assigned the Reader role | Assign the `Reader` role to the managed identity on the target subscription or resources. | + +### "Invalid client secret" or "Client secret not found" + +**Symptoms:** + +- Authentication fails immediately after configuration +- Error message references invalid credentials + +**Solutions:** + +1. Ensure you copied the client secret **value**, not the secret ID. In Azure Portal under **Certificates & secrets**, the secret value is only shown once when created. The secret ID is a different identifier and won't work for authentication. +2. Verify the client secret was copied correctly (no extra spaces or truncation). +3. Check if the secret has expired in Azure Portal under **App registrations** > your app > **Certificates & secrets**. +4. Create a new secret and update the data source configuration. + +### "Tenant not found" or "Invalid tenant ID" + +**Symptoms:** + +- Data source test fails with tenant-related errors +- Unable to authenticate + +**Solutions:** + +1. Verify the Directory (tenant) ID in Azure Portal under **Microsoft Entra ID** > **Overview**. +2. Ensure you're using the correct Azure cloud setting (Azure, Azure Government, or Azure China). +3. Check that the tenant ID is a valid GUID format. + +### Managed Identity not working + +**Symptoms:** + +- Managed Identity option is available but authentication fails +- Error: "Managed identity authentication is not available" + +**Solutions:** + +1. Verify `managed_identity_enabled = true` is set in the Grafana server configuration under `[azure]`. +2. Confirm the Azure resource hosting Grafana has managed identity enabled. +3. For user-assigned managed identity, ensure `managed_identity_client_id` is set correctly. +4. Verify the managed identity has the `Reader` role on the target resources. +5. Restart Grafana after changing server configuration. + +### Workload Identity not working + +**Symptoms:** + +- Workload Identity authentication fails in Kubernetes/AKS environment +- Token file errors + +**Solutions:** + +1. Verify `workload_identity_enabled = true` is set in the Grafana server configuration. +2. Check that the service account is correctly annotated for workload identity. +3. Verify the federated credential is configured in Azure. +4. Ensure the token path is accessible to the Grafana pod. +5. Check the workload identity webhook is running in the cluster. + +## Query errors + +These errors occur when executing queries against Azure Monitor services. + +### "No data" or empty results + +**Symptoms:** + +- Query executes without error but returns no data +- Charts show "No data" message + +**Possible causes and solutions:** + +| Cause | Solution | +| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| Time range doesn't contain data | Expand the dashboard time range or verify data exists in Azure Portal. | +| Wrong resource selected | Verify you've selected the correct subscription, resource group, and resource. | +| Metric not available for resource | Not all metrics are available for all resources. Check available metrics in Azure Portal under the resource's **Metrics** blade. | +| Metric has no values | Some metrics only populate under certain conditions (e.g., error counts when errors occur). | +| Permissions issue | Verify the identity has read access to the specific resource. | + +### "Bad request" or "Invalid query" + +**Symptoms:** + +- Query fails with 400 error +- Error message indicates query syntax issues + +**Solutions for Logs queries:** + +1. Validate your KQL syntax in the Azure Portal Log Analytics query editor. +2. Check for typos in table names or column names. +3. Ensure referenced tables exist in the selected workspace. +4. Verify the time range is valid (not in the future, not too far in the past for data retention). + +**Solutions for Metrics queries:** + +1. Verify the metric name is valid for the selected resource type. +2. Check that dimension filters use valid dimension names and values. +3. Ensure the aggregation type is supported for the selected metric. + +### "Resource not found" + +**Symptoms:** + +- Query fails with 404 error +- Resource picker shows resources that can't be queried + +**Solutions:** + +1. Verify the resource still exists in Azure (it may have been deleted or moved). +2. Check that the subscription is correct. +3. Refresh the resource picker by re-selecting the subscription. +4. Verify the identity has access to the resource's resource group. + +### Logs query timeout + +**Symptoms:** + +- Query runs for a long time then fails +- Error mentions timeout or query limits + +**Solutions:** + +1. Narrow the time range to reduce data volume. +2. Add filters to reduce the result set. +3. Use `summarize` to aggregate data instead of returning raw rows. +4. Consider using Basic Logs for large datasets (if enabled). +5. Break complex queries into smaller parts. + +### "Metrics not available" for a resource + +**Symptoms:** + +- Resource appears in picker but no metrics are listed +- Metric dropdown is empty + +**Solutions:** + +1. Verify the resource type supports Azure Monitor metrics. +2. Check if the resource is in a region that supports metrics. +3. Some resources require diagnostic settings to emit metrics—configure these in Azure Portal. +4. Try selecting a different namespace for the resource. + +## Azure Resource Graph errors + +These errors are specific to Azure Resource Graph (ARG) queries. + +### "Query execution failed" + +**Symptoms:** + +- ARG query fails with execution errors +- Results don't match expected resources + +**Solutions:** + +1. Validate query syntax in Azure Portal Resource Graph Explorer. +2. Check that you have access to the subscriptions being queried. +3. Verify table names are correct (e.g., `Resources`, `ResourceContainers`). +4. Some ARG features require specific permissions, check [ARG documentation](https://docs.microsoft.com/en-us/azure/governance/resource-graph/). + +### Query returns incomplete results + +**Symptoms:** + +- Not all expected resources appear in results +- Results seem truncated + +**Solutions:** + +1. ARG queries are paginated. The data source handles pagination automatically, but very large result sets may be limited. +2. Add filters to reduce result set size. +3. Verify you have access to all subscriptions containing the resources. + +## Application Insights Traces errors + +These errors are specific to the Traces query type. + +### "No traces found" + +**Symptoms:** + +- Trace query returns empty results +- Operation ID search finds nothing + +**Solutions:** + +1. Verify the Application Insights resource is collecting trace data. +2. Check that the time range includes when the traces were generated. +3. Ensure the Operation ID is correct (copy directly from another trace or log). +4. Verify the identity has access to the Application Insights resource. + +## Template variable errors + +For detailed troubleshooting of template variables, refer to the [template variables troubleshooting section](ref:template-variables). + +### Variables return no values + +**Solutions:** + +1. Verify the data source connection is working (test it in the data source settings). +2. Check that parent variables (for cascading variables) have valid selections. +3. Verify the identity has permissions to list the requested resources. +4. For Logs variables, ensure the KQL query returns a single column. + +### Variables are slow to load + +**Solutions:** + +1. Set variable refresh to **On dashboard load** instead of **On time range change**. +2. Reduce the scope of variable queries (e.g., filter by resource group instead of entire subscription). +3. For Logs variables, optimize the KQL query to return results faster. + +## Connection and network errors + +These errors indicate problems with network connectivity between Grafana and Azure services. + +### "Connection refused" or timeout errors + +**Symptoms:** + +- Data source test fails with network errors +- Queries timeout without returning results + +**Solutions:** + +1. Verify network connectivity from Grafana to Azure endpoints. +2. Check firewall rules allow outbound HTTPS (port 443) to Azure services. +3. For private networks, ensure Private Link or VPN is configured correctly. +4. For Grafana Cloud, configure [Private Data Source Connect](ref:configure-azure-monitor) if accessing private resources. + +### SSL/TLS certificate errors + +**Symptoms:** + +- Certificate validation failures +- SSL handshake errors + +**Solutions:** + +1. Ensure the system time is correct (certificate validation fails with incorrect time). +2. Verify corporate proxy isn't intercepting HTTPS traffic. +3. Check that required CA certificates are installed on the Grafana server. + +## Get additional help + +If you've tried the solutions above and still encounter issues: + +1. Check the [Grafana community forums](https://community.grafana.com/) for similar issues. +1. Review the [Azure Monitor data source GitHub issues](https://github.com/grafana/grafana/issues) for known bugs. +1. Enable debug logging in Grafana to capture detailed error information. +1. Contact Grafana Support if you're an Enterprise, Cloud Pro or Cloud Contracted user. +1. When reporting issues, include: + - Grafana version + - Error messages (redact sensitive information) + - Steps to reproduce + - Relevant configuration (redact credentials) diff --git a/docs/sources/datasources/elasticsearch/_index.md b/docs/sources/datasources/elasticsearch/_index.md index 1143dbdc68b..ebee19b2dcb 100644 --- a/docs/sources/datasources/elasticsearch/_index.md +++ b/docs/sources/datasources/elasticsearch/_index.md @@ -17,16 +17,6 @@ menuTitle: Elasticsearch title: Elasticsearch data source weight: 325 refs: - configuration: - - pattern: /docs/grafana/ - destination: /docs/grafana//setup-grafana/configure-grafana/#sigv4_auth_enabled - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana//setup-grafana/configure-grafana/#sigv4_auth_enabled - provisioning-grafana: - - pattern: /docs/grafana/ - destination: /docs/grafana//administration/provisioning/#data-sources - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana//administration/provisioning/#data-sources explore: - pattern: /docs/grafana/ destination: /docs/grafana//explore/ @@ -44,12 +34,36 @@ refs: Elasticsearch is a search and analytics engine used for a variety of use cases. You can create many types of queries to visualize logs or metrics stored in Elasticsearch, and annotate graphs with log events stored in Elasticsearch. -The following will help you get started working with Elasticsearch and Grafana: +The following resources will help you get started with Elasticsearch and Grafana: - [What is Elasticsearch?](https://www.elastic.co/guide/en/elasticsearch/reference/current/elasticsearch-intro.html) -- [Configure the Elasticsearch data source](/docs/grafana/latest/datasources/elasticsearch/configure-elasticsearch-data-source/) -- [Elasticsearch query editor](query-editor/) -- [Elasticsearch template variables](template-variables/) +- [Configure the Elasticsearch data source](https://grafana.com/docs/grafana//datasources/elasticsearch/configure/) +- [Elasticsearch query editor](https://grafana.com/docs/grafana//datasources/elasticsearch/query-editor/) +- [Elasticsearch template variables](https://grafana.com/docs/grafana//datasources/elasticsearch/template-variables/) +- [Elasticsearch annotations](https://grafana.com/docs/grafana//datasources/elasticsearch/annotations/) +- [Elasticsearch alerting](https://grafana.com/docs/grafana//datasources/elasticsearch/alerting/) +- [Troubleshooting issues with the Elasticsearch data source](https://grafana.com/docs/grafana//datasources/elasticsearch/troubleshooting/) + +## Key capabilities + +The Elasticsearch data source supports: + +- **Metrics queries:** Aggregate and visualize numeric data using bucket and metric aggregations. +- **Log queries:** Search, filter, and explore log data with Lucene query syntax. +- **Annotations:** Overlay Elasticsearch events on your dashboard graphs. +- **Alerting:** Create alerts based on Elasticsearch query results. + +## Before you begin + +Before you configure the Elasticsearch data source, you need: + +- An Elasticsearch instance (v7.17+, v8.x, or v9.x) +- Network access from Grafana to your Elasticsearch server +- Appropriate user credentials or API keys with read access + +{{< admonition type="note" >}} +If you use Amazon OpenSearch Service (the successor to Amazon Elasticsearch Service), use the [OpenSearch data source](https://grafana.com/docs/grafana//datasources/opensearch/) instead. +{{< /admonition >}} ## Supported Elasticsearch versions @@ -63,86 +77,18 @@ This data source supports these versions of Elasticsearch: - v8.x - v9.x -Our maintenance policy for Elasticsearch data source is aligned with the [Elastic Product End of Life Dates](https://www.elastic.co/support/eol) and we ensure proper functionality for supported versions. If you are using an Elasticsearch with version that is past its end-of-life (EOL), you can still execute queries, but you will receive a notification in the query builder indicating that the version of Elasticsearch you are using is no longer supported. It's important to note that in such cases, we do not guarantee the correctness of the functionality, and we will not be addressing any related issues. +The Grafana maintenance policy for the Elasticsearch data source aligns with [Elastic Product End of Life Dates](https://www.elastic.co/support/eol). Grafana ensures proper functionality for supported versions only. If you use an EOL version of Elasticsearch, you can still run queries, but the query builder displays a warning. Grafana doesn't guarantee functionality or provide fixes for EOL versions. -## Provision the data source +## Additional resources -You can define and configure the data source in YAML files as part of Grafana's provisioning system. -For more information about provisioning, and for available configuration options, refer to [Provisioning Grafana](ref:provisioning-grafana). +Once you have configured the Elasticsearch data source, you can: -{{< admonition type="note" >}} -The previously used `database` field has now been [deprecated](https://github.com/grafana/grafana/pull/58647). -You should now use the `index` field in `jsonData` to store the index name. -Please see the examples below. -{{< /admonition >}} +- Use [Explore](ref:explore) to run ad-hoc queries against your Elasticsearch data. +- Configure and use [template variables](https://grafana.com/docs/grafana//datasources/elasticsearch/template-variables/) for dynamic dashboards. +- Add [Transformations](https://grafana.com/docs/grafana//panels-visualizations/query-transform-data/transform-data/) to process query results. +- [Build dashboards](ref:build-dashboards) to visualize your Elasticsearch data. -### Provisioning examples +## Related data sources -**Basic provisioning** - -```yaml -apiVersion: 1 - -datasources: - - name: Elastic - type: elasticsearch - access: proxy - url: http://localhost:9200 - jsonData: - index: '[metrics-]YYYY.MM.DD' - interval: Daily - timeField: '@timestamp' -``` - -**Provision for logs** - -```yaml -apiVersion: 1 - -datasources: - - name: elasticsearch-v7-filebeat - type: elasticsearch - access: proxy - url: http://localhost:9200 - jsonData: - index: '[filebeat-]YYYY.MM.DD' - interval: Daily - timeField: '@timestamp' - logMessageField: message - logLevelField: fields.level - dataLinks: - - datasourceUid: my_jaeger_uid # Target UID needs to be known - field: traceID - url: '$${__value.raw}' # Careful about the double "$$" because of env var expansion -``` - -## Configure Amazon Elasticsearch Service - -If you use Amazon Elasticsearch Service, you can use Grafana's Elasticsearch data source to visualize data from it. - -If you use an AWS Identity and Access Management (IAM) policy to control access to your Amazon Elasticsearch Service domain, you must use AWS Signature Version 4 (AWS SigV4) to sign all requests to that domain. - -For details on AWS SigV4, refer to the [AWS documentation](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). - -### AWS Signature Version 4 authentication - -To sign requests to your Amazon Elasticsearch Service domain, you can enable SigV4 in Grafana's [configuration](ref:configuration). - -Once AWS SigV4 is enabled, you can configure it on the Elasticsearch data source configuration page. -For more information about AWS authentication options, refer to [AWS authentication](../aws-cloudwatch/aws-authentication/). - -{{< figure src="/static/img/docs/v73/elasticsearch-sigv4-config-editor.png" max-width="500px" class="docs-image--no-shadow" caption="SigV4 configuration for AWS Elasticsearch Service" >}} - -## Query the data source - -You can select multiple metrics and group by multiple terms or filters when using the Elasticsearch query editor. - -For details, see the [query editor documentation](query-editor/). - -## Use template variables - -Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables. -Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard. -Grafana refers to such variables as template variables. - -For details, see the [template variables documentation](template-variables/). +- [OpenSearch](https://grafana.com/docs/grafana//datasources/opensearch/) - For Amazon OpenSearch Service. +- [Loki](https://grafana.com/docs/grafana//datasources/loki/) - Grafana's log aggregation system. diff --git a/docs/sources/datasources/elasticsearch/alerting/index.md b/docs/sources/datasources/elasticsearch/alerting/index.md new file mode 100644 index 00000000000..ef002764bda --- /dev/null +++ b/docs/sources/datasources/elasticsearch/alerting/index.md @@ -0,0 +1,144 @@ +--- +aliases: + - ../../data-sources/elasticsearch/alerting/ +description: Using Grafana Alerting with the Elasticsearch data source +keywords: + - grafana + - elasticsearch + - alerting + - alerts +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Alerting +title: Elasticsearch alerting +weight: 550 +refs: + alerting: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/alerting-and-irm/alerting/ + create-alert-rule: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/alerting-rules/create-grafana-managed-rule/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/alerting-and-irm/alerting/alerting-rules/create-grafana-managed-rule/ +--- + +# Elasticsearch alerting + +You can use Grafana Alerting with Elasticsearch to create alerts based on your Elasticsearch data. This allows you to monitor metrics, detect anomalies, and receive notifications when specific conditions are met. + +For general information about Grafana Alerting, refer to [Grafana Alerting](ref:alerting). + +## Before you begin + +Before creating alerts with Elasticsearch, ensure you have: + +- An Elasticsearch data source configured in Grafana +- Appropriate permissions to create alert rules +- Understanding of the metrics you want to monitor + +## Supported query types + +Elasticsearch alerting works best with **metrics queries** that return time series data. To create a valid alert query: + +- Use a **Date histogram** as the last bucket aggregation (under **Group by**) +- Select appropriate metric aggregations (Count, Average, Sum, Min, Max, etc.) + +Queries that return time series data allow Grafana to evaluate values over time and trigger alerts when thresholds are crossed. + +### Query types and alerting compatibility + +| Query type | Alerting support | Notes | +| ------------------------------ | ---------------- | ----------------------------------------------------------- | +| Metrics with Date histogram | ✅ Full support | Recommended for alerting | +| Metrics without Date histogram | ⚠️ Limited | May not evaluate correctly over time | +| Logs | ❌ Not supported | Use metrics queries instead | +| Raw data | ❌ Not supported | Use metrics queries instead | +| Raw document (deprecated) | ❌ Not supported | Deprecated since Grafana v10.1. Use metrics queries instead | + +## Create an alert rule + +To create an alert rule using Elasticsearch: + +1. Navigate to **Alerting** > **Alert rules**. +1. Click **New alert rule**. +1. Enter a name for the alert rule. +1. Select your **Elasticsearch** data source. +1. Build your query using the query editor: + - Add metric aggregations (for example, Average, Count, Sum) + - Add a Date histogram under **Group by** + - Optionally add filters using Lucene query syntax +1. Configure the alert condition (for example, when the average is above a threshold). +1. Set the evaluation interval and pending period. +1. Configure notifications and labels. +1. Click **Save rule**. + +For detailed instructions, refer to [Create a Grafana-managed alert rule](ref:create-alert-rule). + +## Example alert queries + +The following examples show common alerting scenarios with Elasticsearch. + +### Alert on high error count + +Monitor the number of error-level log entries: + +1. **Query:** `level:error` +1. **Metric:** Count +1. **Group by:** Date histogram (interval: 1m) +1. **Condition:** When count is above 100 + +### Alert on average response time + +Monitor API response times: + +1. **Query:** `type:api_request` +1. **Metric:** Average on field `response_time` +1. **Group by:** Date histogram (interval: 5m) +1. **Condition:** When average is above 500 (milliseconds) + +### Alert on unique user count drop + +Detect drops in active users: + +1. **Query:** `*` (all documents) +1. **Metric:** Unique count on field `user_id` +1. **Group by:** Date histogram (interval: 1h) +1. **Condition:** When unique count is below 100 + +## Limitations + +When using Elasticsearch with Grafana Alerting, be aware of the following limitations: + +### Template variables not supported + +Alert queries cannot contain template variables. Grafana evaluates alert rules on the backend without dashboard context, so variables like `$hostname` or `$environment` won't be resolved. + +If your dashboard query uses template variables, create a separate query for alerting with hard coded values. + +### Logs queries not supported + +Queries using the **Logs** metric type cannot be used for alerting. Convert your query to use metric aggregations with a Date histogram instead. + +### Query complexity + +Complex queries with many nested aggregations may timeout or fail to evaluate. Simplify queries for alerting by: + +- Reducing the number of bucket aggregations +- Using appropriate time intervals +- Adding filters to limit the data scanned + +## Best practices + +Follow these best practices when creating Elasticsearch alerts: + +- **Use specific filters:** Add Lucene query filters to focus on relevant data and improve query performance. +- **Choose appropriate intervals:** Match the Date histogram interval to your evaluation frequency. +- **Test queries first:** Verify your query returns expected results in Explore before creating an alert. +- **Set realistic thresholds:** Base alert thresholds on historical data patterns. +- **Use meaningful names:** Give alert rules descriptive names that indicate what they monitor. diff --git a/docs/sources/datasources/elasticsearch/annotations/index.md b/docs/sources/datasources/elasticsearch/annotations/index.md new file mode 100644 index 00000000000..788cfe15ff6 --- /dev/null +++ b/docs/sources/datasources/elasticsearch/annotations/index.md @@ -0,0 +1,124 @@ +--- +aliases: + - ../../data-sources/elasticsearch/annotations/ +description: Using annotations with Elasticsearch in Grafana +keywords: + - grafana + - elasticsearch + - annotations + - events +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Annotations +title: Elasticsearch annotations +weight: 500 +refs: + annotate-visualizations: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/build-dashboards/annotate-visualizations/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//dashboards/build-dashboards/annotate-visualizations/ +--- + +# Elasticsearch annotations + +Annotations overlay event data on your dashboard graphs, helping you correlate log events with metrics. +You can use Elasticsearch as a data source for annotations to display events such as deployments, alerts, or other significant occurrences on your visualizations. + +For general information about annotations, refer to [Annotate visualizations](ref:annotate-visualizations). + +## Before you begin + +Before creating Elasticsearch annotations, ensure you have: + +- An Elasticsearch data source configured in Grafana +- Documents in Elasticsearch containing event data with timestamp fields +- Read access to the Elasticsearch index containing your events + +## Create an annotation query + +To add an Elasticsearch annotation to your dashboard: + +1. Navigate to your dashboard and click **Dashboard settings** (gear icon). +1. Select **Annotations** in the left menu. +1. Click **Add annotation query**. +1. Enter a **Name** for the annotation. +1. Select your **Elasticsearch** data source from the **Data source** drop-down. +1. Configure the annotation query and field mappings. +1. Click **Save dashboard**. + +## Query + +Use the query field to filter which Elasticsearch documents appear as annotations. The query uses [Lucene query syntax](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax). + +**Examples:** + +| Query | Description | +| ---------------------------------------- | ---------------------------------------------------- | +| `*` | Matches all documents. | +| `type:deployment` | Shows only deployment events. | +| `level:error OR level:critical` | Shows error and critical events. | +| `service:api AND environment:production` | Shows events for a specific service and environment. | +| `tags:release` | Shows events tagged as releases. | + +You can use template variables in your annotation queries. For example, `service:$service` filters annotations based on the selected service variable. + +## Field mappings + +Field mappings tell Grafana which Elasticsearch fields contain the annotation data. + +### Time + +The **Time** field specifies which field contains the annotation timestamp. + +- **Default:** `@timestamp` +- **Format:** The field must contain a date value that Elasticsearch recognizes. + +### Time End + +The **Time End** field specifies a field containing the end time for range annotations. Range annotations display as a shaded region on the graph instead of a single vertical line. + +- **Default:** Empty (single-point annotations) +- **Use case:** Display maintenance windows, incidents, or any event with a duration. + +### Text + +The **Text** field specifies which field contains the annotation description displayed when you hover over the annotation. + +- **Default:** `tags` +- **Tip:** Use a descriptive field like `message`, `description`, or `summary`. + +### Tags + +The **Tags** field specifies which field contains tags for the annotation. Tags help categorize and filter annotations. + +- **Default:** Empty +- **Format:** The field can contain either a comma-separated string or an array of strings. + +## Example: Deployment annotations + +To display deployment events as annotations: + +1. Create an annotation query with the following settings: + - **Query:** `type:deployment` + - **Time:** `@timestamp` + - **Text:** `message` + - **Tags:** `environment` + +This configuration displays deployment events with their messages as the annotation text and environments as tags. + +## Example: Range annotations for incidents + +To display incidents with duration: + +1. Create an annotation query with the following settings: + - **Query:** `type:incident` + - **Time:** `start_time` + - **Time End:** `end_time` + - **Text:** `description` + - **Tags:** `severity` + +This configuration displays incidents as shaded regions from their start time to end time. diff --git a/docs/sources/datasources/elasticsearch/configure-elasticsearch-data-source.md b/docs/sources/datasources/elasticsearch/configure-elasticsearch-data-source.md deleted file mode 100644 index 6b145841bbf..00000000000 --- a/docs/sources/datasources/elasticsearch/configure-elasticsearch-data-source.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -aliases: - - ../data-sources/elasticsearch/ - - ../features/datasources/elasticsearch/ -description: Guide for configuring the Elasticsearch data source in Grafana -keywords: - - grafana - - elasticsearch - - guide - - data source -labels: - products: - - cloud - - enterprise - - oss -menuTitle: Configure Elasticsearch -title: Configure the Elasticsearch data source -weight: 200 -refs: - administration-documentation: - - pattern: /docs/grafana/ - destination: /docs/grafana//administration/data-source-management/ - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana//administration/data-source-management/ - supported-expressions: - - pattern: /docs/grafana/ - destination: /docs/grafana//explore/logs-integration/#log-level - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana//explore/logs-integration/#log-level - query-and-transform-data: - - pattern: /docs/grafana/ - destination: /docs/grafana//panels-visualizations/query-transform-data/ - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/ - provisioning-data-source: - - pattern: /docs/grafana/ - destination: /docs/grafana//datasources/elasticsearch/#provision-the-data-source - - pattern: /docs/grafana-cloud/ - destination: /docs/grafana-cloud/connect-externally-hosted/data-sources/elasticsearch/#provision-the-data-source ---- - -# Configure the Elasticsearch data source - -Grafana ships with built-in support for Elasticsearch. -You can create a variety of queries to visualize logs or metrics stored in Elasticsearch, and annotate graphs with log events stored in Elasticsearch. - -For instructions on how to add a data source to Grafana, refer to the [administration documentation](ref:administration-documentation). - -Only users with the organization `administrator` role can add data sources. -Administrators can also [configure the data source via YAML](ref:provisioning-data-source) with Grafana's provisioning system. - -## Configuring permissions - -When Elasticsearch security features are enabled, it is essential to configure the necessary cluster privileges to ensure seamless operation. Below is a list of the required privileges along with their purposes: - -- **monitor** - Necessary to retrieve the version information of the connected Elasticsearch instance. -- **view_index_metadata** - Required for accessing mapping definitions of indices. -- **read** - Grants the ability to perform search and retrieval operations on indices. This is essential for querying and extracting data from the cluster. - -## Add the data source - -To add the Elasticsearch data source, complete the following steps: - -1. Click **Connections** in the left-side menu. -1. Under **Connections**, click **Add new connection**. -1. Enter `Elasticsearch` in the search bar. -1. Click **Elasticsearch** under the **Data source** section. -1. Click **Add new data source** in the upper right. - -You will be taken to the **Settings** tab where you will set up your Elasticsearch configuration. - -## Configuration options - -The following is a list of configuration options for Elasticsearch. - -The first option to configure is the name of your connection: - -- **Name** - The data source name. This is how you refer to the data source in panels and queries. Examples: elastic-1, elasticsearch_metrics. - -- **Default** - Toggle to select as the default data source option. When you go to a dashboard panel or Explore, this will be the default selected data source. - -## Connection - -Connect the Elasticsearch data source by specifying a URL. - -- **URL** - The URL of your Elasticsearch server. If your Elasticsearch server is local, use `http://localhost:9200`. If it is on a server within a network, this is the URL with the port where you are running Elasticsearch. Example: `http://elasticsearch.example.orgname:9200`. - -## Authentication - -There are several authentication methods you can choose in the Authentication section. -Select one of the following authentication methods from the dropdown menu. - -- **Basic authentication** - The most common authentication method. Use your `data source` user name and `data source` password to connect. - -- **Forward OAuth identity** - Forward the OAuth access token (and the OIDC ID token if available) of the user querying the data source. - -- **No authentication** - Make the data source available without authentication. Grafana recommends using some type of authentication method. - - - -### TLS settings - -{{< admonition type="note" >}} -Use TLS (Transport Layer Security) for an additional layer of security when working with Elasticsearch. For information on setting up TLS encryption with Elasticsearch see [Configure TLS](https://www.elastic.co/guide/en/elasticsearch/reference/8.8/configuring-tls.html#configuring-tls). You must add TLS settings to your Elasticsearch configuration file **prior** to setting these options in Grafana. -{{< /admonition >}} - -- **Add self-signed certificate** - Check the box to authenticate with a CA certificate. Follow the instructions of the CA (Certificate Authority) to download the certificate file. Required for verifying self-signed TLS certificates. - -- **TLS client authentication** - Check the box to authenticate with the TLS client, where the server authenticates the client. Add the `Server name`, `Client certificate` and `Client key`. The **ServerName** is used to verify the hostname on the returned certificate. The **Client certificate** can be generated from a Certificate Authority (CA) or be self-signed. The **Client key** can also be generated from a Certificate Authority (CA) or be self-signed. The client key encrypts the data between client and server. - -- **Skip TLS certificate validation** - Check the box to bypass TLS certificate validation. Skipping TLS certificate validation is not recommended unless absolutely necessary or for testing purposes. - -### HTTP headers - -Click **+ Add header** to add one or more HTTP headers. HTTP headers pass additional context and metadata about the request/response. - -- **Header** - Add a custom header. This allows custom headers to be passed based on the needs of your Elasticsearch instance. - -- **Value** - The value of the header. - -## Additional settings - -Additional settings are optional settings that can be configured for more control over your data source. - -### Advanced HTTP settings - -- **Allowed cookies** - Specify cookies by name that should be forwarded to the data source. The Grafana proxy deletes all forwarded cookies by default. - -- **Timeout** - The HTTP request timeout. This must be in seconds. There is no default, so this setting is up to you. - -### Elasticsearch details - -The following settings are specific to the Elasticsearch data source. - -- **Index name** - Use the index settings to specify a default for the `time field` and your Elasticsearch index's name. You can use a time pattern, for example `[logstash-]YYYY.MM.DD`, or a wildcard for the index name. When specifying a time pattern, the fixed part(s) of the pattern should be wrapped in square brackets. - -- **Pattern** - Select the matching pattern if using one in your index name. Options include: - - no pattern - - hourly - - daily - - weekly - - monthly - - yearly - -Only select a pattern option if you have specified a time pattern in the Index name field. - -- **Time field name** - Name of the time field. The default value is @timestamp. You can enter a different name. - -- **Max concurrent shard requests** - Sets the number of shards being queried at the same time. The default is `5`. For more information on shards see [Elasticsearch's documentation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/scalability.html#scalability). - -- **Min time interval** - Defines a lower limit for the auto group-by time interval. This value **must** be formatted as a number followed by a valid time identifier: - - | Identifier | Description | - | ---------- | ----------- | - | `y` | year | - | `M` | month | - | `w` | week | - | `d` | day | - | `h` | hour | - | `m` | minute | - | `s` | second | - | `ms` | millisecond | - -We recommend setting this value to match your Elasticsearch write frequency. -For example, set this to `1m` if Elasticsearch writes data every minute. - -You can also override this setting in a dashboard panel under its data source options. The default is `10s`. - -- **X-Pack enabled** - Toggle to enable `X-Pack`-specific features and options, which provide the [query editor](../query-editor/) with additional aggregations, such as `Rate` and `Top Metrics`. - -- **Include frozen indices** - Toggle on when the `X-Pack enabled` setting is active. Includes frozen indices in searches. You can configure Grafana to include [frozen indices](https://www.elastic.co/guide/en/elasticsearch/reference/7.13/frozen-indices.html) when performing search requests. - -{{< admonition type="note" >}} -Frozen indices are [deprecated in Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/frozen-indices.html) since v7.14. -{{< /admonition >}} - -### Logs - -In this section you can configure which fields the data source uses for log messages and log levels. - -- **Message field name:** - Grabs the actual log message from the default source. - -- **Level field name:** - Name of the field with log level/severity information. When a level label is specified, the value of this label is used to determine the log level and update the color of each log line accordingly. If the log doesn’t have a specified level label, we try to determine if its content matches any of the [supported expressions](ref:supported-expressions). The first match always determines the log level. If Grafana cannot infer a log-level field, it will be visualized with an unknown log level. - -### Data links - -Data links create a link from a specified field that can be accessed in Explore's logs view. You can add multiple data links by clicking **+ Add**. - -Each data link configuration consists of: - -- **Field** - Sets the name of the field used by the data link. - -- **URL/query** - Sets the full link URL if the link is external. If the link is internal, this input serves as a query for the target data source.
In both cases, you can interpolate the value from the field with the `${__value.raw }` macro. - -- **URL Label** (Optional) - Sets a custom display label for the link. The link label defaults to the full external URL or name of the linked internal data source and is overridden by this setting. - -- **Internal link** - Toggle on to set an internal link. For an internal link, you can select the target data source with a data source selector. This supports only tracing data sources. - -## Private data source connect (PDC) and Elasticsearch - -Use private data source connect (PDC) to connect to and query data within a secure network without opening that network to inbound traffic from Grafana Cloud. See [Private data source connect](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/) for more information on how PDC works and [Configure Grafana private data source connect (PDC)](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/configure-pdc/#configure-grafana-private-data-source-connect-pdc) for steps on setting up a PDC connection. - -If you use PDC with SIGv4 (AWS Signature Version 4 Authentication), the PDC agent must allow internet egress to`sts..amazonaws.com:443`. - -- **Private data source connect** - Click in the box to set the default PDC connection from the dropdown menu or create a new connection. - -Once you have configured your Elasticsearch data source options, click **Save & test** at the bottom to test out your data source connection. You can also remove a connection by clicking **Delete**. diff --git a/docs/sources/datasources/elasticsearch/configure/index.md b/docs/sources/datasources/elasticsearch/configure/index.md new file mode 100644 index 00000000000..d76a90855ea --- /dev/null +++ b/docs/sources/datasources/elasticsearch/configure/index.md @@ -0,0 +1,377 @@ +--- +aliases: + - ../configure-elasticsearch-data-source/ +description: Guide for configuring the Elasticsearch data source in Grafana +keywords: + - grafana + - elasticsearch + - guide + - data source +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Configure +title: Configure the Elasticsearch data source +weight: 200 +refs: + administration-documentation: + - pattern: /docs/grafana/ + destination: /docs/grafana//administration/data-source-management/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//administration/data-source-management/ + supported-expressions: + - pattern: /docs/grafana/ + destination: /docs/grafana//explore/logs-integration/#log-level + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//explore/logs-integration/#log-level + query-and-transform-data: + - pattern: /docs/grafana/ + destination: /docs/grafana//panels-visualizations/query-transform-data/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/ + provisioning-data-source: + - pattern: /docs/grafana/ + destination: /docs/grafana//datasources/elasticsearch/configure/#provision-the-data-source + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/connect-externally-hosted/data-sources/elasticsearch/configure/#provision-the-data-source + configuration: + - pattern: /docs/grafana/ + destination: /docs/grafana//setup-grafana/configure-grafana/#sigv4_auth_enabled + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//setup-grafana/configure-grafana/#sigv4_auth_enabled + provisioning-grafana: + - pattern: /docs/grafana/ + destination: /docs/grafana//administration/provisioning/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//administration/provisioning/ +--- + +# Configure the Elasticsearch data source + +Grafana ships with built-in support for Elasticsearch. +You can create a variety of queries to visualize logs or metrics stored in Elasticsearch, and annotate graphs with log events stored in Elasticsearch. + +For instructions on how to add a data source to Grafana, refer to the [administration documentation](ref:administration-documentation). +Administrators can also [configure the data source via YAML](ref:provisioning-data-source) with Grafana's provisioning system. + +## Before you begin + +To configure the Elasticsearch data source, you need: + +- **Grafana administrator permissions:** Only users with the organization `administrator` role can add data sources. +- **A supported Elasticsearch version:** v7.17 or later, v8.x, or v9.x. Elastic Cloud Serverless isn't supported. +- **Elasticsearch server URL:** The HTTP or HTTPS endpoint for your Elasticsearch instance, including the port (default: `9200`). +- **Authentication credentials:** Depending on your Elasticsearch security configuration, you need one of the following: + - Username and password for basic authentication + - API key + - No credentials (if Elasticsearch security is disabled) +- **Network access:** Grafana must be able to reach your Elasticsearch server. For Grafana Cloud, consider using [Private data source connect (PDC)](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/) if your Elasticsearch instance is in a private network. + +## Elasticsearch permissions + +When Elasticsearch security features are enabled, you must configure the following cluster privileges for the user or API key that Grafana uses to connect: + +- **monitor** - Necessary to retrieve the version information of the connected Elasticsearch instance. +- **view_index_metadata** - Required for accessing mapping definitions of indices. +- **read** - Grants the ability to perform search and retrieval operations on indices. This is essential for querying and extracting data from the cluster. + +## Add the data source + +To add the Elasticsearch data source, complete the following steps: + +1. Click **Connections** in the left-side menu. +1. Under **Connections**, click **Add new connection**. +1. Enter `Elasticsearch` in the search bar. +1. Click **Elasticsearch** under the **Data source** section. +1. Click **Add new data source** in the upper right. + +You will be taken to the **Settings** tab where you will set up your Elasticsearch configuration. + +## Configuration options + +Configure the following basic settings for the Elasticsearch data source: + +- **Name** - The data source name. This is how you refer to the data source in panels and queries. Examples: `elastic-1`, `elasticsearch_metrics`. + +- **Default** - Toggle on to make this the default data source. New panels and Explore queries use the default data source. + +## Connection + +- **URL** - The URL of your Elasticsearch server, including the port. Examples: `http://localhost:9200`, `http://elasticsearch.example.com:9200`. + +## Authentication + +Select an authentication method from the drop-down menu: + +- **Basic authentication** - Enter the username and password for your Elasticsearch user. + +- **Forward OAuth identity** - Forward the OAuth access token (and the OIDC ID token if available) of the user querying the data source. + +- **No authentication** - Connect without credentials. Only use this option if your Elasticsearch instance doesn't require authentication. + +### API key authentication + +To authenticate using an Elasticsearch API key, select **No authentication** and configure the API key using HTTP headers: + +1. In the **HTTP headers** section, click **+ Add header**. +1. Set **Header** to `Authorization`. +1. Set **Value** to `ApiKey `, replacing `` with your base64-encoded Elasticsearch API key. + +For information about creating API keys, refer to the [Elasticsearch API keys documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html). + +### Amazon Elasticsearch Service + +If you use Amazon Elasticsearch Service, you can use Grafana's Elasticsearch data source to visualize data from it. + +If you use an AWS Identity and Access Management (IAM) policy to control access to your Amazon Elasticsearch Service domain, you must use AWS Signature Version 4 (AWS SigV4) to sign all requests to that domain. + +For details on AWS SigV4, refer to the [AWS documentation](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). + +To sign requests to your Amazon Elasticsearch Service domain, you can enable SigV4 in Grafana's [configuration](ref:configuration). + +Once AWS SigV4 is enabled, you can configure it on the Elasticsearch data source configuration page. +For more information about AWS authentication options, refer to [AWS authentication](https://grafana.com/docs/grafana//datasources/aws-cloudwatch/aws-authentication/). + +{{< figure src="/static/img/docs/v73/elasticsearch-sigv4-config-editor.png" max-width="500px" class="docs-image--no-shadow" caption="SigV4 configuration for AWS Elasticsearch Service" >}} + +### TLS settings + +{{< admonition type="note" >}} +Use TLS (Transport Layer Security) for an additional layer of security when working with Elasticsearch. For information on setting up TLS encryption with Elasticsearch, refer to [Configure TLS](https://www.elastic.co/guide/en/elasticsearch/reference/8.8/configuring-tls.html#configuring-tls). You must add TLS settings to your Elasticsearch configuration file **prior** to setting these options in Grafana. +{{< /admonition >}} + +- **Add self-signed certificate** - Check the box to authenticate with a CA certificate. Follow the instructions of the CA (Certificate Authority) to download the certificate file. Required for verifying self-signed TLS certificates. + +- **TLS client authentication** - Check the box to authenticate with the TLS client, where the server authenticates the client. Add the `Server name`, `Client certificate` and `Client key`. The **ServerName** is used to verify the hostname on the returned certificate. The **Client certificate** can be generated from a Certificate Authority (CA) or be self-signed. The **Client key** can also be generated from a Certificate Authority (CA) or be self-signed. The client key encrypts the data between client and server. + +- **Skip TLS certificate validation** - Check the box to bypass TLS certificate validation. Skipping TLS certificate validation is not recommended unless absolutely necessary or for testing purposes. + +### HTTP headers + +Click **+ Add header** to add one or more HTTP headers. HTTP headers pass additional context and metadata about the request/response. + +- **Header** - Add a custom header. This allows custom headers to be passed based on the needs of your Elasticsearch instance. + +- **Value** - The value of the header. + +## Additional settings + +Additional settings are optional settings that can be configured for more control over your data source. + +### Advanced HTTP settings + +- **Allowed cookies** - Specify cookies by name that should be forwarded to the data source. The Grafana proxy deletes all forwarded cookies by default. + +- **Timeout** - The HTTP request timeout. This must be in seconds. There is no default, so this setting is up to you. + +### Elasticsearch details + +The following settings are specific to the Elasticsearch data source. + +- **Index name** - The name of your Elasticsearch index. You can use the following formats: + - **Wildcard patterns** - Use `*` to match multiple indices. Examples: `logs-*`, `metrics-*`, `filebeat-*`. + - **Time patterns** - Use date placeholders for time-based indices. Wrap the fixed portion in square brackets. Examples: `[logstash-]YYYY.MM.DD`, `[metrics-]YYYY.MM`. + - **Specific index** - Enter the exact index name. Example: `application-logs`. + +- **Pattern** - Select the matching pattern if you use a time pattern in your index name. Options include: + - no pattern + - hourly + - daily + - weekly + - monthly + - yearly + +Only select a pattern option if you have specified a time pattern in the Index name field. + +- **Time field name** - Name of the time field. The default value is `@timestamp`. You can enter a different name. + +- **Max concurrent shard requests** - Sets the number of shards being queried at the same time. The default is `5`. For more information on shards, refer to the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/scalability.html#scalability). + +- **Min time interval** - Defines a lower limit for the auto group-by time interval. This value **must** be formatted as a number followed by a valid time identifier: + + | Identifier | Description | + | ---------- | ----------- | + | `y` | year | + | `M` | month | + | `w` | week | + | `d` | day | + | `h` | hour | + | `m` | minute | + | `s` | second | + | `ms` | millisecond | + +We recommend setting this value to match your Elasticsearch write frequency. +For example, set this to `1m` if Elasticsearch writes data every minute. + +You can also override this setting in a dashboard panel under its data source options. The default is `10s`. + +- **X-Pack enabled** - Toggle to enable `X-Pack`-specific features and options, which provide the [query editor](https://grafana.com/docs/grafana//datasources/elasticsearch/query-editor/) with additional aggregations, such as `Rate` and `Top Metrics`. + +- **Include frozen indices** - Toggle on when the `X-Pack enabled` setting is active. Includes frozen indices in searches. You can configure Grafana to include [frozen indices](https://www.elastic.co/guide/en/elasticsearch/reference/7.13/frozen-indices.html) when performing search requests. + +{{< admonition type="note" >}} +Frozen indices are [deprecated in Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/frozen-indices.html) since v7.14. +{{< /admonition >}} + +### Logs + +Configure which fields the data source uses for log messages and log levels. + +- **Message field name** - The field that contains the log message content. + +- **Level field name** - The field that contains log level or severity information. When specified, Grafana uses this field to determine the log level and color-code each log line. If the log doesn't have a level field, Grafana tries to match the content against [supported expressions](ref:supported-expressions). If Grafana can't determine the log level, it displays as unknown. + +### Data links + +Data links create a link from a specified field that can be accessed in Explore's logs view. You can add multiple data links by clicking **+ Add**. + +Each data link configuration consists of: + +- **Field** - Sets the name of the field used by the data link. + +- **URL/query** - Sets the full link URL if the link is external. If the link is internal, this input serves as a query for the target data source.
In both cases, you can interpolate the value from the field with the `${__value.raw }` macro. + +- **URL Label** (Optional) - Sets a custom display label for the link. The link label defaults to the full external URL or name of the linked internal data source and is overridden by this setting. + +- **Internal link** - Toggle on to set an internal link. For an internal link, you can select the target data source with a data source selector. This supports only tracing data sources. + +## Private data source connect (PDC) and Elasticsearch + +Use private data source connect (PDC) to connect to and query data within a secure network without opening that network to inbound traffic from Grafana Cloud. Refer to [Private data source connect](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/) for more information on how PDC works and [Configure Grafana private data source connect (PDC)](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/configure-pdc/#configure-grafana-private-data-source-connect-pdc) for steps on setting up a PDC connection. + +If you use PDC with SigV4 (AWS Signature Version 4 Authentication), the PDC agent must allow internet egress to `sts..amazonaws.com:443`. + +- **Private data source connect** - Click in the box to set the default PDC connection from the drop-down menu or create a new connection. + +Once you have configured your Elasticsearch data source options, click **Save & test** to test the connection. A successful connection displays the following message: + +`Elasticsearch data source is healthy.` + +## Provision the data source + +You can define and configure the data source in YAML files as part of Grafana's provisioning system. +For more information about provisioning, and for available configuration options, refer to [Provisioning Grafana](ref:provisioning-grafana). + +{{< admonition type="note" >}} +The previously used `database` field has now been [deprecated](https://github.com/grafana/grafana/pull/58647). +Use the `index` field in `jsonData` to store the index name. +Refer to the examples below. +{{< /admonition >}} + +### Basic provisioning + +```yaml +apiVersion: 1 + +datasources: + - name: Elastic + type: elasticsearch + access: proxy + url: http://localhost:9200 + jsonData: + index: '[metrics-]YYYY.MM.DD' + interval: Daily + timeField: '@timestamp' +``` + +### Provision for logs + +```yaml +apiVersion: 1 + +datasources: + - name: elasticsearch-v7-filebeat + type: elasticsearch + access: proxy + url: http://localhost:9200 + jsonData: + index: '[filebeat-]YYYY.MM.DD' + interval: Daily + timeField: '@timestamp' + logMessageField: message + logLevelField: fields.level + dataLinks: + - datasourceUid: my_jaeger_uid # Target UID needs to be known + field: traceID + url: '$${__value.raw}' # Careful about the double "$$" because of env var expansion +``` + +## Provision the data source using Terraform + +You can provision the Elasticsearch data source using [Terraform](https://www.terraform.io/) with the [Grafana Terraform provider](https://registry.terraform.io/providers/grafana/grafana/latest/docs). + +For more information about provisioning resources with Terraform, refer to the [Grafana as code using Terraform](https://grafana.com/docs/grafana-cloud/developer-resources/infrastructure-as-code/terraform/) documentation. + +### Basic Terraform example + +The following example creates a basic Elasticsearch data source for metrics: + +```hcl +resource "grafana_data_source" "elasticsearch" { + name = "Elasticsearch" + type = "elasticsearch" + url = "http://localhost:9200" + + json_data_encoded = jsonencode({ + index = "[metrics-]YYYY.MM.DD" + interval = "Daily" + timeField = "@timestamp" + }) +} +``` + +### Terraform example for logs + +The following example creates an Elasticsearch data source configured for logs with a data link to Jaeger: + +```hcl +resource "grafana_data_source" "elasticsearch_logs" { + name = "Elasticsearch Logs" + type = "elasticsearch" + url = "http://localhost:9200" + + json_data_encoded = jsonencode({ + index = "[filebeat-]YYYY.MM.DD" + interval = "Daily" + timeField = "@timestamp" + logMessageField = "message" + logLevelField = "fields.level" + dataLinks = [ + { + datasourceUid = grafana_data_source.jaeger.uid + field = "traceID" + url = "$${__value.raw}" + } + ] + }) +} +``` + +### Terraform example with basic authentication + +The following example includes basic authentication: + +```hcl +resource "grafana_data_source" "elasticsearch_auth" { + name = "Elasticsearch" + type = "elasticsearch" + url = "http://localhost:9200" + + basic_auth_enabled = true + basic_auth_username = "elastic_user" + + secure_json_data_encoded = jsonencode({ + basicAuthPassword = var.elasticsearch_password + }) + + json_data_encoded = jsonencode({ + index = "[metrics-]YYYY.MM.DD" + interval = "Daily" + timeField = "@timestamp" + }) +} +``` + +For all available configuration options, refer to the [Grafana provider data source resource documentation](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/data_source). diff --git a/docs/sources/datasources/elasticsearch/query-editor/index.md b/docs/sources/datasources/elasticsearch/query-editor/index.md index fa20353a395..c5c7bf91abf 100644 --- a/docs/sources/datasources/elasticsearch/query-editor/index.md +++ b/docs/sources/datasources/elasticsearch/query-editor/index.md @@ -30,7 +30,7 @@ refs: # Elasticsearch query editor Grafana provides a query editor for Elasticsearch. Elasticsearch queries are in Lucene format. -See [Lucene query syntax](https://www.elastic.co/guide/en/kibana/current/lucene-query.html) and [Query string syntax](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/query-dsl-query-string-query.html#query-string-syntax) if you are new to working with Lucene queries in Elasticsearch. +For more information about query syntax, refer to [Lucene query syntax](https://www.elastic.co/guide/en/kibana/current/lucene-query.html) and [Query string syntax](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax). {{< admonition type="note" >}} When composing Lucene queries, ensure that you use uppercase boolean operators: `AND`, `OR`, and `NOT`. Lowercase versions of these operators are not supported by the Lucene query syntax. @@ -38,17 +38,17 @@ When composing Lucene queries, ensure that you use uppercase boolean operators: {{< figure src="/static/img/docs/elasticsearch/elastic-query-editor-10.1.png" max-width="800px" class="docs-image--no-shadow" caption="Elasticsearch query editor" >}} -For general documentation on querying data sources in Grafana, including options and functions common to all query editors, see [Query and transform data](ref:query-and-transform-data). +For general documentation on querying data sources in Grafana, including options and functions common to all query editors, refer to [Query and transform data](ref:query-and-transform-data). ## Aggregation types Elasticsearch groups aggregations into three categories: -- **Bucket** - Bucket aggregations don't calculate metrics, they create buckets of documents based on field values, ranges and a variety of other criteria. See [Bucket aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket.html) for additional information. Use bucket aggregations under `Group by` when creating a metrics query in the query builder. +- **Bucket** - Bucket aggregations don't calculate metrics, they create buckets of documents based on field values, ranges and a variety of other criteria. Refer to [Bucket aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket.html) for additional information. Use bucket aggregations under `Group by` when creating a metrics query in the query builder. -- **Metrics** - Metrics aggregations perform calculations such as sum, average, min, etc. They can be single-value or multi-value. See [Metrics aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics.html) for additional information. Use metrics aggregations in the metrics query type in the query builder. +- **Metrics** - Metrics aggregations perform calculations such as sum, average, min, etc. They can be single-value or multi-value. Refer to [Metrics aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics.html) for additional information. Use metrics aggregations in the metrics query type in the query builder. -- **Pipeline** - Elasticsearch pipeline aggregations work with inputs or metrics created from other aggregations (not documents or fields). There are parent and sibling and sibling pipeline aggregations. See [Pipeline aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-pipeline.html) for additional information. +- **Pipeline** - Pipeline aggregations work on the output of other aggregations rather than on documents or fields. Refer to [Pipeline aggregations](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline.html) for additional information. ## Select a query type @@ -56,44 +56,51 @@ There are three types of queries you can create with the Elasticsearch query bui ### Metrics query type -Metrics queries aggregate data and produce a variety of calculations such as count, min, max, etc. Click on the metric box to view a list of options in the dropdown menu. The default is `count`. +Metrics queries aggregate data and produce calculations such as count, min, max, and more. Click the metric box to view options in the drop-down menu. The default is `count`. - **Alias** - Aliasing only applies to **time series queries**, where the last group is `date histogram`. This is ignored for any other type of query. - **Metric** - Metrics aggregations include: - - count - see [Value count aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-valuecount-aggregation.html) - - average - see [Avg aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-rate-aggregation.html) - - sum - see [Sum aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html) - - max - see [Max aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-max-aggregation.html) - - min - see [Min aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-min-aggregation.html) - - extended stats - see [Extended stats aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-extendedstats-aggregation.html) - - percentiles - see [Percentiles aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-percentile-aggregation.html) - - unique count - see [Cardinality aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-cardinality-aggregation.html) - - top metrics - see [Top metrics aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-top-metrics.html) - - rate - see [Rate aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/8.9/search-aggregations-metrics-rate-aggregation.html) + - count - refer to [Value count aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-valuecount-aggregation.html) + - average - refer to [Avg aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-avg-aggregation.html) + - sum - refer to [Sum aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-sum-aggregation.html) + - max - refer to [Max aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-max-aggregation.html) + - min - refer to [Min aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-min-aggregation.html) + - extended stats - refer to [Extended stats aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-extendedstats-aggregation.html) + - percentiles - refer to [Percentiles aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html) + - unique count - refer to [Cardinality aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html) + - top metrics - refer to [Top metrics aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-metrics.html) + - rate - refer to [Rate aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-rate-aggregation.html) + +- **Pipeline aggregations** - Pipeline aggregations work on the output of other aggregations rather than on documents. The following pipeline aggregations are available: + - moving function - Calculates a value based on a sliding window of aggregated values. Refer to [Moving function aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-movfn-aggregation.html). + - derivative - Calculates the derivative of a metric. Refer to [Derivative aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-derivative-aggregation.html). + - cumulative sum - Calculates the cumulative sum of a metric. Refer to [Cumulative sum aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-cumulative-sum-aggregation.html). + - serial difference - Calculates the difference between values in a time series. Refer to [Serial differencing aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-serialdiff-aggregation.html). + - bucket script - Executes a script on metric values from other aggregations. Refer to [Bucket script aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html). You can select multiple metrics and group by multiple terms or filters when using the Elasticsearch query editor. Use the **+ sign** to the right to add multiple metrics to your query. Click on the **eye icon** next to **Metric** to hide metrics, and the **garbage can icon** to remove metrics. -- **Group by options** - Create multiple group by options when constructing your Elasticsearch query. Date histogram is the default option. Below is a list of options in the dropdown menu. - - terms - see [Terms aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html). - - filter - see [Filter aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html). - - geo hash grid - see [Geohash grid aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-geohashgrid-aggregation.html). - - date histogram - for time series queries. See [Date histogram aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html). - - histogram - Depicts frequency distributions. See [Histogram aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-histogram-aggregation.html). - - nested (experimental) - See [Nested aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html). +- **Group by options** - Create multiple group by options when constructing your Elasticsearch query. Date histogram is the default option. The following options are available in the drop-down menu: + - terms - refer to [Terms aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html). + - filter - refer to [Filter aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-filter-aggregation.html). + - geo hash grid - refer to [Geohash grid aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-geohashgrid-aggregation.html). + - date histogram - for time series queries. Refer to [Date histogram aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html). + - histogram - Depicts frequency distributions. Refer to [Histogram aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-histogram-aggregation.html). + - nested (experimental) - Refer to [Nested aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html). Each group by option will have a different subset of options to further narrow your query. The following options are specific to the **date histogram** bucket aggregation option. -- **Time field** - Depicts date data options. The default option can be specified when configuring the Elasticsearch data source in the **Time field name** under the [**Elasticsearch details**](/docs/grafana/latest/datasources/elasticsearch/configure-elasticsearch-data-source/#elasticsearch-details) section. Otherwise **@timestamp** field will be used as a default option. -- **Interval** - Group by a type of interval. There are option to choose from the dropdown menu to select seconds, minutes, hours or day. You can also add a custom interval such as `30d` (30 days). `Auto` is the default option. -- **Min doc count** - The minimum amount of data to include in your query. The default is `0`. -- **Thin edges** - Select to trim edges on the time series data points. The default is `0`. -- **Offset** - Changes the start value of each bucket by the specified positive(+) or negative (-) offset duration. Examples include `1h` for 1 hour, `5s` for 5 seconds or `1d` for 1 day. -- **Timezone** - Select a timezone from the dropdown menu. The default is `Coordinated universal time`. +- **Time field** - The field used for time-based queries. The default can be set when configuring the data source in the **Time field name** setting under [Elasticsearch details](https://grafana.com/docs/grafana//datasources/elasticsearch/configure/#elasticsearch-details). The default is `@timestamp`. +- **Interval** - The time interval for grouping data. Select from the drop-down menu or enter a custom interval such as `30d` (30 days). The default is `Auto`. +- **Min doc count** - The minimum number of documents required to include a bucket. The default is `0`. +- **Trim edges** - Removes partial buckets at the edges of the time range. The default is `0`. +- **Offset** - Shifts the start of each bucket by the specified duration. Use positive (`+`) or negative (`-`) values. Examples: `1h`, `5s`, `1d`. +- **Timezone** - The timezone for date calculations. The default is `Coordinated Universal Time`. Configure the following options for the **terms** bucket aggregation option: @@ -101,7 +108,7 @@ Configure the following options for the **terms** bucket aggregation option: - **Size** - Limits the number of documents, or size of the data set. You can set a custom number or `no limit`. - **Min doc count** - The minimum amount of data to include in your query. The default is `0`. - **Order by** - Order terms by `term value`, `doc count` or `count`. -- **Missing** - Defines how documents missing a value should be treated. Missing values are ignored by default, but they can be treated as if they had a value. See [Missing value](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_missing_value_5) in Elasticsearch's documentation for more information. +- **Missing** - Defines how documents missing a value should be treated. Missing values are ignored by default, but they can be treated as if they had a value. Refer to [Missing value](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#_missing_value_5) in the Elasticsearch documentation for more information. Configure the following options for the **filters** bucket aggregation option: @@ -114,8 +121,8 @@ Configure the following options for the **geo hash grid** bucket aggregation opt Configure the following options for the **histogram** bucket aggregation option: -- **Interval** - Group by a type of interval. There are option to choose from the dropdown menu to select seconds, minutes, hours or day. You can also add a custom interval such as `30d` (30 days). `Auto` is the default option. -- **Min doc count** - The minimum amount of data to include in your query. The default is `0` +- **Interval** - The numeric interval for grouping values into buckets. +- **Min doc count** - The minimum number of documents required to include a bucket. The default is `0`. The **nested** group by option is currently experimental, you can select a field and then settings specific to that field. @@ -141,7 +148,7 @@ The option to run a **raw document query** is deprecated as of Grafana v10.1. ## Use template variables -You can also augment queries by using [template variables](../template-variables/). +You can also augment queries by using [template variables](https://grafana.com/docs/grafana//datasources/elasticsearch/template-variables/). Queries of `terms` have a 500-result limit by default. To set a custom limit, set the `size` property in your query. diff --git a/docs/sources/datasources/elasticsearch/template-variables/index.md b/docs/sources/datasources/elasticsearch/template-variables/index.md index 66ca17a93bd..ed2cb95f3af 100644 --- a/docs/sources/datasources/elasticsearch/template-variables/index.md +++ b/docs/sources/datasources/elasticsearch/template-variables/index.md @@ -22,6 +22,11 @@ refs: destination: /docs/grafana//dashboards/variables/ - pattern: /docs/grafana-cloud/ destination: /docs/grafana//dashboards/variables/ + add-template-variables-add-ad-hoc-filters: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/variables/add-template-variables/#add-ad-hoc-filters + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//dashboards/variables/add-template-variables/#add-ad-hoc-filters add-template-variables-multi-value-variables: - pattern: /docs/grafana/ destination: /docs/grafana//dashboards/variables/add-template-variables/#multi-value-variables @@ -37,11 +42,29 @@ refs: # Elasticsearch template variables Instead of hard-coding details such as server, application, and sensor names in metric queries, you can use variables. -Grafana lists these variables in dropdown select boxes at the top of the dashboard to help you change the data displayed in your dashboard. +Grafana lists these variables in drop-down select boxes at the top of the dashboard to help you change the data displayed in your dashboard. Grafana refers to such variables as template variables. For an introduction to templating and template variables, refer to the [Templating](ref:variables) and [Add and manage variables](ref:add-template-variables) documentation. +## Use ad hoc filters + +Elasticsearch supports the **Ad hoc filters** variable type. +You can use this variable type to specify any number of key/value filters, and Grafana applies them automatically to all of your Elasticsearch queries. + +Ad hoc filters support the following operators: + +| Operator | Description | +| -------- | ------------------------------------------------------------- | +| `=` | Equals. Adds `AND field:"value"` to the query. | +| `!=` | Not equals. Adds `AND -field:"value"` to the query. | +| `=~` | Matches regex. Adds `AND field:/value/` to the query. | +| `!~` | Does not match regex. Adds `AND -field:/value/` to the query. | +| `>` | Greater than. Adds `AND field:>value` to the query. | +| `<` | Less than. Adds `AND field:}} -To use an ascending sort (`asc`) with doc_count (a bottom-N list), set `order: "asc"`. However, Elasticsearch [discourages this](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order) because sorting by ascending doc count can return inaccurate results. -{{< /admonition >}} - -To keep terms in the doc count order, set the variable's Sort dropdown to **Disabled**. -You can alternatively use other sorting criteria, such as **Alphabetical**, to re-sort them. +This example defines a variable named `$host` that only shows hosts matching the selected `$environment`: +```json +{ "find": "terms", "field": "hostname", "query": "environment:$environment" } ``` -{"find": "terms", "field": "hostname", "orderBy": "doc_count"} -``` + +Whenever you change the value of the `$environment` variable via the drop-down, Grafana triggers an update of the `$host` variable to contain only hostnames filtered by the selected environment. + +### Variables in aggregations + +You can use variables in bucket aggregation fields to dynamically change how data is grouped. For example, use a variable in the **Terms** group by field to let users switch between grouping by `hostname`, `service`, or `datacenter`. ## Template variable examples @@ -92,11 +116,36 @@ Write the query using a custom JSON string, with the field mapped as a [keyword] If the query is [multi-field](https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html) with both a `text` and `keyword` type, use `"field":"fieldname.keyword"` (sometimes `fieldname.raw`) to specify the keyword field in your query. -| Query | Description | -| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `{"find": "fields", "type": "keyword"}` | Returns a list of field names with the index type `keyword`. | -| `{"find": "terms", "field": "hostname.keyword", "size": 1000}` | Returns a list of values for a keyword using term aggregation. Query will use current dashboard time range as time range query. | -| `{"find": "terms", "field": "hostname", "query": ''}` | Returns a list of values for a keyword field using term aggregation and a specified Lucene query filter. Query will use current dashboard time range as time range for query. | +| Query | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `{"find": "fields", "type": "keyword"}` | Returns a list of field names with the index type `keyword`. | +| `{"find": "fields", "type": "number"}` | Returns a list of numeric field names (includes `float`, `double`, `integer`, `long`, `scaled_float`). | +| `{"find": "fields", "type": "date"}` | Returns a list of date field names. | +| `{"find": "terms", "field": "hostname.keyword", "size": 1000}` | Returns a list of values for a keyword field. Uses the current dashboard time range. | +| `{"find": "terms", "field": "hostname", "query": ""}` | Returns a list of values filtered by a Lucene query. Uses the current dashboard time range. | +| `{"find": "terms", "field": "status", "orderBy": "doc_count"}` | Returns values sorted by document count (descending by default). | +| `{"find": "terms", "field": "status", "orderBy": "doc_count", "order": "asc"}` | Returns values sorted by document count in ascending order. | -Queries of `terms` have a 500-result limit by default. -To set a custom limit, set the `size` property in your query. +Queries of `terms` have a 500-result limit by default. To set a custom limit, set the `size` property in your query. + +### Sort query results + +By default, queries return results in term order (which can then be sorted alphabetically or numerically using the variable's Sort setting). + +To produce a list of terms sorted by document count (a top-N values list), add an `orderBy` property of `doc_count`. This automatically selects a descending sort: + +```json +{ "find": "terms", "field": "status", "orderBy": "doc_count" } +``` + +You can also use the `order` property to explicitly set ascending or descending sort: + +```json +{ "find": "terms", "field": "hostname", "orderBy": "doc_count", "order": "asc" } +``` + +{{< admonition type="note" >}} +Elasticsearch [discourages](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html#search-aggregations-bucket-terms-aggregation-order) sorting by ascending doc count because it can return inaccurate results. +{{< /admonition >}} + +To keep terms in the document count order, set the variable's Sort drop-down to **Disabled**. You can alternatively use other sorting criteria, such as **Alphabetical**, to re-sort them. diff --git a/docs/sources/datasources/elasticsearch/troubleshooting/index.md b/docs/sources/datasources/elasticsearch/troubleshooting/index.md new file mode 100644 index 00000000000..ff0f73c6093 --- /dev/null +++ b/docs/sources/datasources/elasticsearch/troubleshooting/index.md @@ -0,0 +1,266 @@ +--- +aliases: + - ../../data-sources/elasticsearch/troubleshooting/ +description: Troubleshooting the Elasticsearch data source in Grafana +keywords: + - grafana + - elasticsearch + - troubleshooting + - errors +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Troubleshooting +title: Troubleshoot issues with the Elasticsearch data source +weight: 600 +--- + +# Troubleshoot issues with the Elasticsearch data source + +This document provides troubleshooting information for common errors you may encounter when using the Elasticsearch data source in Grafana. + +## Connection errors + +The following errors occur when Grafana cannot establish or maintain a connection to Elasticsearch. + +### Failed to connect to Elasticsearch + +**Error message:** "Health check failed: Failed to connect to Elasticsearch" + +**Cause:** Grafana cannot establish a network connection to the Elasticsearch server. + +**Solution:** + +1. Verify that the Elasticsearch URL is correct in the data source configuration. +1. Check that Elasticsearch is running and accessible from the Grafana server. +1. Ensure there are no firewall rules blocking the connection. +1. If using a proxy, verify the proxy settings are correct. +1. For Grafana Cloud, ensure you have configured [Private data source connect](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/) if your Elasticsearch instance is not publicly accessible. + +### Request timed out + +**Error message:** "Health check failed: Elasticsearch data source is not healthy. Request timed out" + +**Cause:** The connection to Elasticsearch timed out before receiving a response. + +**Solution:** + +1. Check the network latency between Grafana and Elasticsearch. +1. Verify that Elasticsearch is not overloaded or experiencing performance issues. +1. Increase the timeout setting in the data source configuration if needed. +1. Check if any network devices (load balancers, proxies) are timing out the connection. + +### Failed to parse data source URL + +**Error message:** "Failed to parse data source URL" + +**Cause:** The URL entered in the data source configuration is not valid. + +**Solution:** + +1. Verify the URL format is correct (for example, `http://localhost:9200` or `https://elasticsearch.example.com:9200`). +1. Ensure the URL includes the protocol (`http://` or `https://`). +1. Remove any trailing slashes or invalid characters from the URL. + +## Authentication errors + +The following errors occur when there are issues with authentication credentials or permissions. + +### Unauthorized (401) + +**Error message:** "Health check failed: Elasticsearch data source is not healthy. Status: 401 Unauthorized" + +**Cause:** The authentication credentials are invalid or missing. + +**Solution:** + +1. Verify that the username and password are correct. +1. If using an API key, ensure the key is valid and has not expired. +1. Check that the authentication method selected matches your Elasticsearch configuration. +1. Verify the user has the required permissions to access the Elasticsearch cluster. + +### Forbidden (403) + +**Error message:** "Health check failed: Elasticsearch data source is not healthy. Status: 403 Forbidden" + +**Cause:** The authenticated user does not have permission to access the requested resource. + +**Solution:** + +1. Verify the user has read access to the specified index. +1. Check Elasticsearch security settings and role mappings. +1. Ensure the user has permission to access the `_cluster/health` endpoint. +1. If using AWS Elasticsearch Service with SigV4 authentication, verify the IAM policy grants the required permissions. + +## Cluster health errors + +The following errors occur when the Elasticsearch cluster is unhealthy or unavailable. + +### Cluster status is red + +**Error message:** "Health check failed: Elasticsearch data source is not healthy" + +**Cause:** The Elasticsearch cluster health status is red, indicating one or more primary shards are not allocated. + +**Solution:** + +1. Check the Elasticsearch cluster health using `GET /_cluster/health`. +1. Review Elasticsearch logs for errors. +1. Verify all nodes in the cluster are running and connected. +1. Check for unassigned shards using `GET /_cat/shards?v&h=index,shard,prirep,state,unassigned.reason`. +1. Consider increasing the cluster's resources or reducing the number of shards. + +### Bad Gateway (502) + +**Error message:** "Health check failed: Elasticsearch data source is not healthy. Status: 502 Bad Gateway" + +**Cause:** A proxy or load balancer between Grafana and Elasticsearch returned an error. + +**Solution:** + +1. Check the health of any proxies or load balancers in the connection path. +1. Verify Elasticsearch is running and accepting connections. +1. Review proxy/load balancer logs for more details. +1. Ensure the proxy timeout is configured appropriately for Elasticsearch requests. + +## Index errors + +The following errors occur when there are issues with the configured index or index pattern. + +### Index not found + +**Error message:** "Error validating index: index_not_found" + +**Cause:** The specified index or index pattern does not match any existing indices. + +**Solution:** + +1. Verify the index name or pattern in the data source configuration. +1. Check that the index exists using `GET /_cat/indices`. +1. If using a time-based index pattern (for example, `[logs-]YYYY.MM.DD`), ensure indices exist for the selected time range. +1. Verify the user has permission to access the index. + +### Time field not found + +**Error message:** "Could not find time field '@timestamp' with type date in index" + +**Cause:** The specified time field does not exist in the index or is not of type `date`. + +**Solution:** + +1. Verify the time field name in the data source configuration matches the field in your index. +1. Check the field mapping using `GET //_mapping`. +1. Ensure the time field is mapped as a `date` type, not `text` or `keyword`. +1. If the field name is different (for example, `timestamp` instead of `@timestamp`), update the data source configuration. + +## Query errors + +The following errors occur when there are issues with query syntax or configuration. + +### Too many buckets + +**Error message:** "Trying to create too many buckets. Must be less than or equal to: [65536]." + +**Cause:** The query is generating more aggregation buckets than Elasticsearch allows. + +**Solution:** + +1. Reduce the time range of your query. +1. Increase the date histogram interval (for example, change from `10s` to `1m`). +1. Add filters to reduce the number of documents being aggregated. +1. Increase the `search.max_buckets` setting in Elasticsearch (requires cluster admin access). + +### Required field missing + +**Error message:** "Required one of fields [field, script], but none were specified." + +**Cause:** A metric aggregation (such as Average, Sum, or Min) was added without specifying a field. + +**Solution:** + +1. Select a field for the metric aggregation in the query editor. +1. Ensure the selected field exists in your index and contains numeric data. + +### Unsupported interval + +**Error message:** "unsupported interval '<interval>'" + +**Cause:** The interval specified for the index pattern is not valid. + +**Solution:** + +1. Use a supported interval: `Hourly`, `Daily`, `Weekly`, `Monthly`, or `Yearly`. +1. If you don't need a time-based index pattern, use `No pattern` and specify the exact index name. + +## Version errors + +The following errors occur when there are Elasticsearch version compatibility issues. + +### Unsupported Elasticsearch version + +**Error message:** "Support for Elasticsearch versions after their end-of-life (currently versions < 7.16) was removed. Using unsupported version of Elasticsearch may lead to unexpected and incorrect results." + +**Cause:** The Elasticsearch version is no longer supported by the Grafana data source. + +**Solution:** + +1. Upgrade Elasticsearch to a supported version (7.17+, 8.x, or 9.x). +1. Refer to [Elastic Product End of Life Dates](https://www.elastic.co/support/eol) for version support information. +1. Note that queries may still work, but Grafana does not guarantee functionality for unsupported versions. + +## Other common issues + +The following issues don't produce specific error messages but are commonly encountered. + +### Empty query results + +**Cause:** The query returns no data. + +**Solution:** + +1. Verify the time range includes data in your index. +1. Check the Lucene query syntax for errors. +1. Test the query directly in Elasticsearch using the `_search` API. +1. Ensure the index contains documents matching your query filters. + +### Slow query performance + +**Cause:** Queries take a long time to execute. + +**Solution:** + +1. Reduce the time range of your query. +1. Add more specific filters to limit the data scanned. +1. Increase the date histogram interval. +1. Check Elasticsearch cluster performance and resource utilization. +1. Consider using index aliases or data streams for better query routing. + +### CORS errors in browser console + +**Cause:** Cross-Origin Resource Sharing (CORS) is blocking requests from the browser to Elasticsearch. + +**Solution:** + +1. Use Server (proxy) access mode instead of Browser access mode in the data source configuration. +1. If Browser access is required, configure CORS settings in Elasticsearch: + +```yaml +http.cors.enabled: true +http.cors.allow-origin: '' +http.cors.allow-headers: 'Authorization, Content-Type' +http.cors.allow-credentials: true +``` + +{{< admonition type="note" >}} +Server (proxy) access mode is recommended for security and reliability. +{{< /admonition >}} + +## Get additional help + +If you continue to experience issues after following this troubleshooting guide: + +1. Check the [Elasticsearch documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html) for API-specific guidance. +1. Review the [Grafana community forums](https://community.grafana.com/) for similar issues. +1. Contact Grafana Support if you have an Enterprise license. diff --git a/docs/sources/datasources/influxdb/_index.md b/docs/sources/datasources/influxdb/_index.md index c3f722d848f..4ede6c02c52 100644 --- a/docs/sources/datasources/influxdb/_index.md +++ b/docs/sources/datasources/influxdb/_index.md @@ -52,6 +52,7 @@ The following documents will help you get started with the InfluxDB data source - [Configure the InfluxDB data source](./configure-influxdb-data-source/) - [InfluxDB query editor](./query-editor/) - [InfluxDB templates and variables](./template-variables/) +- [Troubleshoot issues with the InfluxDB data source](./troubleshooting/) Once you have configured the data source you can: diff --git a/docs/sources/datasources/influxdb/troubleshooting/index.md b/docs/sources/datasources/influxdb/troubleshooting/index.md new file mode 100644 index 00000000000..33fe67ecadf --- /dev/null +++ b/docs/sources/datasources/influxdb/troubleshooting/index.md @@ -0,0 +1,291 @@ +--- +aliases: + - ../../data-sources/influxdb/troubleshooting/ +description: Troubleshooting the InfluxDB data source in Grafana +keywords: + - grafana + - influxdb + - troubleshooting + - errors + - flux + - influxql + - sql +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Troubleshooting +title: Troubleshoot issues with the InfluxDB data source +weight: 600 +--- + +# Troubleshoot issues with the InfluxDB data source + +This document provides troubleshooting information for common errors you may encounter when using the InfluxDB data source in Grafana. + +## Connection errors + +The following errors occur when Grafana cannot establish or maintain a connection to InfluxDB. + +### Failed to connect to InfluxDB + +**Error message:** "error performing influxQL query" or "error performing flux query" or "error performing sql query" + +**Cause:** Grafana cannot establish a network connection to the InfluxDB server. + +**Solution:** + +1. Verify that the InfluxDB URL is correct in the data source configuration. +1. Check that InfluxDB is running and accessible from the Grafana server. +1. Ensure the URL includes the protocol (`http://` or `https://`). +1. Verify the port is correct (the InfluxDB default API port is `8086`). +1. Ensure there are no firewall rules blocking the connection. +1. For Grafana Cloud, ensure you have configured [Private data source connect](https://grafana.com/docs/grafana-cloud/connect-externally-hosted/private-data-source-connect/) if your InfluxDB instance is not publicly accessible. + +### Request timed out + +**Error message:** "context deadline exceeded" or "request timeout" + +**Cause:** The connection to InfluxDB timed out before receiving a response. + +**Solution:** + +1. Check the network latency between Grafana and InfluxDB. +1. Verify that InfluxDB is not overloaded or experiencing performance issues. +1. Increase the timeout setting in the data source configuration under **Advanced HTTP Settings**. +1. Reduce the time range or complexity of your query. + +## Authentication errors + +The following errors occur when there are issues with authentication credentials or permissions. + +### Unauthorized (401) + +**Error message:** "401 Unauthorized" or "authorization failed" + +**Cause:** The authentication credentials are invalid or missing. + +**Solution:** + +1. Verify that the token or password is correct in the data source configuration. +1. For Flux and SQL, ensure the token has not expired. +1. For InfluxQL with InfluxDB 2.x, verify the token is set as an `Authorization` header with the value `Token `. +1. For InfluxDB 1.x, verify the username and password are correct. +1. Check that the token has the required permissions to access the specified bucket or database. + +### Forbidden (403) + +**Error message:** "403 Forbidden" or "access denied" + +**Cause:** The authenticated user or token does not have permission to access the requested resource. + +**Solution:** + +1. Verify the token has read access to the specified bucket or database. +1. Check the token's permissions in the InfluxDB UI under **API Tokens**. +1. Ensure the organization ID is correct for Flux queries. +1. For InfluxQL with InfluxDB 2.x, verify the DBRP mapping is configured correctly. + +## Configuration errors + +The following errors occur when the data source is not configured correctly. + +### Unknown influx version + +**Error message:** "unknown influx version" + +**Cause:** The query language is not properly configured in the data source settings. + +**Solution:** + +1. Open the data source configuration in Grafana. +1. Verify that a valid query language is selected: **Flux**, **InfluxQL**, or **SQL**. +1. Ensure the selected query language matches your InfluxDB version: + - Flux: InfluxDB 1.8+ and 2.x + - InfluxQL: InfluxDB 1.x and 2.x (with DBRP mapping) + - SQL: InfluxDB 3.x only + +### Invalid data source info received + +**Error message:** "invalid data source info received" + +**Cause:** The data source configuration is incomplete or corrupted. + +**Solution:** + +1. Delete and recreate the data source. +1. Ensure all required fields are populated based on your query language: + - **Flux:** URL, Organization, Token, Default Bucket + - **InfluxQL:** URL, Database, User, Password + - **SQL:** URL, Database, Token + +### DBRP mapping required + +**Error message:** "database not found" or queries return no data with InfluxQL on InfluxDB 2.x + +**Cause:** InfluxQL queries on InfluxDB 2.x require a Database and Retention Policy (DBRP) mapping. + +**Solution:** + +1. Create a DBRP mapping in InfluxDB using the CLI or API. +1. Refer to [Manage DBRP Mappings](https://docs.influxdata.com/influxdb/cloud/query-data/influxql/dbrp/) for guidance. +1. Verify the database name in Grafana matches the DBRP mapping. + +## Query errors + +The following errors occur when there are issues with query syntax or execution. + +### Query syntax error + +**Error message:** "error parsing query: found THING" or "failed to parse query: found WERE, expected ; at line 1, char 38" + +**Cause:** The query contains invalid syntax. + +**Solution:** + +1. Check your query syntax for typos or invalid keywords. +1. For InfluxQL, verify the query follows the correct syntax: + + ```sql + SELECT FROM WHERE + ``` + +1. For Flux, ensure proper pipe-forward syntax and function calls. +1. Use the InfluxDB UI or CLI to test your query directly. + +### Query timeout limit exceeded + +**Error message:** "query-timeout limit exceeded" + +**Cause:** The query took longer than the configured timeout limit in InfluxDB. + +**Solution:** + +1. Reduce the time range of your query. +1. Add more specific filters to limit the data scanned. +1. Increase the query timeout setting in InfluxDB if you have admin access. +1. Optimize your query to reduce complexity. + +### Too many series or data points + +**Error message:** "max-series-per-database limit exceeded" or "A query returned too many data points and the results have been truncated" + +**Cause:** The query is returning more data than the configured limits allow. + +**Solution:** + +1. Reduce the time range of your query. +1. Add filters to limit the number of series returned. +1. Increase the **Max series** setting in the data source configuration under **Advanced Database Settings**. +1. Use aggregation functions to reduce the number of data points. +1. For Flux, use `aggregateWindow()` to downsample data. + +### No time column found + +**Error message:** "no time column found" + +**Cause:** The query result does not include a time column, which is required for time series visualization. + +**Solution:** + +1. Ensure your query includes a time field. +1. For Flux, verify the query includes `_time` in the output. +1. For SQL, ensure the query returns a timestamp column. +1. Check that the time field is not being filtered out or excluded. + +## Health check errors + +The following errors occur when testing the data source connection. + +### Error getting flux query buckets + +**Error message:** "error getting flux query buckets" + +**Cause:** The health check query `buckets()` failed to return results. + +**Solution:** + +1. Verify the token has permission to list buckets. +1. Check that the organization ID is correct. +1. Ensure InfluxDB is running and accessible. + +### Error connecting InfluxDB influxQL + +**Error message:** "error connecting InfluxDB influxQL" + +**Cause:** The health check query `SHOW MEASUREMENTS` failed. + +**Solution:** + +1. Verify the database name is correct. +1. Check that the user has permission to run `SHOW MEASUREMENTS`. +1. Ensure the database exists and contains measurements. +1. For InfluxDB 2.x, verify DBRP mapping is configured. + +### 0 measurements found + +**Error message:** "data source is working. 0 measurements found" + +**Cause:** The connection is successful, but the database contains no measurements. + +**Solution:** + +1. Verify you are connecting to the correct database. +1. Check that data has been written to the database. +1. If the database is new, add some test data to verify the connection. + +## Other common issues + +The following issues don't produce specific error messages but are commonly encountered. + +### Empty query results + +**Cause:** The query returns no data. + +**Solution:** + +1. Verify the time range includes data in your database. +1. Check that the measurement and field names are correct. +1. Test the query directly in the InfluxDB UI or CLI. +1. Ensure filters are not excluding all data. +1. For InfluxQL, verify the retention policy contains data for the selected time range. + +### Slow query performance + +**Cause:** Queries take a long time to execute. + +**Solution:** + +1. Reduce the time range of your query. +1. Add more specific filters to limit the data scanned. +1. Increase the **Min time interval** setting to reduce the number of data points. +1. Check InfluxDB server performance and resource utilization. +1. For Flux, use `aggregateWindow()` to downsample data before visualization. +1. Consider using continuous queries or tasks to pre-aggregate data. + +### Data appears delayed or missing recent points + +**Cause:** The visualization doesn't show the most recent data. + +**Solution:** + +1. Check the dashboard time range and refresh settings. +1. Verify the **Min time interval** is not set too high. +1. Ensure InfluxDB has finished writing the data. +1. Check for clock synchronization issues between Grafana and InfluxDB. + +## Get additional help + +If you continue to experience issues after following this troubleshooting guide: + +1. Check the [InfluxDB documentation](https://docs.influxdata.com/) for API-specific guidance. +1. Review the [Grafana community forums](https://community.grafana.com/) for similar issues. +1. Contact Grafana Support if you're an Enterprise, Cloud Pro or Cloud Contracted user. +1. When reporting issues, include: + - Grafana version + - InfluxDB version and product (OSS, Cloud, Enterprise) + - Query language (Flux, InfluxQL, or SQL) + - Error messages (redact sensitive information) + - Steps to reproduce + - Relevant configuration such as data source settings, HTTP method, and TLS settings (redact tokens, passwords, and other credentials) diff --git a/docs/sources/datasources/mysql/troubleshoot/index.md b/docs/sources/datasources/mysql/troubleshoot/index.md new file mode 100644 index 00000000000..0fcf80e55ac --- /dev/null +++ b/docs/sources/datasources/mysql/troubleshoot/index.md @@ -0,0 +1,80 @@ +--- +description: Learn how to troubleshoot common problems with the Grafana MySQL data source plugin +keywords: + - grafana + - mysql + - query +labels: + products: + - cloud + - enterprise + - oss +menuTitle: Troubleshoot +title: Troubleshoot common problems with the Grafana MySQL data source plugin +weight: 40 +refs: + variables: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/variables/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/dashboards/variables/ + variable-syntax-advanced-variable-format-options: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/variables/variable-syntax/#advanced-variable-format-options + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/dashboards/variables/variable-syntax/#advanced-variable-format-options + annotate-visualizations: + - pattern: /docs/grafana/ + destination: /docs/grafana//dashboards/build-dashboards/annotate-visualizations/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/dashboards/build-dashboards/annotate-visualizations/ + explore: + - pattern: /docs/grafana/ + destination: /docs/grafana//explore/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana//explore/ + query-transform-data: + - pattern: /docs/grafana/ + destination: /docs/grafana//panels-visualizations/query-transform-data/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/ + panel-inspector: + - pattern: /docs/grafana/ + destination: /docs/grafana//panels-visualizations/panel-inspector/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/panels-visualizations/panel-inspector/ + query-editor: + - pattern: /docs/grafana/ + destination: /docs/grafana//panels-visualizations/query-transform-data/#query-editors + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/visualizations/panels-visualizations/query-transform-data/#query-editors + alert-rules: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/fundamentals/alert-rules/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/alerting-and-irm/alerting/alerting-rules/ + template-annotations-and-labels: + - pattern: /docs/grafana/ + destination: /docs/grafana//alerting/alerting-rules/templates/ + - pattern: /docs/grafana-cloud/ + destination: /docs/grafana-cloud/alerting-and-irm/alerting/alerting-rules/templates/ + configure-standard-options: + - pattern: /docs/grafana/ + - destination: /docs/grafana//panels-visualizations/configure-standard-options/ +--- + +# Troubleshoot common problems with the Grafana MySQL data source plugin + +This page lists common issues you might experience when setting up the Grafana MySQL data source plugin. + +### My data source connection fails when using the Grafana MySQL data source plugin + +- Check if the MySQL server is up and running. +- Make sure that your firewall is open for MySQL server (default port is `3306`). +- Ensure that you have the correct permissions to access the MySQL server and also have permission to access the database. +- If the error persists, create a new user for the Grafana MySQL data source plugin with correct permissions and try to connect with it. + +### What should I do if I see "An unexpected error happened" or "Could not connect to MySQL" after trying all of the above? + +- Check the Grafana logs for more details about the error. +- For Grafana Cloud customers, contact support. diff --git a/docs/sources/fundamentals/glossary/index.md b/docs/sources/fundamentals/glossary/index.md index eee83a7f2de..428764b4ae5 100644 --- a/docs/sources/fundamentals/glossary/index.md +++ b/docs/sources/fundamentals/glossary/index.md @@ -83,6 +83,11 @@ This topic lists words and abbreviations that are commonly used in the Grafana d A commonly-used visualization that displays data as points, lines, or bars. + + grafanactl + + A command-line tool that enables users to authenticate, manage multiple environments, and perform administrative tasks through Grafana's REST API. + mixin diff --git a/docs/sources/setup-grafana/configure-grafana/_index.md b/docs/sources/setup-grafana/configure-grafana/_index.md index 1a3e4aea652..a82ca8f91dd 100644 --- a/docs/sources/setup-grafana/configure-grafana/_index.md +++ b/docs/sources/setup-grafana/configure-grafana/_index.md @@ -1776,6 +1776,13 @@ Specify the frequency of polling for Alertmanager configuration changes. The def The interval string is a possibly signed sequence of decimal numbers, followed by a unit suffix (ms, s, m, h, d), for example, 30s or 1m. +#### `alertmanager_max_template_output_bytes` + +Maximum size in bytes that the expanded result of any single template expression (e.g. {{ .CommonAnnotations.description }}, {{ .ExternalURL }}, etc.) may reach during notification rendering. +The limit is checked after template execution for each templated field, but before the value is inserted into the final notification payload sent to the receiver. +If exceeded, the notification will contain output truncated up to the limit and a warning will be logged. +The default value is 10,485,760 bytes (10Mb). + #### `ha_redis_address` Redis server address or addresses. It can be a single Redis address if using Redis standalone, diff --git a/docs/sources/upgrade-guide/upgrade-v12.0/index.md b/docs/sources/upgrade-guide/upgrade-v12.0/index.md index 779950c0fd4..b166cc2c022 100644 --- a/docs/sources/upgrade-guide/upgrade-v12.0/index.md +++ b/docs/sources/upgrade-guide/upgrade-v12.0/index.md @@ -80,3 +80,87 @@ Since Grafana 10.2, the endpoint to check compatible versions when installing a #### What if I want to ignore the compatibility check? We _do not_ recommend installing plugins declared as incompatible. However, if you need to force install a plugin despite it being declared as incompatible, refer to the [Installing a plugin from a ZIP](https://grafana.com/docs/grafana/latest/administration/plugin-management/#install-a-plugin-from-a-zip-file) guidance. + +### Annotation table migration + +**Plan for increased disk usage when upgrading from Grafana v11.x** + +Upgrading from Grafana v11.x to Grafana v12.x triggers a full-table rewrite of the `annotation` table. The migration populates the new `dashboard_uid` column, which causes the database to rewrite the entire table and rebuild its indexes. + +Environments with large annotation datasets can experience significant temporary disk usage increase, which may lead to: + +- Rapid disk consumption on the database data volume +- Database migration failures (for example, "could not extend file: No space left on device") +- Grafana startup failures +- Extended downtime during the upgrade process + +#### How do I know if I'm affected? + +You're affected if you're upgrading from Grafana v11.x to v12.x and you have a large `annotation` table in your database. + +To check your annotation table size, connect to your database and check the table size. + +For PostgreSQL, run the following query: + +```sql +SELECT + pg_size_pretty(pg_relation_size('annotation')) AS table_size, + pg_size_pretty(pg_indexes_size('annotation')) AS indexes_size, + pg_size_pretty(pg_total_relation_size('annotation')) AS total_size; +``` + +For MySQL, run the following query: + +```sql +SELECT + ROUND(data_length / 1024 / 1024, 2) AS table_size_mb, + ROUND(index_length / 1024 / 1024, 2) AS indexes_size_mb, + ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_size_mb +FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name = 'annotation'; +``` + +For SQLite, check the database file size directly, as SQLite stores all tables in a single file. You can run the following command from your terminal: + +```bash +ls -lh +``` + +If your total size is several gigabytes or more, you should plan accordingly before upgrading. + +#### What should I do before upgrading? + +Before you upgrade, take the following steps: + +1. **Verify available disk space**: Ensure you have at least 2-3 times the current `annotation` table size available as free disk space on your database data volume. + +1. **Review your annotation data**: Consider whether you need to retain all historical annotations. + +1. **Clean up old annotations (optional)**: If you have annotations you don't need, remove them before upgrading. + +1. **Back up your database**: Always back up your Grafana database before performing an upgrade. For more information, refer to [Back up Grafana](#back-up-grafana). + +#### What should I do after upgrading? + +After successfully upgrading to Grafana v12.x, you can reclaim disk space by performing database maintenance operations during a maintenance window. + +For PostgreSQL, run a `VACUUM FULL` operation on the `annotation` table: + +```sql +VACUUM FULL annotation; +``` + +For MySQL, run an `OPTIMIZE TABLE` operation on the `annotation` table: + +```sql +OPTIMIZE TABLE annotation; +``` + +For SQLite, run a `VACUUM` operation on the database: + +```sql +VACUUM; +``` + +These operations require a lock on the table and may take significant time depending on the table size. Plan to run these during a low-traffic period. diff --git a/docs/sources/upgrade-guide/upgrade-v12.1/index.md b/docs/sources/upgrade-guide/upgrade-v12.1/index.md index 74095298c90..9a96c0cbc0a 100644 --- a/docs/sources/upgrade-guide/upgrade-v12.1/index.md +++ b/docs/sources/upgrade-guide/upgrade-v12.1/index.md @@ -20,3 +20,87 @@ weight: 499 {{< docs/shared lookup="upgrade/upgrade-common-tasks.md" source="grafana" version="" >}} ## Technical notes + +### Annotation table migration + +**Plan for increased disk usage when upgrading from Grafana v11.x** + +Upgrading from Grafana v11.x to Grafana v12.x triggers a full-table rewrite of the `annotation` table. The migration populates the new `dashboard_uid` column, which causes the database to rewrite the entire table and rebuild its indexes. + +Environments with large annotation datasets can experience significant temporary disk usage increase, which may lead to: + +- Rapid disk consumption on the database data volume +- Database migration failures (for example, "could not extend file: No space left on device") +- Grafana startup failures +- Extended downtime during the upgrade process + +#### How do I know if I'm affected? + +You're affected if you're upgrading from Grafana v11.x to v12.x and you have a large `annotation` table in your database. + +To check your annotation table size, connect to your database and check the table size. + +For PostgreSQL, run the following query: + +```sql +SELECT + pg_size_pretty(pg_relation_size('annotation')) AS table_size, + pg_size_pretty(pg_indexes_size('annotation')) AS indexes_size, + pg_size_pretty(pg_total_relation_size('annotation')) AS total_size; +``` + +For MySQL, run the following query: + +```sql +SELECT + ROUND(data_length / 1024 / 1024, 2) AS table_size_mb, + ROUND(index_length / 1024 / 1024, 2) AS indexes_size_mb, + ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_size_mb +FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name = 'annotation'; +``` + +For SQLite, check the database file size directly, as SQLite stores all tables in a single file. You can run the following command from your terminal: + +```bash +ls -lh +``` + +If your total size is several gigabytes or more, you should plan accordingly before upgrading. + +#### What should I do before upgrading? + +Before you upgrade, take the following steps: + +1. **Verify available disk space**: Ensure you have at least 2-3 times the current `annotation` table size available as free disk space on your database data volume. + +1. **Review your annotation data**: Consider whether you need to retain all historical annotations. + +1. **Clean up old annotations (optional)**: If you have annotations you don't need, remove them before upgrading. + +1. **Back up your database**: Always back up your Grafana database before performing an upgrade. For more information, refer to [Back up Grafana](#back-up-grafana). + +#### What should I do after upgrading? + +After successfully upgrading to Grafana v12.x, you can reclaim disk space by performing database maintenance operations during a maintenance window. + +For PostgreSQL, run a `VACUUM FULL` operation on the `annotation` table: + +```sql +VACUUM FULL annotation; +``` + +For MySQL, run an `OPTIMIZE TABLE` operation on the `annotation` table: + +```sql +OPTIMIZE TABLE annotation; +``` + +For SQLite, run a `VACUUM` operation on the database: + +```sql +VACUUM; +``` + +These operations require a lock on the table and may take significant time depending on the table size. Plan to run these during a low-traffic period. diff --git a/docs/sources/upgrade-guide/upgrade-v12.2/index.md b/docs/sources/upgrade-guide/upgrade-v12.2/index.md index d2605fc51d1..221ae3f152c 100644 --- a/docs/sources/upgrade-guide/upgrade-v12.2/index.md +++ b/docs/sources/upgrade-guide/upgrade-v12.2/index.md @@ -18,3 +18,89 @@ weight: 498 {{< docs/shared lookup="back-up/back-up-grafana.md" source="grafana" version="" leveloffset="+1" >}} {{< docs/shared lookup="upgrade/upgrade-common-tasks.md" source="grafana" version="" >}} + +## Technical notes + +### Annotation table migration + +**Plan for increased disk usage when upgrading from Grafana v11.x** + +Upgrading from Grafana v11.x to Grafana v12.x triggers a full-table rewrite of the `annotation` table. The migration populates the new `dashboard_uid` column, which causes the database to rewrite the entire table and rebuild its indexes. + +Environments with large annotation datasets can experience significant temporary disk usage increase, which may lead to: + +- Rapid disk consumption on the database data volume +- Database migration failures (for example, "could not extend file: No space left on device") +- Grafana startup failures +- Extended downtime during the upgrade process + +#### How do I know if I'm affected? + +You're affected if you're upgrading from Grafana v11.x to v12.x and you have a large `annotation` table in your database. + +To check your annotation table size, connect to your database and check the table size. + +For PostgreSQL, run the following query: + +```sql +SELECT + pg_size_pretty(pg_relation_size('annotation')) AS table_size, + pg_size_pretty(pg_indexes_size('annotation')) AS indexes_size, + pg_size_pretty(pg_total_relation_size('annotation')) AS total_size; +``` + +For MySQL, run the following query: + +```sql +SELECT + ROUND(data_length / 1024 / 1024, 2) AS table_size_mb, + ROUND(index_length / 1024 / 1024, 2) AS indexes_size_mb, + ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_size_mb +FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name = 'annotation'; +``` + +For SQLite, check the database file size directly, as SQLite stores all tables in a single file. You can run the following command from your terminal: + +```bash +ls -lh +``` + +If your total size is several gigabytes or more, you should plan accordingly before upgrading. + +#### What should I do before upgrading? + +Before you upgrade, take the following steps: + +1. **Verify available disk space**: Ensure you have at least 2-3 times the current `annotation` table size available as free disk space on your database data volume. + +1. **Review your annotation data**: Consider whether you need to retain all historical annotations. + +1. **Clean up old annotations (optional)**: If you have annotations you don't need, remove them before upgrading. + +1. **Back up your database**: Always back up your Grafana database before performing an upgrade. For more information, refer to [Back up Grafana](#back-up-grafana). + +#### What should I do after upgrading? + +After successfully upgrading to Grafana v12.x, you can reclaim disk space by performing database maintenance operations during a maintenance window. + +For PostgreSQL, run a `VACUUM FULL` operation on the `annotation` table: + +```sql +VACUUM FULL annotation; +``` + +For MySQL, run an `OPTIMIZE TABLE` operation on the `annotation` table: + +```sql +OPTIMIZE TABLE annotation; +``` + +For SQLite, run a `VACUUM` operation on the database: + +```sql +VACUUM; +``` + +These operations require a lock on the table and may take significant time depending on the table size. Plan to run these during a low-traffic period. diff --git a/docs/sources/upgrade-guide/upgrade-v12.3/index.md b/docs/sources/upgrade-guide/upgrade-v12.3/index.md index 8d3dacbf396..6160c443e10 100644 --- a/docs/sources/upgrade-guide/upgrade-v12.3/index.md +++ b/docs/sources/upgrade-guide/upgrade-v12.3/index.md @@ -18,3 +18,89 @@ weight: 497 {{< docs/shared lookup="back-up/back-up-grafana.md" source="grafana" version="" leveloffset="+1" >}} {{< docs/shared lookup="upgrade/upgrade-common-tasks.md" source="grafana" version="" >}} + +## Technical notes + +### Annotation table migration + +**Plan for increased disk usage when upgrading from Grafana v11.x** + +Upgrading from Grafana v11.x to Grafana v12.x triggers a full-table rewrite of the `annotation` table. The migration populates the new `dashboard_uid` column, which causes the database to rewrite the entire table and rebuild its indexes. + +Environments with large annotation datasets can experience significant temporary disk usage increase, which may lead to: + +- Rapid disk consumption on the database data volume +- Database migration failures (for example, "could not extend file: No space left on device") +- Grafana startup failures +- Extended downtime during the upgrade process + +#### How do I know if I'm affected? + +You're affected if you're upgrading from Grafana v11.x to v12.x and you have a large `annotation` table in your database. + +To check your annotation table size, connect to your database and check the table size. + +For PostgreSQL, run the following query: + +```sql +SELECT + pg_size_pretty(pg_relation_size('annotation')) AS table_size, + pg_size_pretty(pg_indexes_size('annotation')) AS indexes_size, + pg_size_pretty(pg_total_relation_size('annotation')) AS total_size; +``` + +For MySQL, run the following query: + +```sql +SELECT + ROUND(data_length / 1024 / 1024, 2) AS table_size_mb, + ROUND(index_length / 1024 / 1024, 2) AS indexes_size_mb, + ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_size_mb +FROM information_schema.tables +WHERE table_schema = DATABASE() + AND table_name = 'annotation'; +``` + +For SQLite, check the database file size directly, as SQLite stores all tables in a single file. You can run the following command from your terminal: + +```bash +ls -lh +``` + +If your total size is several gigabytes or more, you should plan accordingly before upgrading. + +#### What should I do before upgrading? + +Before you upgrade, take the following steps: + +1. **Verify available disk space**: Ensure you have at least 2-3 times the current `annotation` table size available as free disk space on your database data volume. + +1. **Review your annotation data**: Consider whether you need to retain all historical annotations. + +1. **Clean up old annotations (optional)**: If you have annotations you don't need, remove them before upgrading. + +1. **Back up your database**: Always back up your Grafana database before performing an upgrade. For more information, refer to [Back up Grafana](#back-up-grafana). + +#### What should I do after upgrading? + +After successfully upgrading to Grafana v12.x, you can reclaim disk space by performing database maintenance operations during a maintenance window. + +For PostgreSQL, run a `VACUUM FULL` operation on the `annotation` table: + +```sql +VACUUM FULL annotation; +``` + +For MySQL, run an `OPTIMIZE TABLE` operation on the `annotation` table: + +```sql +OPTIMIZE TABLE annotation; +``` + +For SQLite, run a `VACUUM` operation on the database: + +```sql +VACUUM; +``` + +These operations require a lock on the table and may take significant time depending on the table size. Plan to run these during a low-traffic period. diff --git a/docs/sources/upgrade-guide/when-to-upgrade/index.md b/docs/sources/upgrade-guide/when-to-upgrade/index.md index e7a29e531e0..53d8c23330e 100644 --- a/docs/sources/upgrade-guide/when-to-upgrade/index.md +++ b/docs/sources/upgrade-guide/when-to-upgrade/index.md @@ -107,8 +107,8 @@ Here is an overview of version support through 2026: | 12.0.x | May 5, 2025 | February 5, 2026 | Patch Support | | 12.1.x | July 22, 2025 | April 22, 2026 | Patch Support | | 12.2.x | September 23, 2025 | June 23, 2026 | Patch Support | -| 12.3.x | November 18, 2025 | August 18, 2026 | Yet to be released | -| 12.4.x (Last minor of 12) | February 24, 2026 | November 24, 2026 | Yet to be released | +| 12.3.x | November 19, 2025 | August 19, 2026 | Patch Support | +| 12.4.x (Last minor of 12) | February 24, 2026 | May 24, 2027 | Yet to be released | | 13.0.0 | TBD | TBD | Yet to be released | ## How are these versions supported? diff --git a/docs/sources/visualizations/dashboards/build-dashboards/annotate-visualizations/index.md b/docs/sources/visualizations/dashboards/build-dashboards/annotate-visualizations/index.md index fcccfa6bd1b..f356d51c4a5 100644 --- a/docs/sources/visualizations/dashboards/build-dashboards/annotate-visualizations/index.md +++ b/docs/sources/visualizations/dashboards/build-dashboards/annotate-visualizations/index.md @@ -149,7 +149,10 @@ To add a new annotation query to a dashboard, follow these steps: You can also click **Open advanced data source picker** to see more options, including adding a data source (Admins only). 1. If you don't want to use the annotation query right away, clear the **Enabled** checkbox. -1. If you don't want the annotation query toggle to be displayed in the dashboard, select the **Hidden** checkbox. +1. Select one of the following options in the **Show annotation controls in** drop-down list to control where annotations are displayed: + - **Above dashboard** - The annotation toggle is displayed above the dashboard. This is the default. + - **Controls menu** - The annotation toggle is displayed in the dashboard controls menu instead of above the dashboard. The dashboard controls menu appears as a button in the dashboard toolbar. + - **Hidden** - The annotation toggle is not displayed on the dashboard. 1. Select a color for the event markers. 1. In the **Show in** drop-down, choose one of the following options: - **All panels** - The annotations are displayed on all panels that support annotations. diff --git a/docs/sources/visualizations/dashboards/build-dashboards/create-dynamic-dashboard/index.md b/docs/sources/visualizations/dashboards/build-dashboards/create-dynamic-dashboard/index.md index a77e4ca988f..0167ff147e5 100644 --- a/docs/sources/visualizations/dashboards/build-dashboards/create-dynamic-dashboard/index.md +++ b/docs/sources/visualizations/dashboards/build-dashboards/create-dynamic-dashboard/index.md @@ -245,11 +245,12 @@ To configure repeats, follow these steps: 1. Click **Save**. 1. Toggle off the edit mode switch. -### Repeating rows and the Dashboard special data source +### Repeating rows and tabs and the Dashboard special data source If a row includes panels using the special [Dashboard data source](ref:built-in-special-data-sources)—the data source that uses a result set from another panel in the same dashboard—then corresponding panels in repeated rows will reference the panel in the original row, not the ones in the repeated rows. +The same behavior applies to tabs. For example, in a dashboard: diff --git a/docs/sources/visualizations/dashboards/build-dashboards/manage-dashboard-links/index.md b/docs/sources/visualizations/dashboards/build-dashboards/manage-dashboard-links/index.md index cddf9a5b9f5..3e94ec5aa22 100644 --- a/docs/sources/visualizations/dashboards/build-dashboards/manage-dashboard-links/index.md +++ b/docs/sources/visualizations/dashboards/build-dashboards/manage-dashboard-links/index.md @@ -99,6 +99,7 @@ Add links to other dashboards at the top of your current dashboard. - **Include current time range** – Select this option to include the dashboard time range in the link. When the user clicks the link, the linked dashboard opens with the indicated time range already set. **Example:** https://play.grafana.org/d/000000010/annotations?orgId=1&from=now-3h&to=now - **Include current template variable values** – Select this option to include template variables currently used as query parameters in the link. When the user clicks the link, any matching templates in the linked dashboard are set to the values from the link. For more information, see [Dashboard URL variables](ref:dashboard-url-variables). - **Open link in new tab** – Select this option if you want the dashboard link to open in a new tab or window. + - **Show in controls menu** – Select this option to display the link in the dashboard controls menu instead of at the top of the dashboard. The dashboard controls menu appears as a button in the dashboard toolbar. 1. Click **Save dashboard** in the top-right corner. 1. Click **Back to dashboard** and then **Exit edit**. @@ -121,6 +122,7 @@ Add a link to a URL at the top of your current dashboard. You can link to any av - **Include current time range** – Select this option to include the dashboard time range in the link. When the user clicks the link, the linked dashboard opens with the indicated time range already set. **Example:** https://play.grafana.org/d/000000010/annotations?orgId=1&from=now-3h&to=now - **Include current template variable values** – Select this option to include template variables currently used as query parameters in the link. When the user clicks the link, any matching templates in the linked dashboard are set to the values from the link. - **Open link in new tab** – Select this option if you want the dashboard link to open in a new tab or window. + - **Show in controls menu** – Select this option to display the link in the dashboard controls menu instead of at the top of the dashboard. The dashboard controls menu appears as a button in the dashboard toolbar. 1. Click **Save dashboard** in the top-right corner. 1. Click **Back to dashboard** and then **Exit edit**. diff --git a/docs/sources/visualizations/dashboards/share-dashboards-panels/_index.md b/docs/sources/visualizations/dashboards/share-dashboards-panels/_index.md index a2867759119..5fcd2344fe2 100644 --- a/docs/sources/visualizations/dashboards/share-dashboards-panels/_index.md +++ b/docs/sources/visualizations/dashboards/share-dashboards-panels/_index.md @@ -223,17 +223,25 @@ To export a dashboard in its current state as a PDF, follow these steps: 1. Click the **X** at the top-right corner to close the share drawer. -### Export a dashboard as JSON +### Export a dashboard as code Export a Grafana JSON file that contains everything you need, including layout, variables, styles, data sources, queries, and so on, so that you can later import the dashboard. To export a JSON file, follow these steps: 1. Click **Dashboards** in the main menu. 1. Open the dashboard you want to export. -1. Click the **Export** drop-down list in the top-right corner and select **Export as JSON**. +1. Click the **Export** drop-down list in the top-right corner and select **Export as code**. - The **Export dashboard JSON** drawer opens. + The **Export dashboard** drawer opens. + +1. Select the dashboard JSON model that you to export: + - **Classic** - Export dashboards created using the [current dashboard schema](https://grafana.com/docs/grafana//visualizations/dashboards/build-dashboards/view-dashboard-json-model/). + - **V1 Resource** - Export dashboards created using the [current dashboard schema](https://grafana.com/docs/grafana//visualizations/dashboards/build-dashboards/view-dashboard-json-model/) wrapped in the `spec` property of the [V1 Kubernetes-style resource](https://play.grafana.org/swagger?api=dashboard.grafana.app-v2alpha1). Choose between **JSON** and **YAML** format. + - **V2 Resource** - Export dashboards created using the [V2 Resource schema](https://play.grafana.org/swagger?api=dashboard.grafana.app-v2beta1). Choose between **JSON** and **YAML** format. + +1. Do one of the following: + - Toggle the **Export for sharing externally** switch to generate the JSON with a different data source UID. + - Toggle the **Remove deployment details** switch to make the dashboard externally shareable. -1. Toggle the **Export the dashboard to use in another instance** switch to generate the JSON with a different data source UID. 1. Click **Download file** or **Copy to clipboard**. 1. Click the **X** at the top-right corner to close the share drawer. diff --git a/docs/sources/visualizations/dashboards/variables/add-template-variables/index.md b/docs/sources/visualizations/dashboards/variables/add-template-variables/index.md index aef32f9b569..5ee61394a15 100644 --- a/docs/sources/visualizations/dashboards/variables/add-template-variables/index.md +++ b/docs/sources/visualizations/dashboards/variables/add-template-variables/index.md @@ -123,10 +123,11 @@ To create a variable, follow these steps: If you don't enter a display name, then the drop-down list label is the variable name. -1. Choose a **Show on dashboard** option: - - **Label and value** - The variable drop-down list displays the variable **Name** or **Label** value. This is the default. - - **Value:** The variable drop-down list only displays the selected variable value and a down arrow. - - **Nothing:** No variable drop-down list is displayed on the dashboard. +1. Choose a **Display** option: + - **Above dashboard** - The variable drop-down list displays above the dashboard with the variable **Name** or **Label** value. This is the default. + - **Above dashboard, label hidden** - The variable drop-down list displays above the dashboard, but without showing the name of the variable. + - **Controls menu** - The variable is displayed in the dashboard controls menu instead of above the dashboard. The dashboard controls menu appears as a button in the dashboard toolbar. + - **Hidden** - No variable drop-down list is displayed on the dashboard. 1. Click one of the following links to complete the steps for adding your selected variable type: - [Query](#add-a-query-variable) diff --git a/docs/sources/visualizations/explore/logs-integration.md b/docs/sources/visualizations/explore/logs-integration.md index 8aa18f45616..a4f8fe7c64b 100644 --- a/docs/sources/visualizations/explore/logs-integration.md +++ b/docs/sources/visualizations/explore/logs-integration.md @@ -43,24 +43,36 @@ If the data source doesn't support loading the full range logs volume, the logs The following sections provide detailed explanations on how to visualize and interact with individual logs in Explore. -### Logs navigation +### Infinite scroll -Logs navigation, located at the right side of the log lines, can be used to easily request additional logs by clicking **Older logs** at the bottom of the navigation. This is especially useful when you reach the line limit and you want to see more logs. Each request run from the navigation displays in the navigation as separate page. Every page shows `from` and `to` timestamps of the incoming log lines. You can see previous results by clicking on each page. Explore caches the last five requests run from the logs navigation so you're not re-running the same queries when clicking on the pages, saving time and resources. + -![Navigate logs in Explore](/static/img/docs/explore/navigate-logs-8-0.png) +When you reach the bottom of the list of logs, you will see the message `Scroll to load more`. If you continue scrolling and the displayed logs are within the selected time interval, Grafana will load more logs. When the sort order is "newest first" you receive older logs, and when the sort order is "oldest first" you get newer logs. + + ### Visualization options You have the option to customize the display of logs and choose which columns to show. Following is a list of available options. -| Option | Description | -| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Time** | Shows or hides the time column. This is the timestamp associated with the log line as reported from the data source. | -| **Unique labels** | Shows or hides the unique labels column that includes only non-common labels. All common labels are displayed above. | -| **Wrap lines** | Set this to `true` if you want the display to use line wrapping. If set to `false`, it will result in horizontal scrolling. | -| **Prettify JSON** | Set this to `true` to pretty print all JSON logs. This setting does not affect logs in any format other than JSON. | -| **Deduplication** | Log data can be very repetitive. Explore hides duplicate log lines using a few different deduplication algorithms. **Exact** matches are done on the whole line except for date fields. **Numbers** matches are done on the line after stripping out numbers such as durations, IP addresses, and so on. **Signature** is the most aggressive deduplication as it strips all letters and numbers and matches on the remaining whitespace and punctuation. | -| **Display results order** | You can change the order of received logs from the default descending order (newest first) to ascending order (oldest first). | + + +| Option | Description | +| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Expand / Collapse | Expand or collapse the controls toolbar. | +| Scroll to bottom | Jump to the bottom of the logs table. | +| Oldest Logs First / Newest logs first | Sort direction (ascending or descending). | +| Search logs / Close search | Click to open/close the client side string search of the displayed logs result. | +| Deduplication | **None** does not perform any deduplication, **Exact** matches are done on the whole line except for date fields. **Numbers** matches are done on the line after stripping out numbers such as durations, IP addresses, and so on. **Signature** is the most aggressive deduplication as it strips all letters and numbers and matches on the remaining whitespace and punctuation. | +| Filter levels | Filter logs in display by log level: All levels, Info, Debut, Warning, Error. | +| Set Timestamp format | Hide timestamps (disabled), Show milliseconds timestamps, Show nanoseconds timestamps. | +| Set line wrap | Disable line wrapping, Enable line wrapping, Enable line wrapping and prettify JSON. | +| Enable highlighting | Plain text, Highlight text. | +| Font size | Small font (default), Large font. | +| Unescaped newlines | Only displayed if the logs contain unescaped new lines. Click to unescape and display as new lines. | +| Download logs | Plain text (txt), JavaScript Object Notation (JSON), Comma-separated values (CSV) | + + ### Download log lines @@ -143,16 +155,31 @@ Click the **eye icon** to select a subset of fields to visualize in the logs lis Each field has a **stats icon**, which displays ad-hoc statistics in relation to all displayed logs. +For data sources that support log types, such as Loki, instead of a single view containing all fields, fields will be displayed grouped by their type: Indexed Labels, Parsed fields, and Structured Metadata. + #### Links Grafana provides data links or correlations, allowing you to convert any part of a log message into an internal or external link. These links enable you to navigate to related data or external resources, offering a seamless and convenient way to explore additional information. {{< figure src="/static/img/docs/explore/data-link-9-4.png" max-width="800px" caption="Data link in Explore" >}} +#### Log details modes + +There are two modes available to view log details: + +- **Inline** The default, displays log details below the log line. +- **Sidebar** Displays log details in a sidebar view. + +No matter which display mode you are currently viewing, you can change it by clicking the mode control icon. + ### Log context Log context is a feature that displays additional lines of context surrounding a log entry that matches a specific search query. This helps in understanding the context of the log entry and is similar to the `-C` parameter in the `grep` command. +If you're using Loki for your logs, to modify your log context queries, you can use the Loki log context query editor at the top of the table. You can activate this editor by clicking the menu for the log line, and selecting **Show context**. Within the **Log Context** view, you have the option to modify your search by removing one or more label filters from the log stream. If your original query used a parser, you can refine your search by leveraging extracted label filters. + +Change the **Context time window** option to look for logs within a specific time interval around your log line. + Toggle **Wrap lines** if you encounter long lines of text that make it difficult to read and analyze the context around log entries. By enabling this toggle, Grafana automatically wraps long lines of text to fit within the visible width of the viewer, making the log entries easier to read and understand. Click **Open in split view** to execute the context query for a log entry in a split screen in the Explore view. Clicking this button opens a new Explore pane with the context query displayed alongside the log entry, making it easier to analyze and understand the surrounding context. diff --git a/docs/sources/visualizations/panels-visualizations/query-transform-data/_index.md b/docs/sources/visualizations/panels-visualizations/query-transform-data/_index.md index b6c9471e3e3..5b121028404 100644 --- a/docs/sources/visualizations/panels-visualizations/query-transform-data/_index.md +++ b/docs/sources/visualizations/panels-visualizations/query-transform-data/_index.md @@ -162,6 +162,12 @@ To access your saved queries, click **+ Add from saved queries** or **Replace wi Clicking **+ Add from saved queries** adds an additional query, while clicking **Replace with saved query** updates your existing query. +{{< admonition type="note" >}} +Users with Admin and Editor roles can create and save queries for reuse. +While Admin users can edit or delete any saved queries, users with the Editor role can only edit or delete the queries they've saved. +Viewers can only reuse queries. +{{< /admonition >}} + #### Save a query To save a query you've created: diff --git a/docs/sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md b/docs/sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md index b6b3499b4d7..2a13836d246 100644 --- a/docs/sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md +++ b/docs/sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md @@ -12,12 +12,13 @@ comments: | To build this Markdown, do the following: $ cd /docs (from the root of the repository) - $ make sources/panels-visualizations/query-transform-data/transform-data/index.md + $ make sources/visualizations/panels-visualizations/query-transform-data/transform-data/index.md $ make docs Browse to http://localhost:3003/docs/grafana/latest/panels-visualizations/query-transform-data/transform-data/ Refer to ./docs/README.md "Content guidelines" for more information about editing and building these docs. + aliases: - ../../../panels/transform-data/ # /docs/grafana/next/panels/transform-data/ - ../../../panels/transform-data/about-transformation/ # /docs/grafana/next/panels/transform-data/about-transformation/ diff --git a/docs/sources/visualizations/panels-visualizations/visualizations/logs/index.md b/docs/sources/visualizations/panels-visualizations/visualizations/logs/index.md index 3af0eeda0d5..d3a93095e7a 100644 --- a/docs/sources/visualizations/panels-visualizations/visualizations/logs/index.md +++ b/docs/sources/visualizations/panels-visualizations/visualizations/logs/index.md @@ -31,7 +31,7 @@ refs: _Logs_ are structured records of events or messages generated by a system or application—that is, a series of text records with status updates from your system or app. They generally include timestamps, messages, and context information like the severity of the logged event. -The logs visualization displays these records from data sources that support logs, such as Elastic, Influx, and Loki. The logs visualization has colored indicators of log status, as well as collapsible log events that help you analyze the information generated. +The logs visualization displays these records from data sources that support logs, such as Elastic, Influx, and Loki. The logs visualization shows, by default, the timestamp, a colored string representing the log status, the log line body, as well as collapsible log events that help you analyze the information generated. {{< figure src="/media/docs/grafana/panels-visualizations/screenshot-logs-v12.3.png" max-width="750px" alt="Logs visualization" >}} @@ -100,16 +100,16 @@ Use these settings to refine your visualization: | Option | Description | | --------------- | --------------- | -| Time | Show or hide the time column. This is the timestamp associated with the log line as reported from the data source. | +| Show timestamps | Show or hide the time column. This is the timestamp associated with the log line as reported from the data source. | | Unique labels | Show or hide the unique labels column, which shows only non-common labels. | -| Common labels | Show or hide the common labels. | | Wrap lines | Turn line wrapping on or off. | -| Enable logs highlighting | Experimental. Use a predefined coloring scheme to highlight relevant parts of the log lines. Subtle colors are added to the log lines to improve readability and help with identifying important information faster. | +| Prettify JSON | Toggle the switch on to pretty print all JSON logs. This setting does not affect logs in any format other than JSON. | +| Enable highlighting | Use a predefined syntax coloring grammar to highlight relevant parts of the log lines | | Enable log details | Toggle the switch on to see an extendable area with log details including labels and detected fields. Each field or label has a stats icon to display ad-hoc statistics in relation to all displayed logs. The default setting is on. | -| Log details panel mode | Choose to display the log details in a sidebar panel or inline, below the log line. The default mode depends on viewport size: the default mode for smaller viewports is inline, while for larger ones, it's sidebar. You can also change mode dynamically in the panel by clicking the mode control. | -| Enable infinite scrolling | Request more results by scrolling to the bottom of the logs list. When you reach the bottom of the list of logs, if you continue scrolling and the displayed logs are within the selected time interval, you can request to load more logs. When the sort order is **Newest first**, you receive older logs, and when the sort order is **Oldest first** you get newer logs. | -| Show controls | Display controls to jump to the last or first log line, and filter by log level. | -| Font size | Select between the **Default** font size and **Small** font sizes.| +| Log Details panel mode | Choose to display the log details in a sidebar panel or inline, below the log line. | +| Enable infinite scrolling | Request more results by scrolling to the bottom of the logs list. | +| Show controls | Display controls to jump to the last or first log line, and filters by log level | +| Font size | Select between the default font size and small font size. | | Deduplication | Hide log messages that are duplicates of others shown, according to your selected criteria. Choose from:
  • **Exact** - Ignoring ISO datetimes.
  • **Numerical** - Ignoring only those that differ by numbers such as IPs or latencies.
  • **Signatures** - Removing successive lines with identical punctuation and white space.
| | Order | Set whether to show results **Newest first** or **Oldest first**. | diff --git a/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts b/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts index c0e6e55b5b0..952e8a3da63 100644 --- a/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts +++ b/e2e-playwright/dashboard-cujs/scope-redirect.spec.ts @@ -8,6 +8,7 @@ test.use({ scopeFilters: true, groupByVariable: true, reloadDashboardsOnParamsChange: true, + useScopesNavigationEndpoint: true, }, }); @@ -61,31 +62,6 @@ test.describe('Scope Redirect Functionality', () => { }); }); - test('should fall back to scope navigation when no redirectUrl', async ({ page, gotoDashboardPage }) => { - const scopes = testScopesWithRedirect(); - - await test.step('Navigate to dashboard and open scopes selector', async () => { - await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); - await openScopesSelector(page, scopes); - }); - - await test.step('Select scope without redirectUrl', async () => { - // Select the scope without redirectUrl directly - await selectScope(page, 'sn-redirect-fallback', scopes[1]); - }); - - await test.step('Apply scopes and verify fallback behavior', async () => { - await applyScopes(page, [scopes[1]]); - - // Should stay on current dashboard since no redirectUrl is provided - // The scope navigation fallback should not redirect (as per existing behavior) - await expect(page).toHaveURL(/\/d\/cuj-dashboard-1/); - - // Verify the scope was applied - await expect(page).toHaveURL(/scopes=scope-sn-redirect-fallback/); - }); - }); - test('should not redirect when reloading page on dashboard not in dashboard list', async ({ page, gotoDashboardPage, @@ -171,4 +147,47 @@ test.describe('Scope Redirect Functionality', () => { await expect(page).not.toHaveURL(/scopes=/); }); }); + + test('should not redirect to redirectPath when on active scope navigation', async ({ page, gotoDashboardPage }) => { + const scopes = testScopesWithRedirect(); + + await test.step('Set up scope navigation to dashboard-1', async () => { + // First, apply a scope that creates scope navigation to dashboard-1 (without redirectPath) + await gotoDashboardPage({ uid: 'cuj-dashboard-1' }); + await openScopesSelector(page, scopes); + await selectScope(page, 'sn-redirect-setup', scopes[2]); + await applyScopes(page, [scopes[2]]); + + // Verify we're on dashboard-1 with the scope applied + await expect(page).toHaveURL(/\/d\/cuj-dashboard-1/); + await expect(page).toHaveURL(/scopes=scope-sn-redirect-setup/); + }); + + await test.step('Navigate to dashboard-1 to be on active scope navigation', async () => { + // Navigate to dashboard-1 which is now a scope navigation target + await gotoDashboardPage({ + uid: 'cuj-dashboard-1', + queryParams: new URLSearchParams({ scopes: 'scope-sn-redirect-setup' }), + }); + + // Verify we're on dashboard-1 + await expect(page).toHaveURL(/\/d\/cuj-dashboard-1/); + }); + + await test.step('Apply scope with redirectPath and verify no redirect', async () => { + // Now apply a different scope that has redirectPath + // Since we're on an active scope navigation, it should NOT redirect + await openScopesSelector(page, scopes); + await selectScope(page, 'sn-redirect-with-navigation', scopes[3]); + await applyScopes(page, [scopes[3]]); + + // Verify the new scope was applied + await expect(page).toHaveURL(/scopes=scope-sn-redirect-with-navigation/); + + // Since we're already on the active scope navigation (dashboard-1), + // we should NOT redirect to redirectPath (dashboard-3) + await expect(page).toHaveURL(/\/d\/cuj-dashboard-1/); + await expect(page).not.toHaveURL(/\/d\/cuj-dashboard-3/); + }); + }); }); diff --git a/e2e-playwright/dashboard-new-layouts/dashboard-group-panels.spec.ts b/e2e-playwright/dashboard-new-layouts/dashboard-group-panels.spec.ts index c35eb03bf84..ad954267c85 100644 --- a/e2e-playwright/dashboard-new-layouts/dashboard-group-panels.spec.ts +++ b/e2e-playwright/dashboard-new-layouts/dashboard-group-panels.spec.ts @@ -419,6 +419,9 @@ test.describe( // Select tabs layout await page.getByLabel('layout-selection-option-Tabs').click(); + // confirm layout change + await dashboardPage.getByGrafanaSelector(selectors.pages.ConfirmModal.delete).click(); + await expect(dashboardPage.getByGrafanaSelector(selectors.components.Tab.title('New row'))).toBeVisible(); await expect(dashboardPage.getByGrafanaSelector(selectors.components.Tab.title('New row 1'))).toBeVisible(); await expect( @@ -757,6 +760,9 @@ test.describe( // Select rows layout await page.getByLabel('layout-selection-option-Rows').click(); + // confirm layout change + await dashboardPage.getByGrafanaSelector(selectors.pages.ConfirmModal.delete).click(); + await dashboardPage .getByGrafanaSelector(selectors.components.DashboardRow.wrapper('New tab 1')) .scrollIntoViewIfNeeded(); diff --git a/e2e-playwright/dashboard-new-layouts/dashboard-keybindings.spec.ts b/e2e-playwright/dashboard-new-layouts/dashboard-keybindings.spec.ts new file mode 100644 index 00000000000..19ad38f16d5 --- /dev/null +++ b/e2e-playwright/dashboard-new-layouts/dashboard-keybindings.spec.ts @@ -0,0 +1,59 @@ +import { test, expect } from '@grafana/plugin-e2e'; + +test.use({ + featureToggles: { + kubernetesDashboards: true, + dashboardNewLayouts: true, + }, +}); + +test.describe('Dashboard keybindings with new layouts', { tag: ['@dashboards'] }, () => { + test.use({ + viewport: { width: 1280, height: 1080 }, + }); + + test('should collapse and expand all rows', async ({ gotoDashboardPage, page, selectors }) => { + const dashboardPage = await gotoDashboardPage({ uid: 'Repeating-rows-uid/repeating-rows' }); + + const panelContents = dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.content); + await expect(panelContents).toHaveCount(5); + await expect( + dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('server = A, pod = Bob')) + ).toBeVisible(); + await expect( + dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('server = B, pod = Bob')) + ).toBeVisible(); + + // Collapse all rows using keyboard shortcut: d + Shift+C + await page.keyboard.press('d'); + await page.keyboard.press('Shift+C'); + + await expect(panelContents).toHaveCount(0); + await expect(page.getByText('server = A, pod = Bob')).toBeHidden(); + await expect(page.getByText('server = B, pod = Bob')).toBeHidden(); + + // Expand all rows using keyboard shortcut: d + Shift+E + await page.keyboard.press('d'); + await page.keyboard.press('Shift+E'); + + await expect(panelContents).toHaveCount(6); + await expect(page.getByText('server = A, pod = Bob')).toBeVisible(); + await expect(page.getByText('server = B, pod = Bob')).toBeVisible(); + }); + + test('should open panel inspect', async ({ gotoDashboardPage, page, selectors }) => { + const dashboardPage = await gotoDashboardPage({ uid: 'edediimbjhdz4b/a-tall-dashboard' }); + + // Find Panel #1 and press 'i' to open inspector + const panel1 = dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('Panel #1')); + await expect(panel1).toBeVisible(); + await panel1.press('i'); + + await expect(dashboardPage.getByGrafanaSelector(selectors.components.PanelInspector.Json.content)).toBeVisible(); + + // Press Escape to close inspector + await page.keyboard.press('Escape'); + + await expect(page.getByTestId(selectors.components.PanelInspector.Json.content)).toBeHidden(); + }); +}); diff --git a/e2e-playwright/dashboard-new-layouts/dashboards-panel-layouts.spec.ts b/e2e-playwright/dashboard-new-layouts/dashboards-panel-layouts.spec.ts index ffacaa13912..803f9d18d46 100644 --- a/e2e-playwright/dashboard-new-layouts/dashboards-panel-layouts.spec.ts +++ b/e2e-playwright/dashboard-new-layouts/dashboards-panel-layouts.spec.ts @@ -4,6 +4,8 @@ import { test, expect, E2ESelectorGroups, DashboardPage } from '@grafana/plugin- import testV2Dashboard from '../dashboards/TestV2Dashboard.json'; +import { switchToAutoGrid } from './utils'; + test.use({ featureToggles: { kubernetesDashboards: true, @@ -33,7 +35,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); await expect( dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('New panel')) @@ -64,7 +67,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); // Get initial positions - standard width should have panels on different rows const firstPanelTop = await getPanelTop(dashboardPage, selectors); @@ -124,7 +128,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); await dashboardPage .getByGrafanaSelector(selectors.components.PanelEditor.ElementEditPane.AutoGridLayout.minColumnWidth) @@ -181,7 +186,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); await dashboardPage .getByGrafanaSelector(selectors.components.PanelEditor.ElementEditPane.AutoGridLayout.maxColumns) @@ -216,7 +222,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); const regularRowHeight = await getPanelHeight(dashboardPage, selectors); @@ -271,7 +278,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); const regularRowHeight = await getPanelHeight(dashboardPage, selectors); @@ -328,7 +336,8 @@ test.describe( ).toHaveCount(3); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await page.getByLabel('layout-selection-option-Auto grid').click(); + + await switchToAutoGrid(page, dashboardPage); // Set narrow column width first to ensure panels fit horizontally await dashboardPage diff --git a/e2e-playwright/dashboard-new-layouts/dashboards-repeats-auto-grid.spec.ts b/e2e-playwright/dashboard-new-layouts/dashboards-repeats-auto-grid.spec.ts index dbba5c583c1..3e25adc6c41 100644 --- a/e2e-playwright/dashboard-new-layouts/dashboards-repeats-auto-grid.spec.ts +++ b/e2e-playwright/dashboard-new-layouts/dashboards-repeats-auto-grid.spec.ts @@ -1,6 +1,6 @@ import { Page } from 'playwright-core'; -import { test, expect } from '@grafana/plugin-e2e'; +import { test, expect, DashboardPage } from '@grafana/plugin-e2e'; import testV2DashWithRepeats from '../dashboards/V2DashWithRepeats.json'; @@ -12,6 +12,7 @@ import { getPanelPosition, importTestDashboard, goToEmbeddedPanel, + switchToAutoGrid, } from './utils'; const repeatTitleBase = 'repeat - '; @@ -42,7 +43,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('New panel')).first().click(); @@ -78,7 +79,8 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); + await saveDashboard(dashboardPage, page, selectors); await page.reload(); @@ -117,7 +119,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); // select first/original repeat panel to activate edit pane await dashboardPage @@ -148,7 +150,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await saveDashboard(dashboardPage, page, selectors); await page.reload(); @@ -214,7 +216,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await saveDashboard(dashboardPage, page, selectors); // loading directly into panel editor @@ -271,7 +273,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); // this moving repeated panel between two normal panels await movePanel(dashboardPage, selectors, `${repeatTitleBase}${repeatOptions.at(0)}`, 'New panel'); @@ -319,7 +321,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await saveDashboard(dashboardPage, page, selectors); await page.reload(); @@ -382,7 +384,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await saveDashboard(dashboardPage, page, selectors); await page.reload(); @@ -410,7 +412,7 @@ test.describe( await dashboardPage.getByGrafanaSelector(selectors.components.NavToolbar.editDashboard.editButton).click(); await dashboardPage.getByGrafanaSelector(selectors.pages.Dashboard.Sidebar.optionsButton).click(); - await switchToAutoGrid(page); + await switchToAutoGrid(page, dashboardPage); await saveDashboard(dashboardPage, page, selectors); await page.reload(); @@ -462,7 +464,3 @@ test.describe( }); } ); - -async function switchToAutoGrid(page: Page) { - await page.getByLabel('layout-selection-option-Auto grid').click(); -} diff --git a/e2e-playwright/dashboard-new-layouts/utils.ts b/e2e-playwright/dashboard-new-layouts/utils.ts index 83508063ef5..69851994812 100644 --- a/e2e-playwright/dashboard-new-layouts/utils.ts +++ b/e2e-playwright/dashboard-new-layouts/utils.ts @@ -1,5 +1,6 @@ import { Page } from '@playwright/test'; +import { selectors } from '@grafana/e2e-selectors'; import { DashboardPage, E2ESelectorGroups, expect } from '@grafana/plugin-e2e'; import testV2Dashboard from '../dashboards/TestV2Dashboard.json'; @@ -239,3 +240,12 @@ export async function getTabPosition(dashboardPage: DashboardPage, selectors: E2 const boundingBox = await tab.boundingBox(); return boundingBox; } + +export async function switchToAutoGrid(page: Page, dashboardPage: DashboardPage) { + await page.getByLabel('layout-selection-option-Auto grid').click(); + // confirm layout change if applicable + const confirmModal = dashboardPage.getByGrafanaSelector(selectors.pages.ConfirmModal.delete); + if (confirmModal) { + await confirmModal.click(); + } +} diff --git a/e2e-playwright/panels-suite/table-kitchenSink.spec.ts b/e2e-playwright/panels-suite/table-kitchenSink.spec.ts index a14085aa753..6dddba81820 100644 --- a/e2e-playwright/panels-suite/table-kitchenSink.spec.ts +++ b/e2e-playwright/panels-suite/table-kitchenSink.spec.ts @@ -343,6 +343,33 @@ test.describe('Panels test: Table - Kitchen Sink', { tag: ['@panels', '@table'] // TODO -- saving for another day. }); + test('Tests nested table expansion', async ({ gotoDashboardPage, selectors, page }) => { + const dashboardPage = await gotoDashboardPage({ + uid: DASHBOARD_UID, + queryParams: new URLSearchParams({ editPanel: '4' }), + }); + + await expect( + dashboardPage.getByGrafanaSelector(selectors.components.Panels.Panel.title('Nested tables')) + ).toBeVisible(); + + await waitForTableLoad(page); + + await expect(page.locator('[role="row"]')).toHaveCount(3); // header + 2 rows + + const firstRowExpander = dashboardPage + .getByGrafanaSelector(selectors.components.Panels.Visualization.TableNG.RowExpander) + .first(); + + await firstRowExpander.click(); + await expect(page.locator('[role="row"]')).not.toHaveCount(3); // more rows are present now, it is dynamic tho. + + // TODO: test sorting + + await firstRowExpander.click(); + await expect(page.locator('[role="row"]')).toHaveCount(3); // back to original state + }); + test('Tests tooltip interactions', async ({ gotoDashboardPage, selectors }) => { const dashboardPage = await gotoDashboardPage({ uid: DASHBOARD_UID, diff --git a/e2e-playwright/utils/scope-helpers.ts b/e2e-playwright/utils/scope-helpers.ts index 749577ecb05..fc88a79d8fa 100644 --- a/e2e-playwright/utils/scope-helpers.ts +++ b/e2e-playwright/utils/scope-helpers.ts @@ -156,13 +156,18 @@ export async function applyScopes(page: Page, scopes?: TestScope[]) { return; } - const url: string = + const dashboardBindingsUrl: string = '**/apis/scope.grafana.app/v0alpha1/namespaces/*/find/scope_dashboard_bindings?' + scopes.map((scope) => `scope=scope-${scope.name}`).join('&'); + const scopeNavigationsUrl: string = + '**/apis/scope.grafana.app/v0alpha1/namespaces/*/find/scope_navigations?' + + scopes.map((scope) => `scope=scope-${scope.name}`).join('&'); + const groups: string[] = ['Most relevant', 'Dashboards', 'Something else', '']; - await page.route(url, async (route) => { + // Mock scope_dashboard_bindings endpoint + await page.route(dashboardBindingsUrl, async (route) => { await route.fulfill({ status: 200, contentType: 'application/json', @@ -215,7 +220,52 @@ export async function applyScopes(page: Page, scopes?: TestScope[]) { }); }); - const responsePromise = page.waitForResponse((response) => response.url().includes(`/find/scope_dashboard_bindings`)); + // Mock scope_navigations endpoint + await page.route(scopeNavigationsUrl, async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + apiVersion: 'scope.grafana.app/v0alpha1', + items: scopes.flatMap((scope) => { + const navigations: Array<{ + kind: string; + apiVersion: string; + metadata: { name: string; resourceVersion: string; creationTimestamp: string }; + spec: { url: string; scope: string }; + status: { title: string }; + }> = []; + + // Create a scope navigation if dashboardUid is provided + if (scope.dashboardUid && scope.addLinks) { + navigations.push({ + kind: 'ScopeNavigation', + apiVersion: 'scope.grafana.app/v0alpha1', + metadata: { + name: `scope-${scope.name}-nav`, + resourceVersion: '1', + creationTimestamp: 'stamp', + }, + spec: { + url: `/d/${scope.dashboardUid}`, + scope: `scope-${scope.name}`, + }, + status: { + title: scope.dashboardTitle ?? scope.title, + }, + }); + } + + return navigations; + }), + }), + }); + }); + + const responsePromise = page.waitForResponse( + (response) => + response.url().includes(`/find/scope_dashboard_bindings`) || response.url().includes(`/find/scope_navigations`) + ); const scopeRequestPromises: Array> = []; for (const scope of scopes) { diff --git a/e2e-playwright/utils/scopes.ts b/e2e-playwright/utils/scopes.ts index c5b141d4eb7..73a29a5da95 100644 --- a/e2e-playwright/utils/scopes.ts +++ b/e2e-playwright/utils/scopes.ts @@ -124,5 +124,23 @@ export const testScopesWithRedirect = (): TestScope[] => { dashboardTitle: 'CUJ Dashboard 2', addLinks: true, }, + { + name: 'sn-redirect-setup', + title: 'Setup Navigation', + // No redirectPath - used to set up scope navigation to dashboard-1 + filters: [{ key: 'namespace', operator: 'equals', value: 'setup-nav' }], + dashboardUid: 'cuj-dashboard-1', // Creates scope navigation to this dashboard + dashboardTitle: 'CUJ Dashboard 1', + addLinks: true, + }, + { + name: 'sn-redirect-with-navigation', + title: 'Redirect With Navigation', + redirectPath: '/d/cuj-dashboard-3', // Redirect target + filters: [{ key: 'namespace', operator: 'equals', value: 'redirect-with-nav' }], + dashboardUid: 'cuj-dashboard-1', // Creates scope navigation to this dashboard + dashboardTitle: 'CUJ Dashboard 1', + addLinks: true, + }, ]; }; diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 206fc713861..924a548883f 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -397,7 +397,7 @@ }, "packages/grafana-prometheus/src/language_provider.ts": { "@typescript-eslint/no-explicit-any": { - "count": 7 + "count": 2 } }, "packages/grafana-prometheus/src/language_utils.ts": { @@ -669,7 +669,7 @@ }, "packages/grafana-ui/src/components/InteractiveTable/InteractiveTable.story.tsx": { "no-restricted-syntax": { - "count": 3 + "count": 2 } }, "packages/grafana-ui/src/components/JSONFormatter/json_explorer/json_explorer.ts": { @@ -786,11 +786,6 @@ "count": 13 } }, - "packages/grafana-ui/src/components/Sparkline/Sparkline.tsx": { - "react-prefer-function-component/react-prefer-function-component": { - "count": 1 - } - }, "packages/grafana-ui/src/components/Table/Cells/TableCell.tsx": { "@typescript-eslint/consistent-type-assertions": { "count": 3 @@ -809,11 +804,6 @@ "count": 2 } }, - "packages/grafana-ui/src/components/Table/TableNG/utils.ts": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - } - }, "packages/grafana-ui/src/components/Table/TableRT/Filter.tsx": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -886,11 +876,6 @@ "count": 1 } }, - "packages/grafana-ui/src/components/VizLegend/VizLegend.story.tsx": { - "no-restricted-syntax": { - "count": 1 - } - }, "packages/grafana-ui/src/components/VizLegend/types.ts": { "@typescript-eslint/no-explicit-any": { "count": 2 @@ -1447,22 +1432,6 @@ "count": 1 } }, - "public/app/features/alerting/unified/components/receivers/form/ChannelOptions.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - }, - "@typescript-eslint/no-explicit-any": { - "count": 2 - }, - "no-restricted-syntax": { - "count": 1 - } - }, - "public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx": { - "no-restricted-syntax": { - "count": 1 - } - }, "public/app/features/alerting/unified/components/receivers/form/CloudCommonChannelSettings.tsx": { "no-restricted-syntax": { "count": 1 @@ -1473,17 +1442,6 @@ "count": 1 } }, - "public/app/features/alerting/unified/components/receivers/form/ReceiverForm.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 2 - }, - "@typescript-eslint/no-explicit-any": { - "count": 1 - }, - "no-restricted-syntax": { - "count": 1 - } - }, "public/app/features/alerting/unified/components/receivers/form/fields/OptionField.tsx": { "@typescript-eslint/consistent-type-assertions": { "count": 1 @@ -1832,7 +1790,7 @@ }, "public/app/features/dashboard-scene/edit-pane/DashboardEditPaneSplitter.tsx": { "react-hooks/rules-of-hooks": { - "count": 4 + "count": 5 } }, "public/app/features/dashboard-scene/inspect/HelpWizard/HelpWizard.tsx": { @@ -1845,11 +1803,6 @@ "count": 1 } }, - "public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx": { - "no-restricted-syntax": { - "count": 1 - } - }, "public/app/features/dashboard-scene/pages/DashboardScenePage.tsx": { "@typescript-eslint/consistent-type-assertions": { "count": 2 @@ -2887,11 +2840,6 @@ "count": 1 } }, - "public/app/features/panel/components/VizTypePicker/PanelTypeCard.tsx": { - "@grafana/no-aria-label-selectors": { - "count": 1 - } - }, "public/app/features/panel/panellinks/linkSuppliers.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 @@ -2930,11 +2878,6 @@ "count": 1 } }, - "public/app/features/plugins/admin/components/PluginDetailsPage.tsx": { - "@typescript-eslint/consistent-type-assertions": { - "count": 1 - } - }, "public/app/features/plugins/admin/helpers.ts": { "no-restricted-syntax": { "count": 2 @@ -3132,11 +3075,6 @@ "count": 2 } }, - "public/app/features/teams/TeamGroupSync.tsx": { - "react-prefer-function-component/react-prefer-function-component": { - "count": 1 - } - }, "public/app/features/templating/fieldAccessorCache.ts": { "@typescript-eslint/no-explicit-any": { "count": 1 diff --git a/go.mod b/go.mod index 40e3288158d..91d8a0a42fc 100644 --- a/go.mod +++ b/go.mod @@ -48,7 +48,7 @@ require ( github.com/blugelabs/bluge_segment_api v0.2.0 // @grafana/grafana-backend-group github.com/bradfitz/gomemcache v0.0.0-20230905024940-24af94b03874 // @grafana/grafana-backend-group github.com/bwmarrin/snowflake v0.3.0 // @grafana/grafana-app-platform-squad - github.com/centrifugal/centrifuge v0.37.2 // @grafana/grafana-app-platform-squad + github.com/centrifugal/centrifuge v0.38.0 // @grafana/grafana-app-platform-squad github.com/crewjam/saml v0.4.14 // @grafana/identity-access-team github.com/dgraph-io/badger/v4 v4.7.0 // @grafana/grafana-search-and-storage github.com/dlmiddlecote/sqlstats v1.0.2 // @grafana/grafana-backend-group @@ -87,7 +87,7 @@ require ( github.com/googleapis/gax-go/v2 v2.15.0 // @grafana/grafana-backend-group github.com/gorilla/mux v1.8.1 // @grafana/grafana-backend-group github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // @grafana/grafana-app-platform-squad - github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba // @grafana/alerting-backend + github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 // @grafana/alerting-backend github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f // @grafana/identity-access-team github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 // @grafana/identity-access-team github.com/grafana/dataplane/examples v0.0.1 // @grafana/observability-metrics @@ -386,7 +386,7 @@ require ( github.com/caio/go-tdigest v3.1.0+incompatible // indirect github.com/cenkalti/backoff/v4 v4.3.0 // @grafana/alerting-backend github.com/cenkalti/backoff/v5 v5.0.3 // indirect - github.com/centrifugal/protocol v0.16.2 // indirect + github.com/centrifugal/protocol v0.17.0 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cheekybits/genny v1.0.0 // indirect @@ -562,7 +562,7 @@ require ( github.com/prometheus/procfs v0.16.1 // indirect github.com/protocolbuffers/txtpbfmt v0.0.0-20241112170944-20d2c9ebc01d // indirect github.com/puzpuzpuz/xsync/v2 v2.5.1 // indirect - github.com/redis/rueidis v1.0.64 // indirect + github.com/redis/rueidis v1.0.68 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.14.1 // indirect @@ -687,6 +687,7 @@ require ( github.com/moby/term v0.5.0 // indirect github.com/morikuni/aec v1.0.0 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/quagmt/udecimal v1.9.0 // indirect github.com/shirou/gopsutil/v4 v4.25.3 // indirect github.com/tklauser/go-sysconf v0.3.14 // indirect github.com/tklauser/numcpus v0.8.0 // indirect diff --git a/go.sum b/go.sum index f4f91335d2b..d056a11c1cb 100644 --- a/go.sum +++ b/go.sum @@ -1006,10 +1006,10 @@ github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F9 github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= -github.com/centrifugal/centrifuge v0.37.2 h1:rerQNvDfYN2FZEkVtb/hvGV7SIrJfEQrKF3MaE8GDlo= -github.com/centrifugal/centrifuge v0.37.2/go.mod h1:aj4iRJGhzi3SlL8iUtVezxway1Xf8g+hmNQkLLO7sS8= -github.com/centrifugal/protocol v0.16.2 h1:KoIHgDeX1fFxyxQoKW+6E8ZTCf5mwGm8JyGoJ5NBMbQ= -github.com/centrifugal/protocol v0.16.2/go.mod h1:Q7OpS/8HMXDnL7f9DpNx24IhG96MP88WPpVTTCdrokI= +github.com/centrifugal/centrifuge v0.38.0 h1:UJTowwc5lSwnpvd3vbrTseODbU7osSggN67RTrJ8EfQ= +github.com/centrifugal/centrifuge v0.38.0/go.mod h1:rcZLARnO5GXOeE9qG7iIPMvERxESespqkSX4cGLCAzo= +github.com/centrifugal/protocol v0.17.0 h1:hD0WczyiG7zrVJcgkQsd5/nhfFXt0Y04SJHV2Z7B1rg= +github.com/centrifugal/protocol v0.17.0/go.mod h1:9MdiYyjw5Bw1+d5Sp4Y0NK+qiuTNyd88nrHJsUUh8k4= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -1613,8 +1613,8 @@ github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7Fsg github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba h1:psKWNETD5nGxmFAlqnWsXoRyUwSa2GHNEMSEDKGKfQ4= -github.com/grafana/alerting v0.0.0-20251204145817-de8c2bbf9eba/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7 h1:ZzG/gCclEit9w0QUfQt9GURcOycAIGcsQAhY1u0AEX0= +github.com/grafana/alerting v0.0.0-20251212143239-491433b332b7/go.mod h1:l7v67cgP7x72ajB9UPZlumdrHqNztpKoqQ52cU8T3LU= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f h1:Cbm6OKkOcJ+7CSZsGsEJzktC/SIa5bxVeYKQLuYK86o= github.com/grafana/authlib v0.0.0-20250930082137-a40e2c2b094f/go.mod h1:axY0cdOg3q0TZHwpHnIz5x16xZ8ZBxJHShsSHHXcHQg= github.com/grafana/authlib/types v0.0.0-20251119142549-be091cf2f4d4 h1:Muoy+FMGrHj3GdFbvsMzUT7eusgii9PKf9L1ZaXDDbY= @@ -2334,11 +2334,13 @@ github.com/puzpuzpuz/xsync/v2 v2.5.1 h1:mVGYAvzDSu52+zaGyNjC+24Xw2bQi3kTr4QJ6N9p github.com/puzpuzpuz/xsync/v2 v2.5.1/go.mod h1:gD2H2krq/w52MfPLE+Uy64TzJDVY7lP2znR9qmR35kU= github.com/puzpuzpuz/xsync/v4 v4.2.0 h1:dlxm77dZj2c3rxq0/XNvvUKISAmovoXF4a4qM6Wvkr0= github.com/puzpuzpuz/xsync/v4 v4.2.0/go.mod h1:VJDmTCJMBt8igNxnkQd86r+8KUeN1quSfNKu5bLYFQo= +github.com/quagmt/udecimal v1.9.0 h1:TLuZiFeg0HhS6X8VDa78Y6XTaitZZfh+z5q4SXMzpDQ= +github.com/quagmt/udecimal v1.9.0/go.mod h1:ScmJ/xTGZcEoYiyMMzgDLn79PEJHcMBiJ4NNRT3FirA= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/redis/go-redis/v9 v9.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE= github.com/redis/go-redis/v9 v9.14.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= -github.com/redis/rueidis v1.0.64 h1:XqgbueDuNV3qFdVdQwAHJl1uNt90zUuAJuzqjH4cw6Y= -github.com/redis/rueidis v1.0.64/go.mod h1:Lkhr2QTgcoYBhxARU7kJRO8SyVlgUuEkcJO1Y8MCluA= +github.com/redis/rueidis v1.0.68 h1:gept0E45JGxVigWb3zoWHvxEc4IOC7kc4V/4XvN8eG8= +github.com/redis/rueidis v1.0.68/go.mod h1:Lkhr2QTgcoYBhxARU7kJRO8SyVlgUuEkcJO1Y8MCluA= github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= diff --git a/go.work.sum b/go.work.sum index eaa5da46cf0..2e51fd8a06e 100644 --- a/go.work.sum +++ b/go.work.sum @@ -267,8 +267,6 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6 h1:K72hopUosKG3ntOPNG4OzzbuhxGuVf06 git.sr.ht/~sbinet/gg v0.6.0 h1:RIzgkizAk+9r7uPzf/VfbJHBMKUr0F5hRFxTUGMnt38= git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm94= github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20230306123547-8075edf89bb0/go.mod h1:OahwfttHWG6eJ0clwcfBAHoDI6X/LV/15hx/wlMZSrU= github.com/Azure/azure-amqp-common-go/v3 v3.2.3 h1:uDF62mbd9bypXWi19V1bN5NZEO84JqgmI5G73ibAmrk= github.com/Azure/azure-amqp-common-go/v3 v3.2.3/go.mod h1:7rPmbSfszeovxGfc5fSAXE4ehlXQZHpMja2OtxC2Tas= @@ -528,6 +526,8 @@ github.com/campoy/embedmd v1.0.0 h1:V4kI2qTJJLf4J29RzI/MAt2c3Bl4dQSYPuflzwFH2hY= github.com/campoy/embedmd v1.0.0/go.mod h1:oxyr9RCiSXg0M3VJ3ks0UGfp98BpSSGr0kpiX3MzVl8= github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/census-instrumentation/opencensus-proto v0.4.1 h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g= +github.com/centrifugal/centrifuge v0.37.2/go.mod h1:aj4iRJGhzi3SlL8iUtVezxway1Xf8g+hmNQkLLO7sS8= +github.com/centrifugal/protocol v0.16.2/go.mod h1:Q7OpS/8HMXDnL7f9DpNx24IhG96MP88WPpVTTCdrokI= github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo= @@ -604,8 +604,6 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= -github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= -github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/creasty/defaults v1.8.0 h1:z27FJxCAa0JKt3utc0sCImAEb+spPucmKoOdLHvHYKk= github.com/creasty/defaults v1.8.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbDy08fPzYM= github.com/crewjam/httperr v0.2.0 h1:b2BfXR8U3AlIHwNeFFvZ+BV1LFvKLlzMjzaTnZMybNo= @@ -712,6 +710,8 @@ github.com/envoyproxy/go-control-plane/envoy v1.32.3/go.mod h1:F6hWupPfh75TBXGKA github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= github.com/envoyproxy/protoc-gen-validate v1.0.4/go.mod h1:qys6tmnRsYrQqIhm2bvKZH4Blx/1gTIZ2UKVY1M+Yew= github.com/envoyproxy/protoc-gen-validate v1.1.0/go.mod h1:sXRDRVmzEbkM7CVcM06s9shE/m23dg3wzjl0UWqJ2q4= +github.com/ericlagergren/decimal v0.0.0-20240411145413-00de7ca16731 h1:R/ZjJpjQKsZ6L/+Gf9WHbt31GG8NMVcpRqUE+1mMIyo= +github.com/ericlagergren/decimal v0.0.0-20240411145413-00de7ca16731/go.mod h1:M9R1FoZ3y//hwwnJtO51ypFGwm8ZfpxPT/ZLtO1mcgQ= github.com/evanphx/json-patch v5.6.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= @@ -928,6 +928,7 @@ github.com/grafana/grafana/apps/preferences v0.0.0-20250805120145-0c5a00302924 h github.com/grafana/grafana/apps/preferences v0.0.0-20250805120145-0c5a00302924/go.mod h1:NQlHMO5fHhjexw71wVjv522532NRvFg5F4tcjUEktjs= github.com/grafana/grafana/apps/preferences v0.0.0-20250805123034-066163d71001 h1:y2AHkdji2I+zXv8rsSC8OjWEzJJjqW5OlmCsZR5+RuU= github.com/grafana/grafana/apps/preferences v0.0.0-20250805123034-066163d71001/go.mod h1:NQlHMO5fHhjexw71wVjv522532NRvFg5F4tcjUEktjs= +github.com/grafana/grafana/apps/quotas v0.0.0-20251209171149-4b999cd94388/go.mod h1:M7bV60iRB61y0ISPG1HX/oNLZtlh0ZF22rUYwNkAKjo= github.com/grafana/grafana/pkg/aggregator v0.0.0-20250121113133-e747350fee2d/go.mod h1:1sq0guad+G4SUTlBgx7SXfhnzy7D86K/LcVOtiQCiMA= github.com/grafana/grafana/pkg/semconv v0.0.0-20250121113133-e747350fee2d/go.mod h1:tfLnBpPYgwrBMRz4EXqPCZJyCjEG4Ev37FSlXnocJ2c= github.com/grafana/grafana/pkg/storage/unified/apistore v0.0.0-20250121113133-e747350fee2d/go.mod h1:CXpwZ3Mkw6xVlGKc0SqUxqXCP3Uv182q6qAQnLaLxRg= @@ -1333,6 +1334,7 @@ github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgc github.com/pkg/sftp v1.13.1 h1:I2qBYMChEhIjOgazfJmV3/mZM256btk6wkCDRmW7JYs= github.com/pkg/xattr v0.4.10 h1:Qe0mtiNFHQZ296vRgUjRCoPHPqH7VdTOrZx3g0T+pGA= github.com/pkg/xattr v0.4.10/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU= +github.com/planetscale/vtprotobuf v0.6.0/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/pquerna/cachecontrol v0.1.0 h1:yJMy84ti9h/+OEWa752kBTKv4XC30OtVVHYv/8cTqKc= @@ -1369,6 +1371,7 @@ github.com/rabbitmq/amqp091-go v1.9.0 h1:qrQtyzB4H8BQgEuJwhmVQqVHB9O4+MNDJCCAcpc github.com/rabbitmq/amqp091-go v1.9.0/go.mod h1:+jPrT9iY2eLjRaMSRHUhc3z14E/l85kv/f+6luSD3pc= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/redis/rueidis v1.0.64/go.mod h1:Lkhr2QTgcoYBhxARU7kJRO8SyVlgUuEkcJO1Y8MCluA= github.com/relvacode/iso8601 v1.6.0 h1:eFXUhMJN3Gz8Rcq82f9DTMW0svjtAVuIEULglM7QHTU= github.com/relvacode/iso8601 v1.6.0/go.mod h1:FlNp+jz+TXpyRqgmM7tnzHHzBnz776kmAH2h3sZCn0I= github.com/richardartoul/molecule v1.0.0 h1:+LFA9cT7fn8KF39zy4dhOnwcOwRoqKiBkPqKqya+8+U= @@ -1400,6 +1403,7 @@ github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtm github.com/schollz/progressbar/v3 v3.14.6 h1:GyjwcWBAf+GFDMLziwerKvpuS7ZF+mNTAXIB2aspiZs= github.com/schollz/progressbar/v3 v3.14.6/go.mod h1:Nrzpuw3Nl0srLY0VlTvC4V6RL50pcEymjy6qyJAaLa0= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= +github.com/segmentio/asm v1.1.4/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/fasthash v1.0.3 h1:EI9+KE1EwvMLBWwjpRDc+fEM+prwxDYbslddQGtrmhM= github.com/segmentio/fasthash v1.0.3/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= github.com/segmentio/parquet-go v0.0.0-20220811205829-7efc157d28af/go.mod h1:PxYdAI6cGd+s1j4hZDQbz3VFgobF5fDA0weLeNWKTE4= @@ -1938,6 +1942,7 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= @@ -2004,6 +2009,7 @@ golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ= golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0= golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw= golang.org/x/term v0.35.0/go.mod h1:TPGtkTLesOwf2DE8CgVYiZinHAOuy5AYUYT1lENIZnA= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= @@ -2078,9 +2084,9 @@ google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go. google.golang.org/genproto/googleapis/api v0.0.0-20250818200422-3122310a409c/go.mod h1:ea2MjsO70ssTfCjiwHgI0ZFqcw45Ksuk2ckf9G468GA= google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE= google.golang.org/genproto/googleapis/api v0.0.0-20250929231259-57b25ae835d4/go.mod h1:NnuHhy+bxcg30o7FnVAZbXsPHUDQ9qKWAQKCD7VxFtk= -google.golang.org/genproto/googleapis/api v0.0.0-20251022142026-3a174f9686a8/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= google.golang.org/genproto/googleapis/bytestream v0.0.0-20250603155806-513f23925822 h1:zWFRixYR5QlotL+Uv3YfsPRENIrQFXiGs+iwqel6fOQ= google.golang.org/genproto/googleapis/bytestream v0.0.0-20250603155806-513f23925822/go.mod h1:h6yxum/C2qRb4txaZRLDHK8RyS0H/o2oEDeKY4onY/Y= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M= google.golang.org/genproto/googleapis/rpc v0.0.0-20231002182017-d307bd883b97/go.mod h1:v7nGkzlmW8P3n/bKmWBn2WpBjpOEx8Q6gMueudAmKfY= google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:oQ5rr10WTTMvP4A36n8JpR1OrO1BEiV4f78CneXZxkA= google.golang.org/genproto/googleapis/rpc v0.0.0-20240123012728-ef4313101c80/go.mod h1:PAREbraiVEVGVdTZsVWjSbbTtSyGbAgIIvni8a8CD5s= @@ -2108,10 +2114,10 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20250826171959-ef028d996bc1/go. google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090/go.mod h1:GmFNa4BdJZ2a8G+wCe9Bg3wwThLrJun751XstdJt5Og= google.golang.org/genproto/googleapis/rpc v0.0.0-20250929231259-57b25ae835d4/go.mod h1:HSkG/KdJWusxU1F6CNrwNDjBMgisKxGnc5dAZfT0mjQ= google.golang.org/genproto/googleapis/rpc v0.0.0-20251014184007-4626949a642f/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251022142026-3a174f9686a8/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= google.golang.org/genproto/googleapis/rpc v0.0.0-20251103181224-f26f9409b101/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA= +google.golang.org/grpc v1.58.2/go.mod h1:tgX3ZQDlNJGU96V6yHh1T/JeoBQ2TXdr43YbYSsCJk0= google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= google.golang.org/grpc v1.61.0/go.mod h1:VUbo7IFqmF1QtCAstipjG0GIoq49KvMe9+h1jFLBNJs= google.golang.org/grpc v1.62.1/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= diff --git a/kinds/dashboard/dashboard_kind.cue b/kinds/dashboard/dashboard_kind.cue index 454d02f270f..08b7a1b2b6e 100644 --- a/kinds/dashboard/dashboard_kind.cue +++ b/kinds/dashboard/dashboard_kind.cue @@ -702,6 +702,10 @@ lineage: schemas: [{ // Field options allow you to change how the data is displayed in your visualizations. fieldConfig?: #FieldConfigSource + + // When a panel is migrated from a previous version (Angular to React), this field is set to the original panel type. + // This is used to determine the original panel type when migrating to a new version so the plugin migration can be applied. + autoMigrateFrom?: string } @cuetsy(kind="interface") @grafana(TSVeneer="type") @grafanamaturity(NeedsExpertReview) // The data model used in Grafana, namely the data frame, is a columnar-oriented table structure that unifies both time series and table query results. diff --git a/package.json b/package.json index 683ed2373de..7a21333b222 100644 --- a/package.json +++ b/package.json @@ -124,7 +124,6 @@ "@types/eslint": "9.6.1", "@types/eslint-scope": "^8.0.0", "@types/file-saver": "2.0.7", - "@types/glob": "^9.0.0", "@types/google.analytics": "^0.0.46", "@types/gtag.js": "^0.0.20", "@types/history": "4.7.11", @@ -290,7 +289,7 @@ "@grafana/google-sdk": "0.3.5", "@grafana/i18n": "workspace:*", "@grafana/lezer-logql": "0.2.9", - "@grafana/llm": "0.22.1", + "@grafana/llm": "1.0.1", "@grafana/monaco-logql": "^0.0.8", "@grafana/o11y-ds-frontend": "workspace:*", "@grafana/plugin-ui": "^0.11.1", @@ -460,7 +459,8 @@ "gitconfiglocal": "2.1.0", "tmp@npm:^0.0.33": "~0.2.1", "js-yaml@npm:4.1.0": "^4.1.0", - "js-yaml@npm:=4.1.0": "^4.1.0" + "js-yaml@npm:=4.1.0": "^4.1.0", + "nodemailer": "7.0.7" }, "workspaces": { "packages": [ diff --git a/packages/grafana-api-clients/src/clients/rtkq/iam/v0alpha1/endpoints.gen.ts b/packages/grafana-api-clients/src/clients/rtkq/iam/v0alpha1/endpoints.gen.ts index 8b0690f57ba..790db19a6e3 100644 --- a/packages/grafana-api-clients/src/clients/rtkq/iam/v0alpha1/endpoints.gen.ts +++ b/packages/grafana-api-clients/src/clients/rtkq/iam/v0alpha1/endpoints.gen.ts @@ -165,6 +165,19 @@ const injectedRtkApi = api }), providesTags: ['Search'], }), + getSearchUsers: build.query({ + query: (queryArg) => ({ + url: `/searchUsers`, + params: { + query: queryArg.query, + limit: queryArg.limit, + page: queryArg.page, + offset: queryArg.offset, + sort: queryArg.sort, + }, + }), + providesTags: ['Search'], + }), listServiceAccount: build.query({ query: (queryArg) => ({ url: `/serviceaccounts`, @@ -896,6 +909,18 @@ export type GetSearchTeamsApiArg = { /** page number to start from */ page?: number; }; +export type GetSearchUsersApiResponse = unknown; +export type GetSearchUsersApiArg = { + query?: string; + /** number of results to return */ + limit?: number; + /** page number (starting from 1) */ + page?: number; + /** number of results to skip */ + offset?: number; + /** sortable field */ + sort?: string; +}; export type ListServiceAccountApiResponse = /** status 200 OK */ ServiceAccountList; export type ListServiceAccountApiArg = { /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ @@ -2067,6 +2092,9 @@ export type UserSpec = { role: string; title: string; }; +export type UserStatus = { + lastSeenAt: number; +}; export type User = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; @@ -2075,6 +2103,7 @@ export type User = { metadata: ObjectMeta; /** Spec is the spec of the User */ spec: UserSpec; + status: UserStatus; }; export type UserList = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ @@ -2120,6 +2149,8 @@ export const { useUpdateExternalGroupMappingMutation, useGetSearchTeamsQuery, useLazyGetSearchTeamsQuery, + useGetSearchUsersQuery, + useLazyGetSearchUsersQuery, useListServiceAccountQuery, useLazyListServiceAccountQuery, useCreateServiceAccountMutation, diff --git a/packages/grafana-api-clients/src/clients/rtkq/legacy/endpoints.gen.ts b/packages/grafana-api-clients/src/clients/rtkq/legacy/endpoints.gen.ts index 5ba0b811289..4f17bb46ecf 100644 --- a/packages/grafana-api-clients/src/clients/rtkq/legacy/endpoints.gen.ts +++ b/packages/grafana-api-clients/src/clients/rtkq/legacy/endpoints.gen.ts @@ -658,10 +658,6 @@ const injectedRtkApi = api query: (queryArg) => ({ url: `/dashboards/db`, method: 'POST', body: queryArg.saveDashboardCommand }), invalidatesTags: ['dashboards'], }), - getHomeDashboard: build.query({ - query: () => ({ url: `/dashboards/home` }), - providesTags: ['dashboards'], - }), importDashboard: build.mutation({ query: (queryArg) => ({ url: `/dashboards/import`, method: 'POST', body: queryArg.importDashboardRequest }), invalidatesTags: ['dashboards'], @@ -2574,8 +2570,6 @@ export type PostDashboardApiResponse = /** status 200 (empty) */ { export type PostDashboardApiArg = { saveDashboardCommand: SaveDashboardCommand; }; -export type GetHomeDashboardApiResponse = /** status 200 (empty) */ GetHomeDashboardResponse; -export type GetHomeDashboardApiArg = void; export type ImportDashboardApiResponse = /** status 200 (empty) */ ImportDashboardResponseResponseObjectReturnedWhenImportingADashboard; export type ImportDashboardApiArg = { @@ -3446,16 +3440,16 @@ export type RemoveTeamGroupApiQueryApiResponse = /** status 200 An OKResponse is returned if the request was successful. */ SuccessResponseBody; export type RemoveTeamGroupApiQueryApiArg = { groupId?: string; - teamId: number; + teamId: string; }; export type GetTeamGroupsApiApiResponse = /** status 200 (empty) */ TeamGroupDto[]; export type GetTeamGroupsApiApiArg = { - teamId: number; + teamId: string; }; export type AddTeamGroupApiApiResponse = /** status 200 An OKResponse is returned if the request was successful. */ SuccessResponseBody; export type AddTeamGroupApiApiArg = { - teamId: number; + teamId: string; teamGroupMapping: TeamGroupMapping; }; export type SearchTeamGroupsApiResponse = /** status 200 (empty) */ SearchTeamGroupsQueryResult; @@ -4399,51 +4393,6 @@ export type SaveDashboardCommand = { overwrite?: boolean; userId?: number; }; -export type AnnotationActions = { - canAdd?: boolean; - canDelete?: boolean; - canEdit?: boolean; -}; -export type AnnotationPermission = { - dashboard?: AnnotationActions; - organization?: AnnotationActions; -}; -export type DashboardMeta = { - annotationsPermissions?: AnnotationPermission; - apiVersion?: string; - canAdmin?: boolean; - canDelete?: boolean; - canEdit?: boolean; - canSave?: boolean; - canStar?: boolean; - created?: string; - createdBy?: string; - expires?: string; - /** Deprecated: use FolderUID instead */ - folderId?: number; - folderTitle?: string; - folderUid?: string; - folderUrl?: string; - hasAcl?: boolean; - isFolder?: boolean; - isSnapshot?: boolean; - isStarred?: boolean; - provisioned?: boolean; - provisionedExternalId?: string; - publicDashboardEnabled?: boolean; - slug?: string; - type?: string; - updated?: string; - updatedBy?: string; - url?: string; - version?: number; -}; -export type GetHomeDashboardResponse = { - dashboard?: Json; - meta?: DashboardMeta; -} & { - redirectUri?: string; -}; export type ImportDashboardResponseResponseObjectReturnedWhenImportingADashboard = { dashboardId?: number; description?: string; @@ -4535,6 +4484,45 @@ export type PublicDashboardDto = { timeSelectionEnabled?: boolean; uid?: string; }; +export type AnnotationActions = { + canAdd?: boolean; + canDelete?: boolean; + canEdit?: boolean; +}; +export type AnnotationPermission = { + dashboard?: AnnotationActions; + organization?: AnnotationActions; +}; +export type DashboardMeta = { + annotationsPermissions?: AnnotationPermission; + apiVersion?: string; + canAdmin?: boolean; + canDelete?: boolean; + canEdit?: boolean; + canSave?: boolean; + canStar?: boolean; + created?: string; + createdBy?: string; + expires?: string; + /** Deprecated: use FolderUID instead */ + folderId?: number; + folderTitle?: string; + folderUid?: string; + folderUrl?: string; + hasAcl?: boolean; + isFolder?: boolean; + isSnapshot?: boolean; + isStarred?: boolean; + provisioned?: boolean; + provisionedExternalId?: string; + publicDashboardEnabled?: boolean; + slug?: string; + type?: string; + updated?: string; + updatedBy?: string; + url?: string; + version?: number; +}; export type DashboardFullWithMeta = { dashboard?: Json; meta?: DashboardMeta; @@ -6619,8 +6607,6 @@ export const { useSearchDashboardSnapshotsQuery, useLazySearchDashboardSnapshotsQuery, usePostDashboardMutation, - useGetHomeDashboardQuery, - useLazyGetHomeDashboardQuery, useImportDashboardMutation, useInterpolateDashboardMutation, useListPublicDashboardsQuery, diff --git a/packages/grafana-api-clients/src/clients/rtkq/logsdrilldown/v1alpha1/endpoints.gen.ts b/packages/grafana-api-clients/src/clients/rtkq/logsdrilldown/v1alpha1/endpoints.gen.ts index 835194b59e5..22464a2b3fa 100644 --- a/packages/grafana-api-clients/src/clients/rtkq/logsdrilldown/v1alpha1/endpoints.gen.ts +++ b/packages/grafana-api-clients/src/clients/rtkq/logsdrilldown/v1alpha1/endpoints.gen.ts @@ -1,5 +1,10 @@ import { api } from './baseAPI'; -export const addTagTypes = ['API Discovery', 'LogsDrilldownDefaults', 'LogsDrilldown'] as const; +export const addTagTypes = [ + 'API Discovery', + 'LogsDrilldownDefaultColumns', + 'LogsDrilldownDefaults', + 'LogsDrilldown', +] as const; const injectedRtkApi = api .enhanceEndpoints({ addTagTypes, @@ -10,6 +15,183 @@ const injectedRtkApi = api query: () => ({ url: `/` }), providesTags: ['API Discovery'], }), + listLogsDrilldownDefaultColumns: build.query< + ListLogsDrilldownDefaultColumnsApiResponse, + ListLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['LogsDrilldownDefaultColumns'], + }), + createLogsDrilldownDefaultColumns: build.mutation< + CreateLogsDrilldownDefaultColumnsApiResponse, + CreateLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns`, + method: 'POST', + body: queryArg.logsDrilldownDefaultColumns, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + deletecollectionLogsDrilldownDefaultColumns: build.mutation< + DeletecollectionLogsDrilldownDefaultColumnsApiResponse, + DeletecollectionLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + getLogsDrilldownDefaultColumns: build.query< + GetLogsDrilldownDefaultColumnsApiResponse, + GetLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['LogsDrilldownDefaultColumns'], + }), + replaceLogsDrilldownDefaultColumns: build.mutation< + ReplaceLogsDrilldownDefaultColumnsApiResponse, + ReplaceLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}`, + method: 'PUT', + body: queryArg.logsDrilldownDefaultColumns, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + deleteLogsDrilldownDefaultColumns: build.mutation< + DeleteLogsDrilldownDefaultColumnsApiResponse, + DeleteLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + updateLogsDrilldownDefaultColumns: build.mutation< + UpdateLogsDrilldownDefaultColumnsApiResponse, + UpdateLogsDrilldownDefaultColumnsApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + getLogsDrilldownDefaultColumnsStatus: build.query< + GetLogsDrilldownDefaultColumnsStatusApiResponse, + GetLogsDrilldownDefaultColumnsStatusApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}/status`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['LogsDrilldownDefaultColumns'], + }), + replaceLogsDrilldownDefaultColumnsStatus: build.mutation< + ReplaceLogsDrilldownDefaultColumnsStatusApiResponse, + ReplaceLogsDrilldownDefaultColumnsStatusApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}/status`, + method: 'PUT', + body: queryArg.logsDrilldownDefaultColumns, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), + updateLogsDrilldownDefaultColumnsStatus: build.mutation< + UpdateLogsDrilldownDefaultColumnsStatusApiResponse, + UpdateLogsDrilldownDefaultColumnsStatusApiArg + >({ + query: (queryArg) => ({ + url: `/logsdrilldowndefaultcolumns/${queryArg.name}/status`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['LogsDrilldownDefaultColumns'], + }), listLogsDrilldownDefaults: build.query({ query: (queryArg) => ({ url: `/logsdrilldowndefaults`, @@ -340,6 +522,218 @@ const injectedRtkApi = api export { injectedRtkApi as generatedAPI }; export type GetApiResourcesApiResponse = /** status 200 OK */ ApiResourceList; export type GetApiResourcesApiArg = void; +export type ListLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ LogsDrilldownDefaultColumnsList; +export type ListLogsDrilldownDefaultColumnsApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ + | LogsDrilldownDefaultColumns + | /** status 201 Created */ LogsDrilldownDefaultColumns + | /** status 202 Accepted */ LogsDrilldownDefaultColumns; +export type CreateLogsDrilldownDefaultColumnsApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + logsDrilldownDefaultColumns: LogsDrilldownDefaultColumns; +}; +export type DeletecollectionLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ Status; +export type DeletecollectionLogsDrilldownDefaultColumnsApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ LogsDrilldownDefaultColumns; +export type GetLogsDrilldownDefaultColumnsApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ + | LogsDrilldownDefaultColumns + | /** status 201 Created */ LogsDrilldownDefaultColumns; +export type ReplaceLogsDrilldownDefaultColumnsApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + logsDrilldownDefaultColumns: LogsDrilldownDefaultColumns; +}; +export type DeleteLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ + | Status + | /** status 202 Accepted */ Status; +export type DeleteLogsDrilldownDefaultColumnsApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateLogsDrilldownDefaultColumnsApiResponse = /** status 200 OK */ + | LogsDrilldownDefaultColumns + | /** status 201 Created */ LogsDrilldownDefaultColumns; +export type UpdateLogsDrilldownDefaultColumnsApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type GetLogsDrilldownDefaultColumnsStatusApiResponse = /** status 200 OK */ LogsDrilldownDefaultColumns; +export type GetLogsDrilldownDefaultColumnsStatusApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceLogsDrilldownDefaultColumnsStatusApiResponse = /** status 200 OK */ + | LogsDrilldownDefaultColumns + | /** status 201 Created */ LogsDrilldownDefaultColumns; +export type ReplaceLogsDrilldownDefaultColumnsStatusApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + logsDrilldownDefaultColumns: LogsDrilldownDefaultColumns; +}; +export type UpdateLogsDrilldownDefaultColumnsStatusApiResponse = /** status 200 OK */ + | LogsDrilldownDefaultColumns + | /** status 201 Created */ LogsDrilldownDefaultColumns; +export type UpdateLogsDrilldownDefaultColumnsStatusApiArg = { + /** name of the LogsDrilldownDefaultColumns */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; export type ListLogsDrilldownDefaultsApiResponse = /** status 200 OK */ LogsDrilldownDefaultsList; export type ListLogsDrilldownDefaultsApiArg = { /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ @@ -874,13 +1268,21 @@ export type ObjectMeta = { Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ uid?: string; }; -export type LogsDrilldownDefaultsSpec = { - defaultFields: string[]; - interceptDismissed: boolean; - prettifyJSON: boolean; - wrapLogMessage: boolean; +export type LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel = { + key: string; + value: string; }; -export type LogsDrilldownDefaultsOperatorState = { +export type LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels = LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel[]; +export type LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord = { + columns: string[]; + labels: LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels; +}; +export type LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords = + LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord[]; +export type LogsDrilldownDefaultColumnsSpec = { + records: LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords; +}; +export type LogsDrilldownDefaultColumnsOperatorState = { /** descriptiveState is an optional more descriptive state field which has no requirements on format */ descriptiveState?: string; /** details contains any extra information that is operator-specific */ @@ -895,7 +1297,7 @@ export type LogsDrilldownDefaultsOperatorState = { It is limited to three possible states for machine evaluation. */ state: 'success' | 'in_progress' | 'failed'; }; -export type LogsDrilldownDefaultsStatus = { +export type LogsDrilldownDefaultColumnsStatus = { /** additionalFields is reserved for future use */ additionalFields?: { [key: string]: { @@ -905,17 +1307,17 @@ export type LogsDrilldownDefaultsStatus = { /** operatorStates is a map of operator ID to operator state evaluations. Any operator which consumes this kind SHOULD add its state evaluation information to this field. */ operatorStates?: { - [key: string]: LogsDrilldownDefaultsOperatorState; + [key: string]: LogsDrilldownDefaultColumnsOperatorState; }; }; -export type LogsDrilldownDefaults = { +export type LogsDrilldownDefaultColumns = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion: string; /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind: string; metadata: ObjectMeta; - spec: LogsDrilldownDefaultsSpec; - status?: LogsDrilldownDefaultsStatus; + spec: LogsDrilldownDefaultColumnsSpec; + status?: LogsDrilldownDefaultColumnsStatus; }; export type ListMeta = { /** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */ @@ -927,10 +1329,10 @@ export type ListMeta = { /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ selfLink?: string; }; -export type LogsDrilldownDefaultsList = { +export type LogsDrilldownDefaultColumnsList = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; - items: LogsDrilldownDefaults[]; + items: LogsDrilldownDefaultColumns[]; /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ kind?: string; metadata: ListMeta; @@ -980,6 +1382,57 @@ export type Status = { status?: string; }; export type Patch = object; +export type LogsDrilldownDefaultsSpec = { + defaultFields: string[]; + interceptDismissed: boolean; + prettifyJSON: boolean; + wrapLogMessage: boolean; +}; +export type LogsDrilldownDefaultsOperatorState = { + /** descriptiveState is an optional more descriptive state field which has no requirements on format */ + descriptiveState?: string; + /** details contains any extra information that is operator-specific */ + details?: { + [key: string]: { + [key: string]: any; + }; + }; + /** lastEvaluation is the ResourceVersion last evaluated */ + lastEvaluation: string; + /** state describes the state of the lastEvaluation. + It is limited to three possible states for machine evaluation. */ + state: 'success' | 'in_progress' | 'failed'; +}; +export type LogsDrilldownDefaultsStatus = { + /** additionalFields is reserved for future use */ + additionalFields?: { + [key: string]: { + [key: string]: any; + }; + }; + /** operatorStates is a map of operator ID to operator state evaluations. + Any operator which consumes this kind SHOULD add its state evaluation information to this field. */ + operatorStates?: { + [key: string]: LogsDrilldownDefaultsOperatorState; + }; +}; +export type LogsDrilldownDefaults = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind: string; + metadata: ObjectMeta; + spec: LogsDrilldownDefaultsSpec; + status?: LogsDrilldownDefaultsStatus; +}; +export type LogsDrilldownDefaultsList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items: LogsDrilldownDefaults[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata: ListMeta; +}; export type LogsDrilldownSpec = { defaultFields: string[]; interceptDismissed: boolean; @@ -1034,6 +1487,19 @@ export type LogsDrilldownList = { export const { useGetApiResourcesQuery, useLazyGetApiResourcesQuery, + useListLogsDrilldownDefaultColumnsQuery, + useLazyListLogsDrilldownDefaultColumnsQuery, + useCreateLogsDrilldownDefaultColumnsMutation, + useDeletecollectionLogsDrilldownDefaultColumnsMutation, + useGetLogsDrilldownDefaultColumnsQuery, + useLazyGetLogsDrilldownDefaultColumnsQuery, + useReplaceLogsDrilldownDefaultColumnsMutation, + useDeleteLogsDrilldownDefaultColumnsMutation, + useUpdateLogsDrilldownDefaultColumnsMutation, + useGetLogsDrilldownDefaultColumnsStatusQuery, + useLazyGetLogsDrilldownDefaultColumnsStatusQuery, + useReplaceLogsDrilldownDefaultColumnsStatusMutation, + useUpdateLogsDrilldownDefaultColumnsStatusMutation, useListLogsDrilldownDefaultsQuery, useLazyListLogsDrilldownDefaultsQuery, useCreateLogsDrilldownDefaultsMutation, diff --git a/packages/grafana-api-clients/src/clients/rtkq/provisioning/v0alpha1/endpoints.gen.ts b/packages/grafana-api-clients/src/clients/rtkq/provisioning/v0alpha1/endpoints.gen.ts index 7ef1fc4fc91..3bb583d7cb4 100644 --- a/packages/grafana-api-clients/src/clients/rtkq/provisioning/v0alpha1/endpoints.gen.ts +++ b/packages/grafana-api-clients/src/clients/rtkq/provisioning/v0alpha1/endpoints.gen.ts @@ -1,5 +1,5 @@ import { api } from './baseAPI'; -export const addTagTypes = ['API Discovery', 'Job', 'Repository', 'Provisioning'] as const; +export const addTagTypes = ['API Discovery', 'Connection', 'Job', 'Repository', 'Provisioning'] as const; const injectedRtkApi = api .enhanceEndpoints({ addTagTypes, @@ -10,6 +10,156 @@ const injectedRtkApi = api query: () => ({ url: `/` }), providesTags: ['API Discovery'], }), + listConnection: build.query({ + query: (queryArg) => ({ + url: `/connections`, + params: { + pretty: queryArg.pretty, + allowWatchBookmarks: queryArg.allowWatchBookmarks, + continue: queryArg['continue'], + fieldSelector: queryArg.fieldSelector, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + watch: queryArg.watch, + }, + }), + providesTags: ['Connection'], + }), + createConnection: build.mutation({ + query: (queryArg) => ({ + url: `/connections`, + method: 'POST', + body: queryArg.connection, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['Connection'], + }), + deletecollectionConnection: build.mutation< + DeletecollectionConnectionApiResponse, + DeletecollectionConnectionApiArg + >({ + query: (queryArg) => ({ + url: `/connections`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + continue: queryArg['continue'], + dryRun: queryArg.dryRun, + fieldSelector: queryArg.fieldSelector, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + labelSelector: queryArg.labelSelector, + limit: queryArg.limit, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + resourceVersion: queryArg.resourceVersion, + resourceVersionMatch: queryArg.resourceVersionMatch, + sendInitialEvents: queryArg.sendInitialEvents, + timeoutSeconds: queryArg.timeoutSeconds, + }, + }), + invalidatesTags: ['Connection'], + }), + getConnection: build.query({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['Connection'], + }), + replaceConnection: build.mutation({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}`, + method: 'PUT', + body: queryArg.connection, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['Connection'], + }), + deleteConnection: build.mutation({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}`, + method: 'DELETE', + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + gracePeriodSeconds: queryArg.gracePeriodSeconds, + ignoreStoreReadErrorWithClusterBreakingPotential: queryArg.ignoreStoreReadErrorWithClusterBreakingPotential, + orphanDependents: queryArg.orphanDependents, + propagationPolicy: queryArg.propagationPolicy, + }, + }), + invalidatesTags: ['Connection'], + }), + updateConnection: build.mutation({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['Connection'], + }), + getConnectionStatus: build.query({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}/status`, + params: { + pretty: queryArg.pretty, + }, + }), + providesTags: ['Connection'], + }), + replaceConnectionStatus: build.mutation({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}/status`, + method: 'PUT', + body: queryArg.connection, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + }, + }), + invalidatesTags: ['Connection'], + }), + updateConnectionStatus: build.mutation({ + query: (queryArg) => ({ + url: `/connections/${queryArg.name}/status`, + method: 'PATCH', + body: queryArg.patch, + params: { + pretty: queryArg.pretty, + dryRun: queryArg.dryRun, + fieldManager: queryArg.fieldManager, + fieldValidation: queryArg.fieldValidation, + force: queryArg.force, + }, + }), + invalidatesTags: ['Connection'], + }), listJob: build.query({ query: (queryArg) => ({ url: `/jobs`, @@ -411,6 +561,208 @@ const injectedRtkApi = api export { injectedRtkApi as generatedAPI }; export type GetApiResourcesApiResponse = /** status 200 OK */ ApiResourceList; export type GetApiResourcesApiArg = void; +export type ListConnectionApiResponse = /** status 200 OK */ ConnectionList; +export type ListConnectionApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. */ + allowWatchBookmarks?: boolean; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; + /** Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. */ + watch?: boolean; +}; +export type CreateConnectionApiResponse = /** status 200 OK */ + | Connection + | /** status 201 Created */ Connection + | /** status 202 Accepted */ Connection; +export type CreateConnectionApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + connection: Connection; +}; +export type DeletecollectionConnectionApiResponse = /** status 200 OK */ Status; +export type DeletecollectionConnectionApiArg = { + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". + + This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. */ + continue?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** A selector to restrict the list of returned objects by their fields. Defaults to everything. */ + fieldSelector?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** A selector to restrict the list of returned objects by their labels. Defaults to everything. */ + labelSelector?: string; + /** limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. + + The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. */ + limit?: number; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; + /** resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersion?: string; + /** resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. + + Defaults to unset */ + resourceVersionMatch?: string; + /** `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic "Bookmark" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `"k8s.io/initial-events-end": "true"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. + + When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan + is interpreted as "data at least as new as the provided `resourceVersion`" + and the bookmark event is send when the state is synced + to a `resourceVersion` at least as fresh as the one provided by the ListOptions. + If `resourceVersion` is unset, this is interpreted as "consistent read" and the + bookmark event is send when the state is synced at least to the moment + when request started being processed. + - `resourceVersionMatch` set to any other value or unset + Invalid error is returned. + + Defaults to true if `resourceVersion=""` or `resourceVersion="0"` (for backward compatibility reasons) and to false otherwise. */ + sendInitialEvents?: boolean; + /** Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. */ + timeoutSeconds?: number; +}; +export type GetConnectionApiResponse = /** status 200 OK */ Connection; +export type GetConnectionApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceConnectionApiResponse = /** status 200 OK */ Connection | /** status 201 Created */ Connection; +export type ReplaceConnectionApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + connection: Connection; +}; +export type DeleteConnectionApiResponse = /** status 200 OK */ Status | /** status 202 Accepted */ Status; +export type DeleteConnectionApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. */ + gracePeriodSeconds?: number; + /** if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it */ + ignoreStoreReadErrorWithClusterBreakingPotential?: boolean; + /** Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. */ + orphanDependents?: boolean; + /** Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. */ + propagationPolicy?: string; +}; +export type UpdateConnectionApiResponse = /** status 200 OK */ Connection | /** status 201 Created */ Connection; +export type UpdateConnectionApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; +export type GetConnectionStatusApiResponse = /** status 200 OK */ Connection; +export type GetConnectionStatusApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; +}; +export type ReplaceConnectionStatusApiResponse = /** status 200 OK */ Connection | /** status 201 Created */ Connection; +export type ReplaceConnectionStatusApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + connection: Connection; +}; +export type UpdateConnectionStatusApiResponse = /** status 200 OK */ Connection | /** status 201 Created */ Connection; +export type UpdateConnectionStatusApiArg = { + /** name of the Connection */ + name: string; + /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ + pretty?: string; + /** When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed */ + dryRun?: string; + /** fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). */ + fieldManager?: string; + /** fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. */ + fieldValidation?: string; + /** Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. */ + force?: boolean; + patch: Patch; +}; export type ListJobApiResponse = /** status 200 OK */ JobList; export type ListJobApiArg = { /** If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). */ @@ -1053,6 +1405,169 @@ export type ObjectMeta = { Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ uid?: string; }; +export type InlineSecureValue = + | { + /** Create a secure value -- this is only used for POST/PUT */ + create?: string; + /** Name in the secret service (reference) */ + name: string; + /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ + remove?: boolean; + } + | { + /** Create a secure value -- this is only used for POST/PUT */ + create: string; + /** Name in the secret service (reference) */ + name?: string; + /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ + remove?: boolean; + } + | { + /** Create a secure value -- this is only used for POST/PUT */ + create?: string; + /** Name in the secret service (reference) */ + name?: string; + /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ + remove: boolean; + }; +export type ConnectionSecure = { + /** ClientSecret is the reference to the secret used for other providers authentication, and Github on-behalf-of authentication. This value is stored securely and cannot be read back */ + clientSecret?: InlineSecureValue; + /** PrivateKey is the reference to the private key used for GitHub App authentication. This value is stored securely and cannot be read back */ + privateKey?: InlineSecureValue; + /** Token is the reference of the token used to act as the Connection. This value is stored securely and cannot be read back */ + webhook?: InlineSecureValue; +}; +export type BitbucketConnectionConfig = { + /** App client ID */ + clientID: string; +}; +export type GitHubConnectionConfig = { + /** GitHub App ID */ + appID: string; + /** GitHub App installation ID */ + installationID: string; +}; +export type GitlabConnectionConfig = { + /** App client ID */ + clientID: string; +}; +export type ConnectionSpec = { + /** Bitbucket connection configuration Only applicable when provider is "bitbucket" */ + bitbucket?: BitbucketConnectionConfig; + /** GitHub connection configuration Only applicable when provider is "github" */ + github?: GitHubConnectionConfig; + /** Gitlab connection configuration Only applicable when provider is "gitlab" */ + gitlab?: GitlabConnectionConfig; + /** The connection provider type + + Possible enum values: + - `"bitbucket"` + - `"github"` + - `"gitlab"` */ + type: 'bitbucket' | 'github' | 'gitlab'; + /** The connection URL */ + url?: string; +}; +export type HealthStatus = { + /** When the health was checked last time */ + checked?: number; + /** The type of the error + + Possible enum values: + - `"health"` + - `"hook"` */ + error?: 'health' | 'hook'; + /** When not healthy, requests will not be executed */ + healthy: boolean; + /** Summary messages (can be shown to users) Will only be populated when not healthy */ + message?: string[]; +}; +export type ConnectionStatus = { + /** The connection health status */ + health: HealthStatus; + /** The generation of the spec last time reconciliation ran */ + observedGeneration: number; + /** Connection state + + Possible enum values: + - `"connected"` + - `"disconnected"` */ + state: 'connected' | 'disconnected'; +}; +export type Connection = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ObjectMeta; + secure?: ConnectionSecure; + spec?: ConnectionSpec; + status?: ConnectionStatus; +}; +export type ListMeta = { + /** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */ + continue?: string; + /** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */ + remainingItemCount?: number; + /** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ + resourceVersion?: string; + /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ + selfLink?: string; +}; +export type ConnectionList = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + items: Connection[]; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + metadata?: ListMeta; +}; +export type StatusCause = { + /** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. + + Examples: + "name" - the field "name" on the current resource + "items[0].name" - the field "name" on the first array entry in "items" */ + field?: string; + /** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */ + message?: string; + /** A machine-readable description of the cause of the error. If this value is empty there is no information available. */ + reason?: string; +}; +export type StatusDetails = { + /** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */ + causes?: StatusCause[]; + /** The group attribute of the resource associated with the status StatusReason. */ + group?: string; + /** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + /** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */ + name?: string; + /** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */ + retryAfterSeconds?: number; + /** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ + uid?: string; +}; +export type Status = { + /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ + apiVersion?: string; + /** Suggested HTTP return code for this status, 0 if not set. */ + code?: number; + /** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */ + details?: StatusDetails; + /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + kind?: string; + /** A human-readable description of the status of this operation. */ + message?: string; + /** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ + metadata?: ListMeta; + /** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */ + reason?: string; + /** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */ + status?: string; +}; +export type Patch = object; export type ResourceRef = { /** Group is the group of the resource, such as "dashboard.grafana.app". */ group?: string; @@ -1138,7 +1653,7 @@ export type JobResourceSummary = { delete?: number; /** Create or update (export) */ error?: number; - /** Report errors for this resource type This may not be an exhaustive list and recommend looking at the logs for more info */ + /** Report errors/warnings for this resource type This may not be an exhaustive list and recommend looking at the logs for more info */ errors?: string[]; group?: string; kind?: string; @@ -1146,6 +1661,9 @@ export type JobResourceSummary = { noop?: number; total?: number; update?: number; + /** The error count */ + warning?: number; + warnings?: string[]; write?: number; }; export type RepositoryUrLs = { @@ -1176,6 +1694,7 @@ export type JobStatus = { summary?: JobResourceSummary[]; /** URLs contains URLs for the reference branch or commit if applicable. */ url?: RepositoryUrLs; + warnings?: string[]; }; export type Job = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ @@ -1186,16 +1705,6 @@ export type Job = { spec?: JobSpec; status?: JobStatus; }; -export type ListMeta = { - /** continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. */ - continue?: string; - /** remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. */ - remainingItemCount?: number; - /** String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ - resourceVersion?: string; - /** Deprecated: selfLink is a legacy read-only field that is no longer populated by the system. */ - selfLink?: string; -}; export type JobList = { /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ apiVersion?: string; @@ -1204,76 +1713,6 @@ export type JobList = { kind?: string; metadata?: ListMeta; }; -export type StatusCause = { - /** The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. - - Examples: - "name" - the field "name" on the current resource - "items[0].name" - the field "name" on the first array entry in "items" */ - field?: string; - /** A human-readable description of the cause of the error. This field may be presented as-is to a reader. */ - message?: string; - /** A machine-readable description of the cause of the error. If this value is empty there is no information available. */ - reason?: string; -}; -export type StatusDetails = { - /** The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes. */ - causes?: StatusCause[]; - /** The group attribute of the resource associated with the status StatusReason. */ - group?: string; - /** The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ - kind?: string; - /** The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described). */ - name?: string; - /** If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action. */ - retryAfterSeconds?: number; - /** UID of the resource. (when there is a single resource which can be described). More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids */ - uid?: string; -}; -export type Status = { - /** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */ - apiVersion?: string; - /** Suggested HTTP return code for this status, 0 if not set. */ - code?: number; - /** Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type. */ - details?: StatusDetails; - /** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ - kind?: string; - /** A human-readable description of the status of this operation. */ - message?: string; - /** Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */ - metadata?: ListMeta; - /** A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it. */ - reason?: string; - /** Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status */ - status?: string; -}; -export type Patch = object; -export type InlineSecureValue = - | { - /** Create a secure value -- this is only used for POST/PUT */ - create?: string; - /** Name in the secret service (reference) */ - name: string; - /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ - remove?: boolean; - } - | { - /** Create a secure value -- this is only used for POST/PUT */ - create: string; - /** Name in the secret service (reference) */ - name?: string; - /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ - remove?: boolean; - } - | { - /** Create a secure value -- this is only used for POST/PUT */ - create?: string; - /** Name in the secret service (reference) */ - name?: string; - /** Remove this value from the secure value map Values owned by this resource will be deleted if necessary */ - remove: boolean; - }; export type SecureValues = { /** Token used to connect the configured repository */ token?: InlineSecureValue; @@ -1292,6 +1731,9 @@ export type BitbucketRepositoryConfig = { /** The repository URL (e.g. `https://bitbucket.org/example/test`). */ url?: string; }; +export type ConnectionInfo = { + name: string; +}; export type GitRepositoryConfig = { /** The branch to use in the repository. */ branch: string; @@ -1344,6 +1786,8 @@ export type SyncOptions = { export type RepositorySpec = { /** The repository on Bitbucket. Mutually exclusive with local | github | git. */ bitbucket?: BitbucketRepositoryConfig; + /** The connection the repository references. This means the Repository is interacting with git via a Connection. */ + connection?: ConnectionInfo; /** Repository description */ description?: string; /** The repository on Git. Mutually exclusive with local | github | git. */ @@ -1370,20 +1814,6 @@ export type RepositorySpec = { /** UI driven Workflow that allow changes to the contends of the repository. The order is relevant for defining the precedence of the workflows. When empty, the repository does not support any edits (eg, readonly) */ workflows: ('branch' | 'write')[]; }; -export type HealthStatus = { - /** When the health was checked last time */ - checked?: number; - /** The type of the error - - Possible enum values: - - `"health"` - - `"hook"` */ - error?: 'health' | 'hook'; - /** When not healthy, requests will not be executed */ - healthy: boolean; - /** Summary messages (can be shown to users) Will only be populated when not healthy */ - message?: string[]; -}; export type ResourceCount = { count: number; group: string; @@ -1644,6 +2074,19 @@ export type ResourceStats = { export const { useGetApiResourcesQuery, useLazyGetApiResourcesQuery, + useListConnectionQuery, + useLazyListConnectionQuery, + useCreateConnectionMutation, + useDeletecollectionConnectionMutation, + useGetConnectionQuery, + useLazyGetConnectionQuery, + useReplaceConnectionMutation, + useDeleteConnectionMutation, + useUpdateConnectionMutation, + useGetConnectionStatusQuery, + useLazyGetConnectionStatusQuery, + useReplaceConnectionStatusMutation, + useUpdateConnectionStatusMutation, useListJobQuery, useLazyListJobQuery, useCreateJobMutation, diff --git a/packages/grafana-data/src/field/fieldDisplay.ts b/packages/grafana-data/src/field/fieldDisplay.ts index c4423173da3..3d82f571926 100644 --- a/packages/grafana-data/src/field/fieldDisplay.ts +++ b/packages/grafana-data/src/field/fieldDisplay.ts @@ -190,10 +190,62 @@ export const getFieldDisplayValues = (options: GetFieldDisplayValuesOptions): Fi y: dataFrame.fields[i], x: timeField, }; - if (calc === ReducerID.last) { - sparkline.highlightIndex = sparkline.y.values.length - 1; - } else if (calc === ReducerID.first) { - sparkline.highlightIndex = 0; + let highlightIdx: number | undefined = (() => { + switch (calc) { + case ReducerID.last: + return sparkline.y.values.length - 1; + case ReducerID.first: + return 0; + // TODO: #112977 enable more reducers for highlight index + // case ReducerID.lastNotNull: { + // for (let k = sparkline.y.values.length - 1; k >= 0; k--) { + // const v = sparkline.y.values[k]; + // if (v !== null && v !== undefined && !Number.isNaN(v)) { + // return k; + // } + // } + // return; + // } + // case ReducerID.firstNotNull: { + // for (let k = 0; k < sparkline.y.values.length; k++) { + // const v = sparkline.y.values[k]; + // if (v !== null && v !== undefined && !Number.isNaN(v)) { + // return k; + // } + // } + // return; + // } + // case ReducerID.min: { + // let minIdx = -1; + // let prevMin = Infinity; + // for (let k = 0; k < sparkline.y.values.length; k++) { + // const v = sparkline.y.values[k]; + // if (v !== null && v !== undefined && !Number.isNaN(v) && v < prevMin) { + // prevMin = v; + // minIdx = k; + // } + // } + // return minIdx >= 0 ? minIdx : undefined; + // } + // case ReducerID.max: { + // let maxIdx = -1; + // let prevMax = -Infinity; + // for (let k = 0; k < sparkline.y.values.length; k++) { + // const v = sparkline.y.values[k]; + // if (v !== null && v !== undefined && !Number.isNaN(v) && v > prevMax) { + // prevMax = v; + // maxIdx = k; + // } + // } + // return maxIdx >= 0 ? maxIdx : undefined; + // } + default: + return; + } + })(); + + if (typeof highlightIdx === 'number') { + sparkline.highlightIndex = highlightIdx; } } diff --git a/packages/grafana-data/src/field/fieldOverrides.test.ts b/packages/grafana-data/src/field/fieldOverrides.test.ts index 901fc6d8cc2..767da439543 100644 --- a/packages/grafana-data/src/field/fieldOverrides.test.ts +++ b/packages/grafana-data/src/field/fieldOverrides.test.ts @@ -253,7 +253,7 @@ describe('applyFieldOverrides', () => { ], }); - it('will apply field overrides to the fields within the frame', () => { + it('will apply default field overrides to the fields within the frame', () => { const f0 = createDataFrame({ name: 'A', fields: [ @@ -285,6 +285,41 @@ describe('applyFieldOverrides', () => { expect(withOverrides[0].fields[1].values[0].fields[1].state.range.max).toBe(30); }); + it('will apply targeted field overrides to the fields within the frame', () => { + const f0 = createDataFrame({ + name: 'A', + fields: [ + { + name: 'message', + type: FieldType.string, + values: ['foo'], + }, + { + name: 'frame', + type: FieldType.frame, + values: [f0Internal], + }, + ], + }); + const withOverrides = applyFieldOverrides({ + data: [f0], + fieldConfig: { + defaults: {}, + overrides: [ + { + matcher: { id: FieldMatcherID.byName, options: 'frame' }, + properties: [{ id: 'max', value: 30 }], + }, + ], + }, + replaceVariables: (value) => value, + theme: createTheme(), + fieldConfigRegistry: customFieldRegistry, + }); + + expect(withOverrides[0].fields[1].values[0].fields[1].config.max).toBe(30); + }); + it('will not crash when some of the nested frames are undefined', () => { const f0 = createDataFrame({ name: 'A', diff --git a/packages/grafana-data/src/field/fieldOverrides.ts b/packages/grafana-data/src/field/fieldOverrides.ts index 2aac477cd2b..8b345036c64 100644 --- a/packages/grafana-data/src/field/fieldOverrides.ts +++ b/packages/grafana-data/src/field/fieldOverrides.ts @@ -1,4 +1,4 @@ -import { isNumber, set, unset, get, cloneDeep } from 'lodash'; +import { isNumber, set, unset, get, cloneDeep, defaultsDeep } from 'lodash'; import { createContext, useContext, useMemo, useRef } from 'react'; import { usePrevious } from 'react-use'; @@ -240,9 +240,14 @@ export function applyFieldOverrides(options: ApplyFieldOverrideOptions): DataFra ...options, // nested frames can be `undefined` in certain situations, like after `merge` transform due to padding the value array. // let's replace them with empty frames to avoid errors applying overrides - data: field.values.map( - (nestedFrame: DataFrame | undefined): DataFrame => nestedFrame ?? createDataFrame({ fields: [] }) - ), + data: field.values.map((nestedFrame: DataFrame | undefined): DataFrame => { + const result = nestedFrame ?? createDataFrame({ fields: [] }); + result.fields = result.fields.map((newField) => { + newField.config = defaultsDeep(newField.config || {}, config); + return newField; + }); + return result; + }), }); } } @@ -256,7 +261,7 @@ function calculateRange( field: Field, globalRange: NumericRange | undefined, data: DataFrame[] -): { range?: { min?: number | null; max?: number | null; delta: number }; newGlobalRange: NumericRange | undefined } { +): { range?: NumericRange; newGlobalRange?: NumericRange } { // If range is defined with min/max, use it if (isNumber(config.min) && isNumber(config.max)) { const range = { min: config.min, max: config.max, delta: config.max - config.min }; diff --git a/packages/grafana-data/src/types/featureToggles.gen.ts b/packages/grafana-data/src/types/featureToggles.gen.ts index a0d2df1e542..04e4862f2ad 100644 --- a/packages/grafana-data/src/types/featureToggles.gen.ts +++ b/packages/grafana-data/src/types/featureToggles.gen.ts @@ -309,10 +309,6 @@ export interface FeatureToggles { */ queryServiceFromUI?: boolean; /** - * Routes explore requests to the new query service - */ - queryServiceFromExplore?: boolean; - /** * Runs CloudWatch metrics queries as separate batches */ cloudWatchBatchQueries?: boolean; @@ -988,6 +984,11 @@ export interface FeatureToggles { */ restoreDashboards?: boolean; /** + * Enables recently viewed dashboards section in the browsing dashboard page + * @default false + */ + recentlyViewedDashboards?: boolean; + /** * Enable configuration of alert enrichments in Grafana Cloud. * @default false */ @@ -1180,10 +1181,20 @@ export interface FeatureToggles { */ onlyStoreActionSets?: boolean; /** + * Show insights for plugins in the plugin details page + * @default false + */ + pluginInsights?: boolean; + /** * Enables a new panel time settings drawer */ panelTimeSettings?: boolean; /** + * Enables the raw DSL query editor in the Elasticsearch data source + * @default false + */ + elasticsearchRawDSLQuery?: boolean; + /** * Enables app platform API for annotations * @default false */ diff --git a/packages/grafana-data/src/types/icon.ts b/packages/grafana-data/src/types/icon.ts index b49be0d5363..34e672b66f5 100644 --- a/packages/grafana-data/src/types/icon.ts +++ b/packages/grafana-data/src/types/icon.ts @@ -288,6 +288,7 @@ export const availableIconsIndex = { bitbucket: true, git: true, 'tachometer-fast': true, + 'tachometer-empty': true, 'cmab-logo': true, }; diff --git a/packages/grafana-data/src/types/logs.ts b/packages/grafana-data/src/types/logs.ts index 94f1d97518c..b5e66d705f4 100644 --- a/packages/grafana-data/src/types/logs.ts +++ b/packages/grafana-data/src/types/logs.ts @@ -273,7 +273,7 @@ export interface DataSourceWithSupplementaryQueriesSupport): SupplementaryQueryType[]; /** * Returns a supplementary query to be used to fetch supplementary data based on the provided type and original query. * If the provided query is not suitable for the provided supplementary query type, undefined should be returned. @@ -283,7 +283,8 @@ export interface DataSourceWithSupplementaryQueriesSupport( datasource: DataSourceApi | (DataSourceApi & DataSourceWithSupplementaryQueriesSupport), - type: SupplementaryQueryType + type: SupplementaryQueryType, + dsRequest?: DataQueryRequest ): datasource is DataSourceApi & DataSourceWithSupplementaryQueriesSupport => { if (!datasource) { return false; @@ -293,7 +294,7 @@ export const hasSupplementaryQuerySupport = ( ('getDataProvider' in datasource || 'getSupplementaryRequest' in datasource) && 'getSupplementaryQuery' in datasource && 'getSupportedSupplementaryQueryTypes' in datasource && - datasource.getSupportedSupplementaryQueryTypes().includes(type) + datasource.getSupportedSupplementaryQueryTypes(dsRequest).includes(type) ); }; diff --git a/packages/grafana-e2e-selectors/src/index.ts b/packages/grafana-e2e-selectors/src/index.ts index 32b22b5bb52..5b078f1233f 100644 --- a/packages/grafana-e2e-selectors/src/index.ts +++ b/packages/grafana-e2e-selectors/src/index.ts @@ -1,5 +1,5 @@ /** - * A library containing the different design components of the Grafana ecosystem. + * A library containing e2e selectors for the Grafana ecosystem. * * @packageDocumentation */ diff --git a/packages/grafana-e2e-selectors/src/selectors/components.ts b/packages/grafana-e2e-selectors/src/selectors/components.ts index aca18844459..0755477f93b 100644 --- a/packages/grafana-e2e-selectors/src/selectors/components.ts +++ b/packages/grafana-e2e-selectors/src/selectors/components.ts @@ -3,7 +3,7 @@ // (a ); diff --git a/packages/grafana-ui/src/components/InteractiveTable/utils.ts b/packages/grafana-ui/src/components/InteractiveTable/utils.ts index 68017bbfd19..2b664b16f6d 100644 --- a/packages/grafana-ui/src/components/InteractiveTable/utils.ts +++ b/packages/grafana-ui/src/components/InteractiveTable/utils.ts @@ -1,6 +1,6 @@ import { Column as RTColumn } from 'react-table'; -import { ExpanderCell, ExpanderHeader } from './Expander'; +import { EmptyExpanderHeader, ExpanderCell, ExpanderHeader } from './Expander'; import { Column } from './types'; export const EXPANDER_CELL_ID = '__expander' as const; @@ -18,9 +18,7 @@ export function getColumns( { id: EXPANDER_CELL_ID, Cell: ExpanderCell, - ...(showExpandAll && { - Header: ExpanderHeader, - }), + Header: showExpandAll ? ExpanderHeader : EmptyExpanderHeader, disableSortBy: true, width: 0, }, diff --git a/packages/grafana-ui/src/components/Layout/Grid/Grid.tsx b/packages/grafana-ui/src/components/Layout/Grid/Grid.tsx index ffba1eb88de..2960de1f502 100644 --- a/packages/grafana-ui/src/components/Layout/Grid/Grid.tsx +++ b/packages/grafana-ui/src/components/Layout/Grid/Grid.tsx @@ -28,7 +28,7 @@ interface PropsWithMinColumnWidth extends GridPropsBase { /** For a responsive layout, fit as many columns while maintaining this minimum column width. * The real width will be calculated based on the theme spacing tokens: `theme.spacing(minColumnWidth)` */ - minColumnWidth?: ResponsiveProp<1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 44 | 55 | 72 | 89 | 144>; + minColumnWidth?: ResponsiveProp<1 | 2 | 3 | 5 | 8 | 13 | 16 | 21 | 34 | 44 | 55 | 72 | 89 | 144>; } /** 'columns' and 'minColumnWidth' are mutually exclusive */ diff --git a/packages/grafana-ui/src/components/PanelChrome/HoverWidget.tsx b/packages/grafana-ui/src/components/PanelChrome/HoverWidget.tsx index eb5c54d7b3b..0660b9a0118 100644 --- a/packages/grafana-ui/src/components/PanelChrome/HoverWidget.tsx +++ b/packages/grafana-ui/src/components/PanelChrome/HoverWidget.tsx @@ -16,17 +16,22 @@ interface Props { title?: string; offset?: number; dragClass?: string; + onDragStart?: (event: React.PointerEvent) => void; onOpenMenu?: () => void; } -export function HoverWidget({ menu, title, dragClass, children, offset = -32, onOpenMenu }: Props) { +export function HoverWidget({ menu, title, dragClass, children, offset = -32, onOpenMenu, onDragStart }: Props) { const styles = useStyles2(getStyles); const draggableRef = useRef(null); const selectors = e2eSelectors.components.Panels.Panel.HoverWidget; // Capture the pointer to keep the widget visible while dragging - const onPointerDown = useCallback((e: React.PointerEvent) => { - draggableRef.current?.setPointerCapture(e.pointerId); - }, []); + const onPointerDown = useCallback( + (e: React.PointerEvent) => { + draggableRef.current?.setPointerCapture(e.pointerId); + onDragStart?.(e); + }, + [onDragStart] + ); const onPointerUp = useCallback((e: React.PointerEvent) => { draggableRef.current?.releasePointerCapture(e.pointerId); diff --git a/packages/grafana-ui/src/components/PanelChrome/PanelChrome.tsx b/packages/grafana-ui/src/components/PanelChrome/PanelChrome.tsx index 28a395c7d98..8eace0b38b8 100644 --- a/packages/grafana-ui/src/components/PanelChrome/PanelChrome.tsx +++ b/packages/grafana-ui/src/components/PanelChrome/PanelChrome.tsx @@ -384,6 +384,7 @@ export function PanelChrome({ menu={menu} title={typeof title === 'string' ? title : undefined} dragClass={dragClass} + onDragStart={onDragStart} offset={hoverHeaderOffset} onOpenMenu={onOpenMenu} > diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx index 96e8b0f50f3..fadabf8ec72 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialGauge.tsx @@ -2,7 +2,13 @@ import { css, cx } from '@emotion/css'; import { isNumber } from 'lodash'; import { useId } from 'react'; -import { DisplayValueAlignmentFactors, FieldDisplay, getDisplayProcessor, GrafanaTheme2 } from '@grafana/data'; +import { + DisplayValueAlignmentFactors, + FieldDisplay, + getDisplayProcessor, + GrafanaTheme2, + TimeRange, +} from '@grafana/data'; import { t } from '@grafana/i18n'; import { useStyles2, useTheme2 } from '../../themes/ThemeContext'; @@ -66,6 +72,7 @@ export interface RadialGaugeProps { showScaleLabels?: boolean; /** For data links */ onClick?: React.MouseEventHandler; + timeRange?: TimeRange; } export type RadialGradientMode = 'none' | 'auto'; @@ -99,6 +106,11 @@ export function RadialGauge(props: RadialGaugeProps) { const gaugeId = useId(); const styles = useStyles2(getStyles); + let effectiveTextMode = textMode; + if (effectiveTextMode === 'auto') { + effectiveTextMode = vizCount === 1 ? 'value' : 'value_and_name'; + } + const startAngle = shape === 'gauge' ? 250 : 0; const endAngle = shape === 'gauge' ? 110 : 360; @@ -181,7 +193,7 @@ export function RadialGauge(props: RadialGaugeProps) { // These elements are only added for first value / bar if (barIndex === 0) { if (glowBar) { - defs.push(); + defs.push(); } if (glowCenter) { @@ -191,14 +203,14 @@ export function RadialGauge(props: RadialGaugeProps) { graphics.push( ); @@ -247,6 +259,7 @@ export function RadialGauge(props: RadialGaugeProps) { theme={theme} color={color} shape={shape} + textMode={effectiveTextMode} /> ); } diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx index 7a25fe3201a..acb255a3f3e 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialSparkline.tsx @@ -1,11 +1,9 @@ -import { css } from '@emotion/css'; - import { FieldDisplay, GrafanaTheme2, FieldConfig } from '@grafana/data'; import { GraphFieldConfig, GraphGradientMode, LineInterpolation } from '@grafana/schema'; import { Sparkline } from '../Sparkline/Sparkline'; -import { RadialShape } from './RadialGauge'; +import { RadialShape, RadialTextMode } from './RadialGauge'; import { GaugeDimensions } from './utils'; interface RadialSparklineProps { @@ -14,23 +12,22 @@ interface RadialSparklineProps { theme: GrafanaTheme2; color?: string; shape?: RadialShape; + textMode: Exclude; } -export function RadialSparkline({ sparkline, dimensions, theme, color, shape }: RadialSparklineProps) { +export function RadialSparkline({ sparkline, dimensions, theme, color, shape, textMode }: RadialSparklineProps) { + const { radius, barWidth } = dimensions; + if (!sparkline) { return null; } - const { radius, barWidth } = dimensions; - - const height = radius / 4; - const widthFactor = shape === 'gauge' ? 1.6 : 1.4; - const width = radius * widthFactor - barWidth; - const topPos = shape === 'gauge' ? `${dimensions.gaugeBottomY - height}px` : `calc(50% + ${radius / 2.8}px)`; - - const styles = css({ - position: 'absolute', - top: topPos, - }); + const showNameAndValue = textMode === 'value_and_name'; + const height = radius / (showNameAndValue ? 4 : 3); + const width = radius * (shape === 'gauge' ? 1.6 : 1.4) - barWidth; + const topPos = + shape === 'gauge' + ? `${dimensions.gaugeBottomY - height}px` + : `calc(50% + ${radius / (showNameAndValue ? 3.3 : 4)}px)`; const config: FieldConfig = { color: { @@ -45,7 +42,7 @@ export function RadialSparkline({ sparkline, dimensions, theme, color, shape }: }; return ( -
+
); diff --git a/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx b/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx index d01a2d99570..51a1c64c842 100644 --- a/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/RadialText.tsx @@ -1,6 +1,12 @@ import { css } from '@emotion/css'; -import { DisplayValue, DisplayValueAlignmentFactors, formattedValueToString, GrafanaTheme2 } from '@grafana/data'; +import { + DisplayValue, + DisplayValueAlignmentFactors, + FieldSparkline, + formattedValueToString, + GrafanaTheme2, +} from '@grafana/data'; import { useStyles2 } from '../../themes/ThemeContext'; import { calculateFontSize } from '../../utils/measureText'; @@ -8,21 +14,13 @@ import { calculateFontSize } from '../../utils/measureText'; import { RadialShape, RadialTextMode } from './RadialGauge'; import { GaugeDimensions } from './utils'; -// function toCartesian(centerX: number, centerY: number, radius: number, angleInDegrees: number) { -// let radian = ((angleInDegrees - 90) * Math.PI) / 180.0; -// return { -// x: centerX + radius * Math.cos(radian), -// y: centerY + radius * Math.sin(radian), -// }; -// } - interface RadialTextProps { displayValue: DisplayValue; theme: GrafanaTheme2; dimensions: GaugeDimensions; - textMode: RadialTextMode; - vizCount: number; + textMode: Exclude; shape: RadialShape; + sparkline?: FieldSparkline; alignmentFactors?: DisplayValueAlignmentFactors; valueManualFontSize?: number; nameManualFontSize?: number; @@ -33,8 +31,8 @@ export function RadialText({ theme, dimensions, textMode, - vizCount, shape, + sparkline, alignmentFactors, valueManualFontSize, nameManualFontSize, @@ -46,10 +44,6 @@ export function RadialText({ return null; } - if (textMode === 'auto') { - textMode = vizCount === 1 ? 'value' : 'value_and_name'; - } - const nameToAlignTo = (alignmentFactors ? alignmentFactors.title : displayValue.title) ?? ''; const valueToAlignTo = formattedValueToString(alignmentFactors ? alignmentFactors : displayValue); @@ -59,7 +53,7 @@ export function RadialText({ // Not sure where this comes from but svg text is not using body line-height const lineHeight = 1.21; - const valueWidthToRadiusFactor = 0.85; + const valueWidthToRadiusFactor = 0.82; const nameToHeightFactor = 0.45; const largeRadiusScalingDecay = 0.86; @@ -98,18 +92,23 @@ export function RadialText({ const valueHeight = valueFontSize * lineHeight; const nameHeight = nameFontSize * lineHeight; - const valueY = showName ? centerY - nameHeight / 2 : centerY; - const valueNameSpacing = valueHeight / 3.5; - const nameY = showValue ? valueY + valueHeight / 2 + valueNameSpacing : centerY; + const valueY = showName ? centerY - nameHeight * 0.3 : centerY; + const nameY = showValue ? valueY + valueHeight * 0.7 : centerY; const nameColor = showValue ? theme.colors.text.secondary : theme.colors.text.primary; const suffixShift = (valueFontSize - unitFontSize * 1.2) / 2; - // For gauge shape we shift text up a bit - const valueDy = shape === 'gauge' ? -valueFontSize * 0.3 : 0; - const nameDy = shape === 'gauge' ? -nameFontSize * 0.7 : 0; + // adjust the text up on gauges and when sparklines are present + let yOffset = 0; + if (shape === 'gauge') { + // we render from the center of the gauge, so move up by half of half of the total height + yOffset -= (valueHeight + nameHeight) / 4; + } + if (sparkline) { + yOffset -= 8; + } return ( - + {showValue && ( {displayValue.prefix ?? ''} {displayValue.text} @@ -133,7 +131,6 @@ export function RadialText({ fontSize={nameFontSize} x={centerX} y={nameY} - dy={nameDy} textAnchor="middle" dominantBaseline="middle" fill={nameColor} diff --git a/packages/grafana-ui/src/components/RadialGauge/effects.tsx b/packages/grafana-ui/src/components/RadialGauge/effects.tsx index 76f15900a14..354a68a25ba 100644 --- a/packages/grafana-ui/src/components/RadialGauge/effects.tsx +++ b/packages/grafana-ui/src/components/RadialGauge/effects.tsx @@ -4,11 +4,12 @@ import { GaugeDimensions } from './utils'; export interface GlowGradientProps { id: string; - radius: number; + barWidth: number; } -export function GlowGradient({ id, radius }: GlowGradientProps) { - const glowSize = 0.03 * radius; +export function GlowGradient({ id, barWidth }: GlowGradientProps) { + // 0.75 is the minimum glow size, and it scales with bar width + const glowSize = 0.75 + barWidth * 0.08; return ( @@ -82,7 +83,7 @@ export function MiddleCircleGlow({ dimensions, gaugeId, color }: CenterGlowProps <> - + diff --git a/packages/grafana-ui/src/components/Sparkline/Sparkline.test.tsx b/packages/grafana-ui/src/components/Sparkline/Sparkline.test.tsx index 9ad678132e9..91f3d9945f3 100644 --- a/packages/grafana-ui/src/components/Sparkline/Sparkline.test.tsx +++ b/packages/grafana-ui/src/components/Sparkline/Sparkline.test.tsx @@ -27,4 +27,48 @@ describe('Sparkline', () => { render() ).not.toThrow(); }); + + it('should not throw an error if there is a single value', () => { + const sparkline: FieldSparkline = { + x: { + name: 'x', + values: [1679839200000], + type: FieldType.time, + config: {}, + }, + y: { + name: 'y', + values: [1], + type: FieldType.number, + config: {}, + state: { + range: { min: 1, max: 1, delta: 0 }, + }, + }, + }; + expect(() => + render() + ).not.toThrow(); + }); + + it('should not throw an error if there are no values', () => { + const sparkline: FieldSparkline = { + x: { + name: 'x', + values: [], + type: FieldType.time, + config: {}, + }, + y: { + name: 'y', + values: [], + type: FieldType.number, + config: {}, + state: {}, + }, + }; + expect(() => + render() + ).not.toThrow(); + }); }); diff --git a/packages/grafana-ui/src/components/Sparkline/Sparkline.tsx b/packages/grafana-ui/src/components/Sparkline/Sparkline.tsx index 8de8ed1b893..c18b235e757 100644 --- a/packages/grafana-ui/src/components/Sparkline/Sparkline.tsx +++ b/packages/grafana-ui/src/components/Sparkline/Sparkline.tsx @@ -1,32 +1,13 @@ -import { isEqual } from 'lodash'; -import { PureComponent } from 'react'; -import { AlignedData, Range } from 'uplot'; +import React, { memo } from 'react'; -import { - compareDataFrameStructures, - DataFrame, - Field, - FieldConfig, - FieldSparkline, - FieldType, - getFieldColorModeForField, - nullToValue, -} from '@grafana/data'; -import { - AxisPlacement, - GraphDrawStyle, - GraphFieldConfig, - VisibilityMode, - ScaleDirection, - ScaleOrientation, -} from '@grafana/schema'; +import { FieldConfig, FieldSparkline } from '@grafana/data'; +import { GraphFieldConfig } from '@grafana/schema'; import { Themeable2 } from '../../types/theme'; import { UPlotChart } from '../uPlot/Plot'; -import { UPlotConfigBuilder } from '../uPlot/config/UPlotConfigBuilder'; import { preparePlotData2, getStackingGroups } from '../uPlot/utils'; -import { getYRange, preparePlotFrame } from './utils'; +import { prepareSeries, prepareConfig } from './utils'; export interface SparklineProps extends Themeable2 { width: number; @@ -35,169 +16,28 @@ export interface SparklineProps extends Themeable2 { sparkline: FieldSparkline; } -interface State { - data: AlignedData; - alignedDataFrame: DataFrame; - configBuilder: UPlotConfigBuilder; -} +const SparklineFn: React.FC = memo((props) => { + const { sparkline, config: fieldConfig, theme, width, height } = props; -const defaultConfig: GraphFieldConfig = { - drawStyle: GraphDrawStyle.Line, - showPoints: VisibilityMode.Auto, - axisPlacement: AxisPlacement.Hidden, - pointSize: 2, -}; - -/** @internal */ -export class Sparkline extends PureComponent { - constructor(props: SparklineProps) { - super(props); - - const alignedDataFrame = preparePlotFrame(props.sparkline, props.config); - - this.state = { - data: preparePlotData2(alignedDataFrame, getStackingGroups(alignedDataFrame)), - alignedDataFrame, - configBuilder: this.prepareConfig(alignedDataFrame), - }; + const { frame: alignedDataFrame, warning } = prepareSeries(sparkline, fieldConfig); + if (warning) { + return null; } - static getDerivedStateFromProps(props: SparklineProps, state: State) { - const _frame = preparePlotFrame(props.sparkline, props.config); - const frame = nullToValue(_frame); - if (!frame) { - return { ...state }; - } + const data = preparePlotData2(alignedDataFrame, getStackingGroups(alignedDataFrame)); + const configBuilder = prepareConfig(sparkline, alignedDataFrame, theme); - return { - ...state, - data: preparePlotData2(frame, getStackingGroups(frame)), - alignedDataFrame: frame, - }; - } + return ; +}); - componentDidUpdate(prevProps: SparklineProps, prevState: State) { - const { alignedDataFrame } = this.state; - - if (!alignedDataFrame) { - return; - } - - let rebuildConfig = false; - - if (prevProps.sparkline !== this.props.sparkline) { - const isStructureChanged = !compareDataFrameStructures(this.state.alignedDataFrame, prevState.alignedDataFrame); - const isRangeChanged = !isEqual( - alignedDataFrame.fields[1].state?.range, - prevState.alignedDataFrame.fields[1].state?.range - ); - rebuildConfig = isStructureChanged || isRangeChanged; - } else { - rebuildConfig = !isEqual(prevProps.config, this.props.config); - } - - if (rebuildConfig) { - this.setState({ configBuilder: this.prepareConfig(alignedDataFrame) }); - } - } - - getYRange(field: Field): Range.MinMax { - return getYRange(field, this.state.alignedDataFrame); - } - - prepareConfig(data: DataFrame) { - const { theme } = this.props; - const builder = new UPlotConfigBuilder(); - - builder.setCursor({ - show: false, - x: false, // no crosshairs - y: false, - }); - - // X is the first field in the alligned frame - const xField = data.fields[0]; - builder.addScale({ - scaleKey: 'x', - orientation: ScaleOrientation.Horizontal, - direction: ScaleDirection.Right, - isTime: false, //xField.type === FieldType.time, - range: () => { - const { sparkline } = this.props; - if (sparkline.x) { - if (sparkline.timeRange && sparkline.x.type === FieldType.time) { - return [sparkline.timeRange.from.valueOf(), sparkline.timeRange.to.valueOf()]; - } - const vals = sparkline.x.values; - return [vals[0], vals[vals.length - 1]]; - } - return [0, sparkline.y.values.length - 1]; - }, - }); - - builder.addAxis({ - scaleKey: 'x', - theme, - placement: AxisPlacement.Hidden, - }); - - for (let i = 0; i < data.fields.length; i++) { - const field = data.fields[i]; - const config: FieldConfig = field.config; - const customConfig: GraphFieldConfig = { - ...defaultConfig, - ...config.custom, - }; - - if (field === xField || field.type !== FieldType.number) { - continue; - } - - const scaleKey = config.unit || '__fixed'; - builder.addScale({ - scaleKey, - orientation: ScaleOrientation.Vertical, - direction: ScaleDirection.Up, - range: () => this.getYRange(field), - }); - - builder.addAxis({ - scaleKey, - theme, - placement: AxisPlacement.Hidden, - }); - - const colorMode = getFieldColorModeForField(field); - const seriesColor = colorMode.getCalculator(field, theme)(0, 0); - const pointsMode = - customConfig.drawStyle === GraphDrawStyle.Points ? VisibilityMode.Always : customConfig.showPoints; - - builder.addSeries({ - pxAlign: false, - scaleKey, - theme, - colorMode, - thresholds: config.thresholds, - drawStyle: customConfig.drawStyle!, - lineColor: customConfig.lineColor ?? seriesColor, - lineWidth: customConfig.lineWidth, - lineInterpolation: customConfig.lineInterpolation, - showPoints: pointsMode, - pointSize: customConfig.pointSize, - fillOpacity: customConfig.fillOpacity, - fillColor: customConfig.fillColor, - lineStyle: customConfig.lineStyle, - gradientMode: customConfig.gradientMode, - spanNulls: customConfig.spanNulls, - }); - } - - return builder; - } +SparklineFn.displayName = 'Sparkline'; +// we converted to function component above, but some apps extend Sparkline, so we need +// to keep exporting a class component until those apps are all rolled out. +// see https://github.com/grafana/app-observability-plugin/pull/2079 +// eslint-disable-next-line react-prefer-function-component/react-prefer-function-component +export class Sparkline extends React.PureComponent { render() { - const { data, configBuilder } = this.state; - const { width, height } = this.props; - return ; + return ; } } diff --git a/packages/grafana-ui/src/components/Sparkline/utils.test.ts b/packages/grafana-ui/src/components/Sparkline/utils.test.ts index 9eb914af438..ca49f6da512 100644 --- a/packages/grafana-ui/src/components/Sparkline/utils.test.ts +++ b/packages/grafana-ui/src/components/Sparkline/utils.test.ts @@ -114,6 +114,20 @@ describe('Get y range', () => { config: {}, state: { range: { min: -2, max: -2, delta: 0 } }, }; + const decimalsCloseYField: Field = { + name: 'y', + values: [2, 1.999999999999999, 2.000000000000001, 2, 2], + type: FieldType.number, + config: {}, + state: { range: { min: 1.9999999999999999999, max: 2.000000000000000001, delta: 0 } }, + }; + const decimalsNotCloseYField: Field = { + name: 'y', + values: [2, 0.0094, 0.0053, 0.0078, 0.0061], + type: FieldType.number, + config: {}, + state: { range: { min: 0.0053, max: 0.0094, delta: 0.0041 } }, + }; const xField: Field = { name: 'x', values: [1000, 2000, 3000, 4000, 5000], @@ -154,12 +168,12 @@ describe('Get y range', () => { { description: 'straight line', field: straightLineYField, - expected: [0, 4], + expected: [2, 4], }, { description: 'straight line, negative values', field: straightLineNegYField, - expected: [-4, 0], + expected: [-4, -2], }, { description: 'straight line with config min and max', @@ -171,8 +185,18 @@ describe('Get y range', () => { field: { ...straightLineYField, config: { noValue: '0' } }, expected: [0, 2], }, + { + description: 'long decimals which are nearly equal and result in a functional delta of 0', + field: decimalsCloseYField, + expected: [2, 4], + }, + { + description: 'decimal values which are not close to equal should not be rounded out', + field: decimalsNotCloseYField, + expected: [0.0053, 0.0094], + }, ])(`should return correct range for $description`, ({ field, expected }) => { - const actual = getYRange(field, getAlignedFrame(field)); + const actual = getYRange(getAlignedFrame(field)); expect(actual).toEqual(expected); expect(actual[0]).toBeLessThan(actual[1]!); }); diff --git a/packages/grafana-ui/src/components/Sparkline/utils.ts b/packages/grafana-ui/src/components/Sparkline/utils.ts index 5c2afd8a1cb..be24eb6c4e8 100644 --- a/packages/grafana-ui/src/components/Sparkline/utils.ts +++ b/packages/grafana-ui/src/components/Sparkline/utils.ts @@ -1,16 +1,30 @@ import { Range } from 'uplot'; import { + applyNullInsertThreshold, DataFrame, FieldConfig, FieldSparkline, FieldType, + getFieldColorModeForField, + GrafanaTheme2, + guessDecimals, isLikelyAscendingVector, + nullToValue, + roundDecimals, sortDataFrame, - applyNullInsertThreshold, - Field, } from '@grafana/data'; -import { GraphFieldConfig } from '@grafana/schema'; +import { t } from '@grafana/i18n'; +import { + AxisPlacement, + GraphDrawStyle, + GraphFieldConfig, + VisibilityMode, + ScaleDirection, + ScaleOrientation, +} from '@grafana/schema'; + +import { UPlotConfigBuilder } from '../uPlot/config/UPlotConfigBuilder'; /** @internal * Given a sparkline config returns a DataFrame ready to be turned into Plot data set @@ -55,33 +69,174 @@ export function preparePlotFrame(sparkline: FieldSparkline, config?: FieldConfig /** * apply configuration defaults and ensure that the range is never two equal values. */ -export function getYRange(field: Field, alignedFrame: DataFrame): Range.MinMax { - let { min, max } = alignedFrame.fields[1].state?.range!; +export function getYRange(alignedFrame: DataFrame): Range.MinMax { + const field = alignedFrame.fields[1]; + let { min, max } = field.state?.range!; - // enure that the min/max from the field config are respected - min = Math.max(min!, field.config.min ?? -Infinity); - max = Math.min(max!, field.config.max ?? Infinity); + // enure that the min/max from the field config are respected. + min = Math.min(min!, field.config.min ?? Infinity); + max = Math.max(max!, field.config.max ?? -Infinity); // if noValue is set, ensure that it is included in the range as well - const noValue = +alignedFrame.fields[1].config?.noValue!; + const noValue = +field.config?.noValue!; if (!Number.isNaN(noValue)) { min = Math.min(min, noValue); max = Math.max(max, noValue); } - // if min and max are equal after all of that, create a range - // that allows the sparkline to be visible in the center of the viz - if (min === max) { - if (min === 0) { - max = 100; - } else if (min < 0) { - max = 0; - min *= 2; - } else { - min = 0; - max *= 2; - } + const decimals = field.config.decimals ?? Math.max(guessDecimals(min), guessDecimals(max)); + + // call roundDecimals to mirror what is going to eventually happen in uplot + let roundedMin = roundDecimals(min, decimals); + let roundedMax = roundDecimals(max, decimals); + + // if the rounded min and max are different, + // we can return the real min and max. + if (roundedMin !== roundedMax) { + return [min, max]; } - return [min, max]; + // we are forced to tweak the min and max since they + // will be treated as equal after rounding by uPlot. + if (roundedMin === 0) { + // both are zero + roundedMax = 1; + } else if (roundedMin < 0) { + // both are negative + roundedMin *= 2; + } else { + // both are positive + roundedMax *= 2; + } + + return [roundedMin, roundedMax]; } + +// TODO: #112977 enable highlight index +// const HIGHLIGHT_IDX_POINT_SIZE = 6; + +const defaultConfig: GraphFieldConfig = { + drawStyle: GraphDrawStyle.Line, + showPoints: VisibilityMode.Auto, + axisPlacement: AxisPlacement.Hidden, + pointSize: 2, +}; + +export const prepareSeries = ( + sparkline: FieldSparkline, + fieldConfig?: FieldConfig +): { frame: DataFrame; warning?: string } => { + const frame = nullToValue(preparePlotFrame(sparkline, fieldConfig)); + if (frame.fields.some((f) => f.values.length <= 1)) { + return { + warning: t( + 'grafana-ui.components.sparkline.warning.too-few-values', + 'Sparkline requires at least two values to render.' + ), + frame, + }; + } + return { frame }; +}; + +export const prepareConfig = ( + sparkline: FieldSparkline, + dataFrame: DataFrame, + theme: GrafanaTheme2 +): UPlotConfigBuilder => { + const builder = new UPlotConfigBuilder(); + // const rangePad = HIGHLIGHT_IDX_POINT_SIZE / 2; + + builder.setCursor({ + show: false, + x: false, // no crosshairs + y: false, + }); + + // X is the first field in the aligned frame + const xField = dataFrame.fields[0]; + builder.addScale({ + scaleKey: 'x', + orientation: ScaleOrientation.Horizontal, + direction: ScaleDirection.Right, + isTime: false, // xField.type === FieldType.time, + range: () => { + if (sparkline.x) { + if (sparkline.timeRange && sparkline.x.type === FieldType.time) { + return [sparkline.timeRange.from.valueOf(), sparkline.timeRange.to.valueOf()]; + } + const vals = sparkline.x.values; + return [vals[0], vals[vals.length - 1]]; + } + return [0, sparkline.y.values.length - 1]; + }, + }); + + builder.addAxis({ + scaleKey: 'x', + theme, + placement: AxisPlacement.Hidden, + }); + + for (let i = 0; i < dataFrame.fields.length; i++) { + const field = dataFrame.fields[i]; + const config: FieldConfig = field.config; + const customConfig: GraphFieldConfig = { + ...defaultConfig, + ...config.custom, + }; + + if (field === xField || field.type !== FieldType.number) { + continue; + } + + const scaleKey = config.unit || '__fixed'; + builder.addScale({ + scaleKey, + orientation: ScaleOrientation.Vertical, + direction: ScaleDirection.Up, + range: () => getYRange(dataFrame), + }); + + builder.addAxis({ + scaleKey, + theme, + placement: AxisPlacement.Hidden, + }); + + const colorMode = getFieldColorModeForField(field); + const seriesColor = colorMode.getCalculator(field, theme)(0, 0); + // TODO: #112977 enable highlight index and adjust padding accordingly + // const hasHighlightIndex = typeof sparkline.highlightIndex === 'number'; + // if (hasHighlightIndex) { + // builder.setPadding([rangePad, rangePad, rangePad, rangePad]); + // } + const pointsMode = + customConfig.drawStyle === GraphDrawStyle.Points // || hasHighlightIndex + ? VisibilityMode.Always + : customConfig.showPoints; + + builder.addSeries({ + pxAlign: false, + scaleKey, + theme, + colorMode, + thresholds: config.thresholds, + drawStyle: customConfig.drawStyle!, + lineColor: customConfig.lineColor ?? seriesColor, + lineWidth: customConfig.lineWidth, + lineInterpolation: customConfig.lineInterpolation, + showPoints: pointsMode, + // TODO: #112977 enable highlight index + pointSize: /* hasHighlightIndex ? HIGHLIGHT_IDX_POINT_SIZE : */ customConfig.pointSize, + // pointsFilter: hasHighlightIndex ? [sparkline.highlightIndex!] : undefined, + fillOpacity: customConfig.fillOpacity, + fillColor: customConfig.fillColor, + lineStyle: customConfig.lineStyle, + gradientMode: customConfig.gradientMode, + spanNulls: customConfig.spanNulls, + }); + } + + return builder; +}; diff --git a/packages/grafana-ui/src/components/Table/TableNG/TableNG.test.tsx b/packages/grafana-ui/src/components/Table/TableNG/TableNG.test.tsx index 56e38b9cd60..ead8014e550 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/TableNG.test.tsx +++ b/packages/grafana-ui/src/components/Table/TableNG/TableNG.test.tsx @@ -451,6 +451,19 @@ describe('TableNG', () => { expect(screen.getByText('A1')).toBeInTheDocument(); expect(screen.getByText('1')).toBeInTheDocument(); }); + + it('shows full column name in title attribute for truncated headers', () => { + const { container } = render( + + ); + + const headers = container.querySelectorAll('[role="columnheader"]'); + const firstHeaderSpan = headers[0].querySelector('span'); + const secondHeaderSpan = headers[1].querySelector('span'); + + expect(firstHeaderSpan).toHaveAttribute('title', 'Column A'); + expect(secondHeaderSpan).toHaveAttribute('title', 'Column B'); + }); }); describe('Footer options', () => { diff --git a/packages/grafana-ui/src/components/Table/TableNG/TableNG.tsx b/packages/grafana-ui/src/components/Table/TableNG/TableNG.tsx index 798ca4e1ae0..f17a62b92cf 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/TableNG.tsx +++ b/packages/grafana-ui/src/components/Table/TableNG/TableNG.tsx @@ -105,6 +105,7 @@ export function TableNG(props: TableNGProps) { const { cellHeight, data, + disableKeyboardEvents, disableSanitizeHtml, enablePagination = false, enableSharedCrosshair = false, @@ -153,8 +154,18 @@ export function TableNG(props: TableNGProps) { const resizeHandler = useColumnResize(onColumnResize); - const rows = useMemo(() => frameToRecords(data), [data]); const hasNestedFrames = useMemo(() => getIsNestedTable(data.fields), [data]); + const nestedFramesFieldName = useMemo(() => { + if (!hasNestedFrames) { + return; + } + const firstNestedField = data.fields.find((f) => f.type === FieldType.nestedFrames); + if (!firstNestedField) { + return; + } + return getDisplayName(firstNestedField); + }, [data, hasNestedFrames]); + const rows = useMemo(() => frameToRecords(data, nestedFramesFieldName), [data, nestedFramesFieldName]); const getTextColorForBackground = useMemo(() => memoize(_getTextColorForBackground, { maxSize: 1000 }), []); const { @@ -373,7 +384,11 @@ export function TableNG(props: TableNGProps) { return null; } - const expandedRecords = applySort(frameToRecords(nestedData), nestedData.fields, sortColumns); + const expandedRecords = applySort( + frameToRecords(nestedData, nestedFramesFieldName), + nestedData.fields, + sortColumns + ); if (!expandedRecords.length) { return (
@@ -397,7 +412,7 @@ export function TableNG(props: TableNGProps) { width: COLUMN.EXPANDER_WIDTH, minWidth: COLUMN.EXPANDER_WIDTH, }), - [commonDataGridProps, data.fields.length, expandedRows, sortColumns, styles] + [commonDataGridProps, data.fields.length, expandedRows, sortColumns, styles, nestedFramesFieldName] ); const fromFields = useCallback( @@ -819,9 +834,9 @@ export function TableNG(props: TableNGProps) { } }} onCellKeyDown={ - hasNestedFrames + hasNestedFrames || disableKeyboardEvents ? (_, event) => { - if (event.isDefaultPrevented()) { + if (disableKeyboardEvents || event.isDefaultPrevented()) { // skip parent grid keyboard navigation if nested grid handled it event.preventGridDefault(); } diff --git a/packages/grafana-ui/src/components/Table/TableNG/components/HeaderCell.tsx b/packages/grafana-ui/src/components/Table/TableNG/components/HeaderCell.tsx index 8ccc73a98b9..fc59c08aa3c 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/components/HeaderCell.tsx +++ b/packages/grafana-ui/src/components/Table/TableNG/components/HeaderCell.tsx @@ -55,7 +55,9 @@ const HeaderCell: React.FC = ({ {showTypeIcons && ( )} - {getDisplayName(field)} + + {displayName} + {direction && ( +
diff --git a/packages/grafana-ui/src/components/Table/TableNG/types.ts b/packages/grafana-ui/src/components/Table/TableNG/types.ts index b828dfddbb6..ddfaf189f34 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/types.ts +++ b/packages/grafana-ui/src/components/Table/TableNG/types.ts @@ -79,7 +79,6 @@ export interface TableRow { // Nested table properties data?: DataFrame; - __nestedFrames?: DataFrame[]; __expanded?: boolean; // For row expansion state // Generic typing for column values @@ -138,6 +137,8 @@ export interface BaseTableProps { enableVirtualization?: boolean; // for MarkdownCell, this flag disables sanitization of HTML content. Configured via config.ini. disableSanitizeHtml?: boolean; + // if true, disables all keyboard events in the table. this is used when previewing a table (i.e. suggestions) + disableKeyboardEvents?: boolean; } /* ---------------------------- Table cell props ---------------------------- */ @@ -260,7 +261,7 @@ export type TableCellStyles = (theme: GrafanaTheme2, options: TableCellStyleOpti export type Comparator = (a: TableCellValue, b: TableCellValue) => number; // Type for converting a DataFrame into an array of TableRows -export type FrameToRowsConverter = (frame: DataFrame) => TableRow[]; +export type FrameToRowsConverter = (frame: DataFrame, nestedFramesFieldName?: string) => TableRow[]; // Type for mapping column names to their field types export type ColumnTypes = Record; diff --git a/packages/grafana-ui/src/components/Table/TableNG/utils.ts b/packages/grafana-ui/src/components/Table/TableNG/utils.ts index 0226f8b6463..b960d8c08c5 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/utils.ts +++ b/packages/grafana-ui/src/components/Table/TableNG/utils.ts @@ -675,10 +675,12 @@ export function applySort( /** * @internal */ -export const frameToRecords = (frame: DataFrame): TableRow[] => { +export const frameToRecords = (frame: DataFrame, nestedFramesFieldName?: string): TableRow[] => { const fnBody = ` const rows = Array(frame.length); const values = frame.fields.map(f => f.values); + const hasNestedFrames = '${nestedFramesFieldName ?? ''}'.length > 0; + let rowCount = 0; for (let i = 0; i < frame.length; i++) { rows[rowCount] = { @@ -686,11 +688,14 @@ export const frameToRecords = (frame: DataFrame): TableRow[] => { __index: i, ${frame.fields.map((field, fieldIdx) => `${JSON.stringify(getDisplayName(field))}: values[${fieldIdx}][i]`).join(',')} }; - rowCount += 1; - if (rows[rowCount-1]['__nestedFrames']){ - const childFrame = rows[rowCount-1]['__nestedFrames']; - rows[rowCount] = {__depth: 1, __index: i, data: childFrame[0]} - rowCount += 1; + rowCount++; + + if (hasNestedFrames) { + const childFrame = rows[rowCount-1][${JSON.stringify(nestedFramesFieldName)}]; + if (childFrame){ + rows[rowCount] = {__depth: 1, __index: i, data: childFrame[0]} + rowCount++; + } } } return rows; @@ -698,8 +703,9 @@ export const frameToRecords = (frame: DataFrame): TableRow[] => { // Creates a function that converts a DataFrame into an array of TableRows // Uses new Function() for performance as it's faster than creating rows using loops - const convert = new Function('frame', fnBody) as FrameToRowsConverter; - return convert(frame); + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + const convert = new Function('frame', 'nestedFramesFieldName', fnBody) as FrameToRowsConverter; + return convert(frame, nestedFramesFieldName); }; /* ----------------------------- Data grid comparator ---------------------------- */ diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegend.story.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegend.story.tsx index cba6f984501..b9af4d23fc4 100644 --- a/packages/grafana-ui/src/components/VizLegend/VizLegend.story.tsx +++ b/packages/grafana-ui/src/components/VizLegend/VizLegend.story.tsx @@ -16,10 +16,6 @@ const meta: Meta = { containerWidth: '100%', seriesCount: 5, }, - parameters: { - // TODO fix a11y issue in story and remove this - a11y: { test: 'off' }, - }, argTypes: { containerWidth: { control: { diff --git a/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx index b0f578fae79..b654a2d3ac6 100644 --- a/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx +++ b/packages/grafana-ui/src/components/VizLegend/VizLegendTable.tsx @@ -29,11 +29,9 @@ export const VizLegendTable = ({ isSortable, }: VizLegendTableProps): JSX.Element => { const styles = useStyles2(getStyles); - const header: Record = {}; - - if (isSortable) { - header[nameSortKey] = ''; - } + const header: Record = { + [nameSortKey]: '', + }; for (const item of items) { if (item.getDisplayValues) { @@ -90,16 +88,18 @@ export const VizLegendTable = ({ - {!isSortable && } {Object.keys(header).map((columnTitle) => ( @@ -87,7 +65,7 @@ export class TeamGroupSync extends PureComponent { ); - } + }; - render() { - const { isAdding, newGroupId } = this.state; - const { groups, isReadOnly } = this.props; - const styles = getStyles(); - return ( -
- {highlightTrial() && ( - + return ( +
+ {highlightTrial() && ( + + )} +
+ {(!highlightTrial() || groups.length > 0) && ( + <> +

+ External group sync +

+ + + + )} -
- {(!highlightTrial() || groups.length > 0) && ( - <> -

- External group sync -

- - - - - )} -
- {groups.length > 0 && ( - - )} -
- - -
- -
- - - - - - - -
-
- - {groups.length === 0 && - !isAdding && - (highlightTrial() ? ( - - ) : ( - - ))} - +
{groups.length > 0 && ( -
-
{ - if (onToggleSort) { + if (onToggleSort && isSortable) { onToggleSort(columnTitle); } }} diff --git a/pkg/api/alerting.go b/pkg/api/alerting.go index 27abb6ebbfc..8fb2f366bf2 100644 --- a/pkg/api/alerting.go +++ b/pkg/api/alerting.go @@ -10,6 +10,7 @@ import ( "github.com/grafana/grafana/pkg/api/response" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" + "github.com/grafana/grafana/pkg/services/ngalert/models" ) func (hs *HTTPServer) GetAlertNotifiers() func(*contextmodel.ReqContext) response.Response { @@ -23,13 +24,13 @@ func (hs *HTTPServer) GetAlertNotifiers() func(*contextmodel.ReqContext) respons } type NotifierPlugin struct { - Type string `json:"type"` - TypeAlias string `json:"typeAlias,omitempty"` - Name string `json:"name"` - Heading string `json:"heading"` - Description string `json:"description"` - Info string `json:"info"` - Options []schema.Field `json:"options"` + Type string `json:"type"` + TypeAlias string `json:"typeAlias,omitempty"` + Name string `json:"name"` + Heading string `json:"heading"` + Description string `json:"description"` + Info string `json:"info"` + Options []Field `json:"options"` } result := make([]*NotifierPlugin, 0, len(v2)) @@ -44,9 +45,56 @@ func (hs *HTTPServer) GetAlertNotifiers() func(*contextmodel.ReqContext) respons Description: s.Description, Heading: s.Heading, Info: s.Info, - Options: v1.Options, + Options: schemaFieldsToFields(s.Type, nil, v1.Options), }) } return response.JSON(http.StatusOK, result) } } + +type Field struct { + Element schema.ElementType `json:"element"` + InputType schema.InputType `json:"inputType"` + Label string `json:"label"` + Description string `json:"description"` + Placeholder string `json:"placeholder"` + PropertyName string `json:"propertyName"` + SelectOptions []schema.SelectOption `json:"selectOptions"` + ShowWhen schema.ShowWhen `json:"showWhen"` + Required bool `json:"required"` + Protected bool `json:"protected,omitempty"` + ValidationRule string `json:"validationRule"` + Secure bool `json:"secure"` + DependsOn string `json:"dependsOn"` + SubformOptions []Field `json:"subformOptions"` +} + +func schemaFieldsToFields(iType schema.IntegrationType, parent schema.IntegrationFieldPath, fields []schema.Field) []Field { + if fields == nil { + return nil + } + result := make([]Field, 0, len(fields)) + for _, f := range fields { + result = append(result, schemaFieldToField(iType, parent, f)) + } + return result +} + +func schemaFieldToField(iType schema.IntegrationType, parent schema.IntegrationFieldPath, f schema.Field) Field { + return Field{ + Element: f.Element, + InputType: f.InputType, + Label: f.Label, + Description: f.Description, + Placeholder: f.Placeholder, + PropertyName: f.PropertyName, + SelectOptions: f.SelectOptions, + ShowWhen: f.ShowWhen, + Required: f.Required, + ValidationRule: f.ValidationRule, + Secure: f.Secure, + DependsOn: f.DependsOn, + SubformOptions: schemaFieldsToFields(iType, append(parent, f.PropertyName), f.SubformOptions), + Protected: models.IsProtectedField(iType, append(parent, f.PropertyName)), + } +} diff --git a/pkg/api/api.go b/pkg/api/api.go index 88f432c206c..da1efa5067f 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -187,6 +187,15 @@ func (hs *HTTPServer) registerRoutes() { publicdashboardsapi.CountPublicDashboardRequest(), hs.Index, ) + + r.Get("/bootdata/:accessToken", + reqNoAuth, + hs.PublicDashboardsApi.Middleware.HandleView, + publicdashboardsapi.SetPublicDashboardAccessToken, + publicdashboardsapi.SetPublicDashboardOrgIdOnContext(hs.PublicDashboardsApi.PublicDashboardService), + publicdashboardsapi.CountPublicDashboardRequest(), + hs.GetBootdata, + ) } r.Get("/explore", authorize(ac.EvalPermission(ac.ActionDatasourcesExplore)), hs.Index) diff --git a/pkg/api/apierrors/folder.go b/pkg/api/apierrors/folder.go index 81b16c3899e..9509ff4ff55 100644 --- a/pkg/api/apierrors/folder.go +++ b/pkg/api/apierrors/folder.go @@ -57,7 +57,11 @@ func ToFolderErrorResponse(err error) response.Response { // --- Kubernetes status errors --- var statusErr *k8sErrors.StatusError if errors.As(err, &statusErr) { - return response.Error(int(statusErr.ErrStatus.Code), statusErr.ErrStatus.Message, err) + message := statusErr.ErrStatus.Message + if message == "" { + message = getDefaultMessageForStatus(int(statusErr.ErrStatus.Code)) + } + return response.Error(int(statusErr.ErrStatus.Code), message, err) } return response.ErrOrFallback(http.StatusInternalServerError, fmt.Sprintf("Folder API error: %s", err.Error()), err) @@ -100,6 +104,19 @@ func ToFolderStatusError(err error) k8sErrors.StatusError { } } +func getDefaultMessageForStatus(statusCode int) string { + switch statusCode { + case http.StatusForbidden: + return "Access denied" + case http.StatusNotFound: + return "Folder not found" + case http.StatusBadRequest: + return "Invalid request" + default: + return "Folder API error" + } +} + func IsForbidden(err error) bool { return k8sErrors.IsForbidden(err) || errors.Is(err, dashboards.ErrFolderAccessDenied) } diff --git a/pkg/api/apierrors/folder_test.go b/pkg/api/apierrors/folder_test.go index 2def7fb48a4..0ca8b16fc87 100644 --- a/pkg/api/apierrors/folder_test.go +++ b/pkg/api/apierrors/folder_test.go @@ -125,7 +125,7 @@ func TestToFolderErrorResponse(t *testing.T) { }, // --- Kubernetes status errors --- { - name: "kubernetes status error", + name: "kubernetes status error with message", input: &k8sErrors.StatusError{ ErrStatus: metav1.Status{ Code: 412, @@ -139,6 +139,66 @@ func TestToFolderErrorResponse(t *testing.T) { }, }), }, + { + name: "kubernetes status error with empty message - 403 forbidden", + input: &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusForbidden, + Message: "", + }, + }, + want: response.Error(http.StatusForbidden, "Access denied", &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusForbidden, + Message: "", + }, + }), + }, + { + name: "kubernetes status error with empty message - 404 not found", + input: &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusNotFound, + Message: "", + }, + }, + want: response.Error(http.StatusNotFound, "Folder not found", &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusNotFound, + Message: "", + }, + }), + }, + { + name: "kubernetes status error with empty message - 400 bad request", + input: &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusBadRequest, + Message: "", + }, + }, + want: response.Error(http.StatusBadRequest, "Invalid request", &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusBadRequest, + Message: "", + }, + }), + }, + { + name: "kubernetes status error with empty message - default fallback", + input: &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusInternalServerError, + Message: "", + }, + }, + want: response.Error(http.StatusInternalServerError, "Folder API error", &k8sErrors.StatusError{ + ErrStatus: metav1.Status{ + Code: http.StatusInternalServerError, + Message: "", + }, + }), + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index 5ebbca411eb..a560ff47c5d 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -380,13 +380,6 @@ func (hs *HTTPServer) deleteDashboard(c *contextmodel.ReqContext) response.Respo return dashboardErrResponse(err, "Failed to delete dashboard") } - if hs.Live != nil { - err := hs.Live.GrafanaScope.Dashboards.DashboardDeleted(c.GetOrgID(), c.SignedInUser, dash.UID) - if err != nil { - hs.log.Error("Failed to broadcast delete info", "dashboard", dash.UID, "error", err) - } - } - return response.JSON(http.StatusOK, util.DynMap{ "title": dash.Title, "message": fmt.Sprintf("Dashboard %s deleted", dash.Title), @@ -482,31 +475,6 @@ func (hs *HTTPServer) postDashboard(c *contextmodel.ReqContext, cmd dashboards.S } dashboard, saveErr := hs.DashboardService.SaveDashboard(ctx, dashItem, allowUiUpdate) - - if hs.Live != nil { - // Tell everyone listening that the dashboard changed - if dashboard == nil { - dashboard = dash // the original request - } - - // This will broadcast all save requests only if a `gitops` observer exists. - // gitops is useful when trying to save dashboards in an environment where the user can not save - channel := hs.Live.GrafanaScope.Dashboards - liveerr := channel.DashboardSaved(c.GetOrgID(), c.SignedInUser, cmd.Message, dashboard, saveErr) - - // When an error exists, but the value broadcast to a gitops listener return 202 - if liveerr == nil && saveErr != nil && channel.HasGitOpsObserver(c.GetOrgID()) { - return response.JSON(http.StatusAccepted, util.DynMap{ - "status": "pending", - "message": "changes were broadcast to the gitops listener", - }) - } - - if liveerr != nil { - hs.log.Warn("Unable to broadcast save event", "uid", dashboard.UID, "error", liveerr) - } - } - if saveErr != nil { return apierrors.ToDashboardErrorResponse(ctx, hs.pluginStore, saveErr) } @@ -525,7 +493,9 @@ func (hs *HTTPServer) postDashboard(c *contextmodel.ReqContext, cmd dashboards.S // swagger:route GET /dashboards/home dashboards getHomeDashboard // -// Get home dashboard. +// NOTE: the home dashboard is configured in preferences. This API will be removed in G13 +// +// Deprecated: true // // Responses: // 200: getHomeDashboardResponse diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index 6c140667a37..7a667ee5e62 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -111,20 +111,16 @@ func TestGetHomeDashboard(t *testing.T) { } } -func newTestLive(t *testing.T, store db.DB) *live.GrafanaLive { - features := featuremgmt.WithFeatures() +func newTestLive(t *testing.T) *live.GrafanaLive { cfg := setting.NewCfg() cfg.AppURL = "http://localhost:3000/" - gLive, err := live.ProvideService(nil, cfg, + gLive, err := live.ProvideService(cfg, routing.NewRouteRegister(), nil, nil, nil, nil, - store, - nil, &usagestats.UsageStatsMock{T: t}, - nil, - features, acimpl.ProvideAccessControl(features), - &dashboards.FakeDashboardService{}, - nil, nil) + featuremgmt.WithFeatures(), + &dashboards.FakeDashboardService{}, nil) + require.NoError(t, err) return gLive } @@ -751,7 +747,7 @@ func TestIntegrationDashboardAPIEndpoint(t *testing.T) { hs := HTTPServer{ Cfg: cfg, ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()), - Live: newTestLive(t, db.InitTestDB(t)), + Live: newTestLive(t), QuotaService: quotatest.New(false, nil), LibraryElementService: &libraryelementsfake.LibraryElementService{}, DashboardService: dashboardService, @@ -1003,7 +999,7 @@ func postDashboardScenario(t *testing.T, desc string, url string, routePattern s hs := HTTPServer{ Cfg: cfg, ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()), - Live: newTestLive(t, db.InitTestDB(t)), + Live: newTestLive(t), QuotaService: quotatest.New(false, nil), pluginStore: &pluginstore.FakePluginStore{}, LibraryElementService: &libraryelementsfake.LibraryElementService{}, @@ -1043,7 +1039,7 @@ func restoreDashboardVersionScenario(t *testing.T, desc string, url string, rout hs := HTTPServer{ Cfg: cfg, ProvisioningService: provisioning.NewProvisioningServiceMock(context.Background()), - Live: newTestLive(t, db.InitTestDB(t)), + Live: newTestLive(t), QuotaService: quotatest.New(false, nil), LibraryElementService: &libraryelementsfake.LibraryElementService{}, DashboardService: mock, diff --git a/pkg/api/datasources_test.go b/pkg/api/datasources_test.go index e2f951b0a37..dd0b39e13a7 100644 --- a/pkg/api/datasources_test.go +++ b/pkg/api/datasources_test.go @@ -343,7 +343,7 @@ func TestUpdateDataSourceByID_DataSourceNameExists(t *testing.T) { Cfg: setting.NewCfg(), AccessControl: acimpl.ProvideAccessControl(featuremgmt.WithFeatures()), accesscontrolService: actest.FakeService{}, - Live: newTestLive(t, nil), + Live: newTestLive(t), } sc := setupScenarioContext(t, "/api/datasources/1") @@ -450,7 +450,7 @@ func TestAPI_datasources_AccessControl(t *testing.T) { hs.Cfg = setting.NewCfg() hs.DataSourcesService = &dataSourcesServiceMock{expectedDatasource: &datasources.DataSource{}} hs.accesscontrolService = actest.FakeService{} - hs.Live = newTestLive(t, hs.SQLStore) + hs.Live = newTestLive(t) hs.promRegister, hs.dsConfigHandlerRequestsDuration = setupDsConfigHandlerMetrics() }) diff --git a/pkg/api/dtos/live.go b/pkg/api/dtos/live.go deleted file mode 100644 index 6b524584187..00000000000 --- a/pkg/api/dtos/live.go +++ /dev/null @@ -1,11 +0,0 @@ -package dtos - -import "encoding/json" - -type LivePublishCmd struct { - Channel string `json:"channel"` - Data json.RawMessage `json:"data,omitempty"` -} - -type LivePublishResponse struct { -} diff --git a/pkg/api/http_server.go b/pkg/api/http_server.go index f2ac32a80c6..0898a5ecb66 100644 --- a/pkg/api/http_server.go +++ b/pkg/api/http_server.go @@ -638,7 +638,7 @@ func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() { m := hs.web m.Use(requestmeta.SetupRequestMetadata()) - m.Use(middleware.RequestTracing(hs.tracer, middleware.SkipTracingPaths)) + m.Use(middleware.RequestTracing(hs.tracer, middleware.ShouldTraceWithExceptions)) m.Use(middleware.RequestMetrics(hs.Features, hs.Cfg, hs.promRegister)) m.UseMiddleware(hs.LoggerMiddleware.Middleware()) diff --git a/pkg/api/org_users.go b/pkg/api/org_users.go index 8a10cc24944..37b459f0e69 100644 --- a/pkg/api/org_users.go +++ b/pkg/api/org_users.go @@ -294,6 +294,7 @@ func (hs *HTTPServer) SearchOrgUsersWithPaging(c *contextmodel.ReqContext) respo } func (hs *HTTPServer) searchOrgUsersHelper(c *contextmodel.ReqContext, query *org.SearchOrgUsersQuery) (*org.SearchOrgUsersQueryResult, error) { + query.ExcludeHiddenUsers = true result, err := hs.orgService.SearchOrgUsers(c.Req.Context(), query) if err != nil { return nil, err @@ -303,9 +304,6 @@ func (hs *HTTPServer) searchOrgUsersHelper(c *contextmodel.ReqContext, query *or userIDs := map[string]bool{} authLabelsUserIDs := make([]int64, 0, len(result.OrgUsers)) for _, user := range result.OrgUsers { - if dtos.IsHiddenUser(user.Login, c.SignedInUser, hs.Cfg) { - continue - } user.AvatarURL = dtos.GetGravatarUrl(hs.Cfg, user.Email) userIDs[fmt.Sprint(user.UserID)] = true diff --git a/pkg/api/org_users_test.go b/pkg/api/org_users_test.go index a43b5c7edcf..c8313ecefce 100644 --- a/pkg/api/org_users_test.go +++ b/pkg/api/org_users_test.go @@ -171,11 +171,16 @@ func TestIntegrationOrgUsersAPIEndpoint_userLoggedIn(t *testing.T) { orgService.ExpectedSearchOrgUsersResult = &org.SearchOrgUsersQueryResult{ OrgUsers: []*org.OrgUserDTO{ {Login: testUserLogin, Email: "testUser@grafana.com"}, - {Login: "user1", Email: "user1@grafana.com"}, {Login: "user2", Email: "user2@grafana.com"}, }, } + orgService.SearchOrgUsersFn = func(ctx context.Context, query *org.SearchOrgUsersQuery) (*org.SearchOrgUsersQueryResult, error) { + require.True(t, query.ExcludeHiddenUsers) + return orgService.ExpectedSearchOrgUsersResult, nil + } + defer func() { orgService.SearchOrgUsersFn = nil }() + sc.handlerFunc = hs.GetOrgUsersForCurrentOrg sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() @@ -191,6 +196,18 @@ func TestIntegrationOrgUsersAPIEndpoint_userLoggedIn(t *testing.T) { loggedInUserScenarioWithRole(t, "When calling GET as an admin on", "GET", "api/org/users/lookup", "api/org/users/lookup", org.RoleAdmin, func(sc *scenarioContext) { + orgService.ExpectedSearchOrgUsersResult = &org.SearchOrgUsersQueryResult{ + OrgUsers: []*org.OrgUserDTO{ + {Login: testUserLogin, Email: "testUser@grafana.com"}, + {Login: "user2", Email: "user2@grafana.com"}, + }, + } + orgService.SearchOrgUsersFn = func(ctx context.Context, query *org.SearchOrgUsersQuery) (*org.SearchOrgUsersQueryResult, error) { + require.True(t, query.ExcludeHiddenUsers) + return orgService.ExpectedSearchOrgUsersResult, nil + } + defer func() { orgService.SearchOrgUsersFn = nil }() + sc.handlerFunc = hs.GetOrgUsersForCurrentOrgLookup sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() diff --git a/pkg/apimachinery/identity/context.go b/pkg/apimachinery/identity/context.go index 984a9b24831..c66b4188cbf 100644 --- a/pkg/apimachinery/identity/context.go +++ b/pkg/apimachinery/identity/context.go @@ -161,6 +161,8 @@ var serviceIdentityTokenPermissions = []string{ "preferences.grafana.app:*", // user, team, and org preferences "collections.grafana.app:*", // user stars "plugins.grafana.app:*", + "historian.alerting.grafana.app:*", + "advisor.grafana.app:*", // Secrets Manager uses a custom verb for secret decryption, and its authorizer does not allow wildcard permissions. "secret.grafana.app/securevalues:decrypt", diff --git a/pkg/apiserver/auditing/noop.go b/pkg/apiserver/auditing/noop.go new file mode 100644 index 00000000000..5a6b39a3b71 --- /dev/null +++ b/pkg/apiserver/auditing/noop.go @@ -0,0 +1,36 @@ +package auditing + +import ( + auditinternal "k8s.io/apiserver/pkg/apis/audit" + "k8s.io/apiserver/pkg/audit" + "k8s.io/apiserver/pkg/authorization/authorizer" +) + +// NoopBackend is a no-op implementation of audit.Backend +type NoopBackend struct{} + +func ProvideNoopBackend() audit.Backend { return &NoopBackend{} } + +func (b *NoopBackend) ProcessEvents(k8sEvents ...*auditinternal.Event) bool { return false } + +func (NoopBackend) Run(stopCh <-chan struct{}) error { return nil } + +func (NoopBackend) Shutdown() {} + +func (NoopBackend) String() string { return "" } + +// NoopPolicyRuleProvider is a no-op implementation of PolicyRuleProvider +type NoopPolicyRuleProvider struct{} + +func ProvideNoopPolicyRuleProvider() PolicyRuleProvider { return &NoopPolicyRuleProvider{} } + +func (NoopPolicyRuleProvider) PolicyRuleProvider(PolicyRuleEvaluators) audit.PolicyRuleEvaluator { + return NoopPolicyRuleEvaluator{} +} + +// NoopPolicyRuleEvaluator is a no-op implementation of audit.PolicyRuleEvaluator +type NoopPolicyRuleEvaluator struct{} + +func (NoopPolicyRuleEvaluator) EvaluatePolicyRule(authorizer.Attributes) audit.RequestAuditConfig { + return audit.RequestAuditConfig{Level: auditinternal.LevelNone} +} diff --git a/pkg/apiserver/auditing/policy.go b/pkg/apiserver/auditing/policy.go new file mode 100644 index 00000000000..e88acf7c4cc --- /dev/null +++ b/pkg/apiserver/auditing/policy.go @@ -0,0 +1,59 @@ +package auditing + +import ( + "slices" + + "github.com/grafana/grafana/pkg/apimachinery/utils" + "k8s.io/apimachinery/pkg/runtime/schema" + auditinternal "k8s.io/apiserver/pkg/apis/audit" + "k8s.io/apiserver/pkg/audit" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/authorization/authorizer" +) + +// PolicyRuleEvaluators is a map of API group+version to audit.PolicyRuleEvaluator +type PolicyRuleEvaluators = map[schema.GroupVersion]audit.PolicyRuleEvaluator + +type PolicyRuleProvider interface { + PolicyRuleProvider(evaluators PolicyRuleEvaluators) audit.PolicyRuleEvaluator +} + +// PolicyRuleEvaluator alias for easier imports. +type PolicyRuleEvaluator = audit.PolicyRuleEvaluator + +// DefaultGrafanaPolicyRuleEvaluator provides a sane default configuration for audit logging for API group+versions. +type defaultGrafanaPolicyRuleEvaluator struct{} + +var _ PolicyRuleEvaluator = &defaultGrafanaPolicyRuleEvaluator{} + +func NewDefaultGrafanaPolicyRuleEvaluator() audit.PolicyRuleEvaluator { + return defaultGrafanaPolicyRuleEvaluator{} +} + +func (defaultGrafanaPolicyRuleEvaluator) EvaluatePolicyRule(attrs authorizer.Attributes) audit.RequestAuditConfig { + // Skip non-resource and watch requests otherwise it is too noisy. + if !attrs.IsResourceRequest() || attrs.GetVerb() == utils.VerbWatch { + return audit.RequestAuditConfig{ + Level: auditinternal.LevelNone, + } + } + + // Skip auditing if the user is part of the privileged group. + // The loopback client uses this group, so requests initiated in `/api/` would be duplicated. + if u := attrs.GetUser(); u != nil && slices.Contains(u.GetGroups(), user.SystemPrivilegedGroup) { + return audit.RequestAuditConfig{ + Level: auditinternal.LevelNone, + } + } + + return audit.RequestAuditConfig{ + Level: auditinternal.LevelMetadata, + OmitStages: []auditinternal.Stage{ + // Only log on StageResponseComplete + auditinternal.StageRequestReceived, + auditinternal.StageResponseStarted, + auditinternal.StagePanic, + }, + OmitManagedFields: false, // Setting it to true causes extra copying/unmarshalling. + } +} diff --git a/pkg/apiserver/auditing/policy_test.go b/pkg/apiserver/auditing/policy_test.go new file mode 100644 index 00000000000..af18f9110fd --- /dev/null +++ b/pkg/apiserver/auditing/policy_test.go @@ -0,0 +1,73 @@ +package auditing_test + +import ( + "testing" + + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/apiserver/auditing" + "github.com/stretchr/testify/require" + auditinternal "k8s.io/apiserver/pkg/apis/audit" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/authorization/authorizer" +) + +func TestDefaultGrafanaPolicyRuleEvaluator(t *testing.T) { + t.Parallel() + + evaluator := auditing.NewDefaultGrafanaPolicyRuleEvaluator() + require.NotNil(t, evaluator) + + t.Run("returns audit level none for non-resource requests", func(t *testing.T) { + t.Parallel() + + attrs := authorizer.AttributesRecord{ + ResourceRequest: false, + } + + config := evaluator.EvaluatePolicyRule(attrs) + require.Equal(t, auditinternal.LevelNone, config.Level) + }) + + t.Run("returns audit level none for watch requests", func(t *testing.T) { + t.Parallel() + + attrs := authorizer.AttributesRecord{ + ResourceRequest: true, + Verb: utils.VerbWatch, + } + + config := evaluator.EvaluatePolicyRule(attrs) + require.Equal(t, auditinternal.LevelNone, config.Level) + }) + + t.Run("returns audit level none for requests from privileged group", func(t *testing.T) { + t.Parallel() + + attrs := authorizer.AttributesRecord{ + ResourceRequest: true, + Verb: utils.VerbCreate, + User: &user.DefaultInfo{ + Groups: []string{"test-group", user.SystemPrivilegedGroup}, + }, + } + + config := evaluator.EvaluatePolicyRule(attrs) + require.Equal(t, auditinternal.LevelNone, config.Level) + }) + + t.Run("return audit level metadata for other resource requests", func(t *testing.T) { + t.Parallel() + + attrs := authorizer.AttributesRecord{ + ResourceRequest: true, + Verb: utils.VerbCreate, + User: &user.DefaultInfo{ + Name: "test-user", + Groups: []string{"test-group"}, + }, + } + + config := evaluator.EvaluatePolicyRule(attrs) + require.Equal(t, auditinternal.LevelMetadata, config.Level) + }) +} diff --git a/pkg/extensions/enterprise_imports.go b/pkg/extensions/enterprise_imports.go index fbff17523fc..472652cc103 100644 --- a/pkg/extensions/enterprise_imports.go +++ b/pkg/extensions/enterprise_imports.go @@ -56,8 +56,7 @@ import ( _ "github.com/grafana/e2e" _ "github.com/grafana/gofpdf" _ "github.com/grafana/gomemcache/memcache" - _ "github.com/grafana/tempo/pkg/traceql" - _ "github.com/grafana/grafana/apps/alerting/alertenrichment/pkg/apis/alertenrichment/v1beta1" _ "github.com/grafana/grafana/apps/scope/pkg/apis/scope/v0alpha1" + _ "github.com/grafana/tempo/pkg/traceql" ) diff --git a/pkg/kinds/dashboard/dashboard_spec_gen.go b/pkg/kinds/dashboard/dashboard_spec_gen.go index bd73e527534..7d2a0ba5439 100644 --- a/pkg/kinds/dashboard/dashboard_spec_gen.go +++ b/pkg/kinds/dashboard/dashboard_spec_gen.go @@ -204,6 +204,9 @@ type Panel struct { Options map[string]any `json:"options,omitempty"` // Field options allow you to change how the data is displayed in your visualizations. FieldConfig *FieldConfigSource `json:"fieldConfig,omitempty"` + // When a panel is migrated from a previous version (Angular to React), this field is set to the original panel type. + // This is used to determine the original panel type when migrating to a new version so the plugin migration can be applied. + AutoMigrateFrom *string `json:"autoMigrateFrom,omitempty"` } // NewPanel creates a new Panel object. diff --git a/pkg/middleware/request_tracing.go b/pkg/middleware/request_tracing.go index 998b20d7dbb..c06142a936a 100644 --- a/pkg/middleware/request_tracing.go +++ b/pkg/middleware/request_tracing.go @@ -73,16 +73,20 @@ func RouteOperationName(req *http.Request) (string, bool) { return "", false } -// Paths that don't need tracing spans applied to them because of the -// little value that would provide us -func SkipTracingPaths(req *http.Request) bool { - return strings.HasPrefix(req.URL.Path, "/public/") || +func ShouldTraceWithExceptions(req *http.Request) bool { + // Paths that don't need tracing spans applied to them because of the + // little value that would provide us + if strings.HasPrefix(req.URL.Path, "/public/") || req.URL.Path == "/robots.txt" || req.URL.Path == "/favicon.ico" || - req.URL.Path == "/api/health" + req.URL.Path == "/api/health" { + return false + } + + return true } -func TraceAllPaths(req *http.Request) bool { +func ShouldTraceAllPaths(req *http.Request) bool { return true } diff --git a/pkg/operators/iam/zanzana_folder_reconciler.go b/pkg/operators/iam/zanzana_folder_reconciler.go index 0f2fb287bb4..ee2233d7877 100644 --- a/pkg/operators/iam/zanzana_folder_reconciler.go +++ b/pkg/operators/iam/zanzana_folder_reconciler.go @@ -11,15 +11,16 @@ import ( "os/signal" "syscall" + "github.com/prometheus/client_golang/prometheus" + "k8s.io/client-go/rest" + "k8s.io/client-go/transport" + "github.com/grafana/grafana-app-sdk/logging" "github.com/grafana/grafana-app-sdk/operator" folder "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" "github.com/grafana/grafana/apps/iam/pkg/app" "github.com/grafana/grafana/pkg/server" "github.com/grafana/grafana/pkg/setting" - "github.com/prometheus/client_golang/prometheus" - "k8s.io/client-go/rest" - "k8s.io/client-go/transport" "github.com/grafana/authlib/authn" utilnet "k8s.io/apimachinery/pkg/util/net" @@ -95,7 +96,7 @@ func buildIAMConfigFromSettings(cfg *setting.Cfg, registerer prometheus.Register if zanzanaURL == "" { return nil, fmt.Errorf("zanzana_url is required in [operator] section") } - iamCfg.AppConfig.ZanzanaClientCfg.URL = zanzanaURL + iamCfg.AppConfig.ZanzanaClientCfg.Addr = zanzanaURL iamCfg.AppConfig.InformerConfig.MaxConcurrentWorkers = operatorSec.Key("max_concurrent_workers").MustUint64(20) diff --git a/pkg/registry/apis/collections/legacy/stars.go b/pkg/registry/apis/collections/legacy/stars.go index 8c7d9e711ea..39f7a9c088f 100644 --- a/pkg/registry/apis/collections/legacy/stars.go +++ b/pkg/registry/apis/collections/legacy/stars.go @@ -204,11 +204,14 @@ func (s *DashboardStarsStorage) write(ctx context.Context, obj *collections.Star previous[v] = true } } - for _, dashboard := range stars { + for idx, dashboard := range stars { if previous[dashboard] { delete(previous, dashboard) continue // nothing needed } + if idx > 0 { + time.Sleep(75 * time.Millisecond) // values are ordered by update time; this keeps the order predictable + } err = s.stars.Add(ctx, &star.StarDashboardCommand{ UserID: user.ID, OrgID: user.OrgID, diff --git a/pkg/registry/apis/collections/register.go b/pkg/registry/apis/collections/register.go index 9be4412c377..699d3bbe672 100644 --- a/pkg/registry/apis/collections/register.go +++ b/pkg/registry/apis/collections/register.go @@ -46,12 +46,6 @@ func RegisterAPIService( users user.Service, apiregistration builder.APIRegistrar, ) *APIBuilder { - // Requires development settings and clearly experimental - //nolint:staticcheck // not yet migrated to OpenFeature - if !features.IsEnabledGlobally(featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs) { - return nil - } - sql := legacy.NewLegacySQL(legacysql.NewDatabaseProvider(db)) builder := &APIBuilder{ authorizer: &utils.AuthorizeFromName{ diff --git a/pkg/registry/apis/dashboard/dashboard_storage.go b/pkg/registry/apis/dashboard/dashboard_storage.go index d2d54c8d815..7ab91f8ec66 100644 --- a/pkg/registry/apis/dashboard/dashboard_storage.go +++ b/pkg/registry/apis/dashboard/dashboard_storage.go @@ -7,20 +7,41 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/registry/rest" + "github.com/grafana/grafana-app-sdk/logging" grafanarest "github.com/grafana/grafana/pkg/apiserver/rest" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/apiserver/endpoints/request" + "github.com/grafana/grafana/pkg/services/live" ) -// dashboardStoragePermissionWrapper is a wrapper around the grafanarest.Storage that adds dashboard permissions handling -// when dual writing is enabled. -type dashboardStoragePermissionWrapper struct { - dashboardPermissionsSvc accesscontrol.DashboardPermissionsService +// dashboardStorageWrapper is a wrapper around the grafanarest.Storage so it will: +// 1. support adds dashboard permissions handling +// 2. broadcast changes to grafana live +// when running in single tenant mode +type dashboardStorageWrapper struct { grafanarest.Storage + + dashboardPermissionsSvc accesscontrol.DashboardPermissionsService + live live.DashboardActivityChannel } -func (d dashboardStoragePermissionWrapper) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { - info, err := request.NamespaceInfoFrom(ctx, true) +func (d dashboardStorageWrapper) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) { + ns, err := request.NamespaceInfoFrom(ctx, true) + if err != nil { + return nil, false, err + } + + obj, created, err := d.Storage.Update(ctx, name, objInfo, createValidation, updateValidation, forceAllowCreate, options) + if err == nil && ns.OrgID > 0 && d.live != nil { + if err := d.live.DashboardSaved(ns.OrgID, name); err != nil { + logging.FromContext(ctx).Info("live dashboard update failed", "err", err) + } + } + return obj, created, err +} + +func (d dashboardStorageWrapper) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { + ns, err := request.NamespaceInfoFrom(ctx, true) if err != nil { return nil, false, err } @@ -28,7 +49,12 @@ func (d dashboardStoragePermissionWrapper) Delete(ctx context.Context, name stri if err != nil { return obj, async, err } - if accessErr := d.dashboardPermissionsSvc.DeleteResourcePermissions(ctx, info.OrgID, name); accessErr != nil { + if ns.OrgID > 0 && d.live != nil { + if err := d.live.DashboardDeleted(ns.OrgID, name); err != nil { + logging.FromContext(ctx).Info("live dashboard update failed", "err", err) + } + } + if accessErr := d.dashboardPermissionsSvc.DeleteResourcePermissions(ctx, ns.OrgID, name); accessErr != nil { return obj, async, accessErr } return obj, async, nil diff --git a/pkg/registry/apis/dashboard/legacy/queries_test.go b/pkg/registry/apis/dashboard/legacy/queries_test.go index 1345bfc2925..ec865873960 100644 --- a/pkg/registry/apis/dashboard/legacy/queries_test.go +++ b/pkg/registry/apis/dashboard/legacy/queries_test.go @@ -100,6 +100,42 @@ func TestDashboardQueries(t *testing.T) { Order: "ASC", }), }, + { + // Tests that MaxRows generates LIMIT clause for regular dashboard queries + Name: "dashboard_with_max_rows", + Data: getQuery(&DashboardQuery{ + OrgID: 2, + MaxRows: 100, + }), + }, + { + // Tests that MaxRows generates LIMIT clause for history queries + Name: "history_with_max_rows", + Data: getQuery(&DashboardQuery{ + OrgID: 1, + GetHistory: true, + MaxRows: 50, + }), + }, + { + // Tests that MaxRows + LastID generates correct pagination query + Name: "dashboard_with_max_rows_last_id", + Data: getQuery(&DashboardQuery{ + OrgID: 2, + MaxRows: 100, + LastID: 500, + }), + }, + { + // Tests that MaxRows + LastID generates correct pagination query + Name: "history_with_max_rows_last_id", + Data: getQuery(&DashboardQuery{ + OrgID: 2, + MaxRows: 100, + GetHistory: true, + LastID: 500, + }), + }, }, sqlQueryPanels: { { diff --git a/pkg/registry/apis/dashboard/legacy/query_dashboards.sql b/pkg/registry/apis/dashboard/legacy/query_dashboards.sql index e8503170a2c..b32c5aa3465 100644 --- a/pkg/registry/apis/dashboard/legacy/query_dashboards.sql +++ b/pkg/registry/apis/dashboard/legacy/query_dashboards.sql @@ -71,6 +71,9 @@ WHERE dashboard.is_folder = {{ .Arg .Query.GetFolders }} COALESCE(dashboard_version.version, dashboard.version) {{ .Query.Order }}, {{ end }} dashboard.uid ASC + {{ if .Query.MaxRows }} + LIMIT {{ .Arg .Query.MaxRows }} + {{ end }} {{ else }} {{ if .Query.UID }} AND dashboard.uid = {{ .Arg .Query.UID }} @@ -83,4 +86,7 @@ WHERE dashboard.is_folder = {{ .Arg .Query.GetFolders }} AND dashboard.deleted IS NULL {{ end }} ORDER BY dashboard.id DESC + {{ if .Query.MaxRows }} + LIMIT {{ .Arg .Query.MaxRows }} + {{ end }} {{ end }} diff --git a/pkg/registry/apis/dashboard/legacy/sql_dashboards.go b/pkg/registry/apis/dashboard/legacy/sql_dashboards.go index fbb0e825cd1..077cf0a6700 100644 --- a/pkg/registry/apis/dashboard/legacy/sql_dashboards.go +++ b/pkg/registry/apis/dashboard/legacy/sql_dashboards.go @@ -712,6 +712,128 @@ func (r *rowsWrapper) Value() []byte { return b } +// batchingIterator wraps rowsWrapper to fetch data in batches +type batchingIterator struct { + wrapper *rowsWrapper + a *dashboardSqlAccess + ctx context.Context + helper *legacysql.LegacyDatabaseHelper + query *DashboardQuery + batchSize int + done bool + err error +} + +var _ resource.ListIterator = (*batchingIterator)(nil) + +func (b *batchingIterator) Error() error { + if b.err != nil { + return b.err + } + return b.wrapper.Error() +} + +func (b *batchingIterator) ContinueToken() string { + return b.wrapper.ContinueToken() +} + +func (b *batchingIterator) ResourceVersion() int64 { + return b.wrapper.ResourceVersion() +} + +func (b *batchingIterator) Namespace() string { + return b.wrapper.Namespace() +} + +func (b *batchingIterator) Name() string { + return b.wrapper.Name() +} + +func (b *batchingIterator) Folder() string { + return b.wrapper.Folder() +} + +func (b *batchingIterator) Value() []byte { + return b.wrapper.Value() +} + +func (b *batchingIterator) Close() error { + return b.wrapper.Close() +} + +func newBatchingIterator(ctx context.Context, a *dashboardSqlAccess, helper *legacysql.LegacyDatabaseHelper, query *DashboardQuery) (*batchingIterator, error) { + iter := &batchingIterator{ + a: a, + ctx: ctx, + helper: helper, + query: query, + batchSize: query.MaxRows, + } + + // Loads the first batch + if err := iter.nextBatch(query.LastID); err != nil { + return nil, err + } + return iter, nil +} + +func (b *batchingIterator) nextBatch(lastID int64) error { + b.query.LastID = lastID + wrapper, err := b.a.getRows(b.ctx, b.helper, b.query) + if err != nil { + return err + } + b.wrapper = wrapper + return nil +} + +func (b *batchingIterator) Next() bool { + if b.done { + return false + } + + // Try to get next row from current batch + if b.wrapper.Next() { + return true + } + + // Check for errors in current wrapper + if b.Error() != nil { + return false + } + + // No more rows in current batch - close it + if err := b.wrapper.Close(); err != nil { + // Should not happen, but handle it + b.err = err + b.done = true + return false + } + + // Current batch exhausted - check if we got a full batch (might be more data) + if b.wrapper.count < b.batchSize { + // Got fewer rows than batch size, so we're done + b.done = true + return false + } + + // Fetch next batch with LastID from last row + if err := b.nextBatch(b.wrapper.row.token.id); err != nil { + b.err = err + b.done = true + return false + } + + // Try to get first row from new batch + if b.wrapper.Next() { + return true + } + + // New batch is empty, we're done + b.done = true + return false +} + func generateFallbackDashboard(data []byte, title, uid string) ([]byte, error) { generatedDashboard := map[string]interface{}{ "editable": true, diff --git a/pkg/registry/apis/dashboard/legacy/storage.go b/pkg/registry/apis/dashboard/legacy/storage.go index 1521021c424..3d4eb6dcd91 100644 --- a/pkg/registry/apis/dashboard/legacy/storage.go +++ b/pkg/registry/apis/dashboard/legacy/storage.go @@ -305,11 +305,19 @@ func (a *dashboardSqlAccess) ListIterator(ctx context.Context, req *resourcepb.L return 0, fmt.Errorf("token and orgID mismatch") } + // Default batch size for iterator - fetch rows in batches to avoid slow queries + const defaultMaxRows = 500 + maxRows := defaultMaxRows + if req.Limit > 0 && req.Limit < int64(defaultMaxRows) { + maxRows = int(req.Limit) + } + query := &DashboardQuery{ - OrgID: info.OrgID, - Limit: int(req.Limit), - LastID: token.id, - Labels: req.Options.Labels, + OrgID: info.OrgID, + Limit: int(req.Limit), + MaxRows: maxRows, + LastID: token.id, + Labels: req.Options.Labels, } sql, err := a.sql(ctx) @@ -332,14 +340,15 @@ func (a *dashboardSqlAccess) ListIterator(ctx context.Context, req *resourcepb.L return 0, err } listRV *= 1000 // Convert to microseconds - rows, err := a.getRows(ctx, sql, query) - if rows != nil { + + iter, err := newBatchingIterator(ctx, a, sql, query) + if iter != nil { defer func() { - _ = rows.Close() + _ = iter.Close() }() } if err == nil { - err = cb(rows) + err = cb(iter) } return listRV, err } diff --git a/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows.sql new file mode 100755 index 00000000000..2470760c9e3 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows.sql @@ -0,0 +1,31 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM `grafana`.`dashboard` as dashboard +LEFT OUTER JOIN `grafana`.`dashboard_provisioning` as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN `grafana`.`user` as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN `grafana`.`user` as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows_last_id.sql new file mode 100755 index 00000000000..d6c5ce10313 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-dashboard_with_max_rows_last_id.sql @@ -0,0 +1,32 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM `grafana`.`dashboard` as dashboard +LEFT OUTER JOIN `grafana`.`dashboard_provisioning` as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN `grafana`.`user` as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN `grafana`.`user` as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.id < 500 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows.sql new file mode 100755 index 00000000000..96efe4956a9 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows.sql @@ -0,0 +1,34 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM `grafana`.`dashboard` as dashboard +LEFT OUTER JOIN `grafana`.`dashboard_version` as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN `grafana`.`dashboard_provisioning` as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN `grafana`.`user` as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN `grafana`.`user` as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 1 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 50 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows_last_id.sql new file mode 100755 index 00000000000..f5934ab44d1 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/mysql--query_dashboards-history_with_max_rows_last_id.sql @@ -0,0 +1,35 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM `grafana`.`dashboard` as dashboard +LEFT OUTER JOIN `grafana`.`dashboard_version` as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN `grafana`.`dashboard_provisioning` as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN `grafana`.`user` as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN `grafana`.`user` as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard_version.version < 500 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows.sql new file mode 100755 index 00000000000..2cdb3115aec --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows.sql @@ -0,0 +1,31 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows_last_id.sql new file mode 100755 index 00000000000..6994bf56bd4 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-dashboard_with_max_rows_last_id.sql @@ -0,0 +1,32 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.id < 500 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows.sql new file mode 100755 index 00000000000..18a557c9dfd --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows.sql @@ -0,0 +1,34 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_version" as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 1 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 50 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows_last_id.sql new file mode 100755 index 00000000000..b1930157b6e --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/postgres--query_dashboards-history_with_max_rows_last_id.sql @@ -0,0 +1,35 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_version" as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard_version.version < 500 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows.sql new file mode 100755 index 00000000000..2cdb3115aec --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows.sql @@ -0,0 +1,31 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows_last_id.sql new file mode 100755 index 00000000000..6994bf56bd4 --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-dashboard_with_max_rows_last_id.sql @@ -0,0 +1,32 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard.updated, + updated_user.uid as updated_by, + dashboard.updated_by as updated_by_id, + dashboard.version, + '' as message, + dashboard.data, + dashboard.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard.updated_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard.id < 500 + AND dashboard.deleted IS NULL + ORDER BY dashboard.id DESC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows.sql b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows.sql new file mode 100755 index 00000000000..18a557c9dfd --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows.sql @@ -0,0 +1,34 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_version" as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 1 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 50 diff --git a/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows_last_id.sql b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows_last_id.sql new file mode 100755 index 00000000000..b1930157b6e --- /dev/null +++ b/pkg/registry/apis/dashboard/legacy/testdata/sqlite--query_dashboards-history_with_max_rows_last_id.sql @@ -0,0 +1,35 @@ +SELECT + dashboard.org_id, + dashboard.id, + dashboard.uid, + dashboard.title, + dashboard.folder_uid, + dashboard.deleted, + plugin_id, + provisioning.name as repo_name, + provisioning.external_id as repo_path, + provisioning.check_sum as repo_hash, + provisioning.updated as repo_ts, + dashboard.created, + created_user.uid as created_by, + dashboard.created_by as created_by_id, + dashboard_version.created as updated, + updated_user.uid as updated_by, + dashboard_version.created_by as updated_by_id, + dashboard_version.version, + dashboard_version.message, + dashboard_version.data, + dashboard_version.api_version +FROM "grafana"."dashboard" as dashboard +LEFT OUTER JOIN "grafana"."dashboard_version" as dashboard_version ON dashboard.id = dashboard_version.dashboard_id +LEFT OUTER JOIN "grafana"."dashboard_provisioning" as provisioning ON dashboard.id = provisioning.dashboard_id +LEFT OUTER JOIN "grafana"."user" as created_user ON dashboard.created_by = created_user.id +LEFT OUTER JOIN "grafana"."user" as updated_user ON dashboard_version.created_by = updated_user.id +WHERE dashboard.is_folder = FALSE + AND dashboard.org_id = 2 + AND dashboard_version.version < 500 + ORDER BY + dashboard_version.created DESC, + dashboard_version.version DESC, + dashboard.uid ASC + LIMIT 100 diff --git a/pkg/registry/apis/dashboard/legacy/types.go b/pkg/registry/apis/dashboard/legacy/types.go index 26cd043e8e5..968b2eb123c 100644 --- a/pkg/registry/apis/dashboard/legacy/types.go +++ b/pkg/registry/apis/dashboard/legacy/types.go @@ -16,6 +16,11 @@ type DashboardQuery struct { UID string // to select a single dashboard Limit int + // MaxRows is used internally by the iterator to fetch data in batches + // When set, the SQL query will include LIMIT MaxRows + // If Limit is smaller, that will be used instead + MaxRows int + // Included in the continue token // This is the ID from the last dashboard sent in the previous page LastID int64 diff --git a/pkg/registry/apis/dashboard/mutation_test.go b/pkg/registry/apis/dashboard/mutation_test.go index b95ae2519b5..78c49b28e8a 100644 --- a/pkg/registry/apis/dashboard/mutation_test.go +++ b/pkg/registry/apis/dashboard/mutation_test.go @@ -22,7 +22,7 @@ import ( ) func TestDashboardAPIBuilder_Mutate(t *testing.T) { - migration.Initialize(testutil.NewDataSourceProvider(testutil.StandardTestConfig), testutil.NewLibraryElementProvider()) + migration.Initialize(testutil.NewDataSourceProvider(testutil.StandardTestConfig), testutil.NewLibraryElementProvider(), migration.DefaultCacheTTL) tests := []struct { name string inputObj runtime.Object diff --git a/pkg/registry/apis/dashboard/register.go b/pkg/registry/apis/dashboard/register.go index e9925f0a3b7..e651a5716ac 100644 --- a/pkg/registry/apis/dashboard/register.go +++ b/pkg/registry/apis/dashboard/register.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "strconv" "strings" "github.com/prometheus/client_golang/prometheus" @@ -55,6 +56,7 @@ import ( "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/libraryelements" "github.com/grafana/grafana/pkg/services/librarypanels" + "github.com/grafana/grafana/pkg/services/live" "github.com/grafana/grafana/pkg/services/provisioning" "github.com/grafana/grafana/pkg/services/publicdashboards" "github.com/grafana/grafana/pkg/services/quota" @@ -121,6 +123,7 @@ type DashboardsAPIBuilder struct { snapshotService dashboardsnapshots.Service snapshotOptions dashv0.SnapshotSharingOptions namespacer request.NamespaceMapper + dashboardActivityChannel live.DashboardActivityChannel isStandalone bool // skips any handling including anything to do with legacy storage } @@ -150,6 +153,7 @@ func RegisterAPIService( libraryPanels libraryelements.Service, publicDashboardService publicdashboards.Service, snapshotService dashboardsnapshots.Service, + dashboardActivityChannel live.DashboardActivityChannel, ) *DashboardsAPIBuilder { dbp := legacysql.NewDatabaseProvider(sql) namespacer := request.GetNamespaceMapper(cfg) @@ -184,6 +188,7 @@ func RegisterAPIService( snapshotService: snapshotService, snapshotOptions: snapshotOptions, namespacer: namespacer, + dashboardActivityChannel: dashboardActivityChannel, legacy: &DashboardStorage{ Access: legacy.NewDashboardSQLAccess(dbp, namespacer, dashStore, provisioning, libraryPanelSvc, sorter, dashboardPermissionsSvc, accessControl, features), DashboardService: dashboardService, @@ -195,13 +200,30 @@ func RegisterAPIService( datasourceService: datasourceService, }, &libraryElementIndexProvider{ libraryElementService: libraryPanels, - }) + }, cfg.DashboardSchemaMigrationCacheTTL) + + // For single-tenant deployments (indicated by StackID), preload the cache in the background + if cfg.StackID != "" { + // Single namespace for cloud stack + stackID, err := strconv.ParseInt(cfg.StackID, 10, 64) + if err == nil { + var nsInfo authlib.NamespaceInfo + nsInfo, err = authlib.ParseNamespace(authlib.CloudNamespaceFormatter(stackID)) + if err == nil { + migration.PreloadCacheInBackground([]authlib.NamespaceInfo{nsInfo}) + } + } + if err != nil { + logging.DefaultLogger.Error("failed to parse namespace for cache preloading", "stackId", cfg.StackID, "err", err) + } + } + apiregistration.RegisterAPI(builder) return builder } -func NewAPIService(ac authlib.AccessClient, features featuremgmt.FeatureToggles, folderClientProvider client.K8sHandlerProvider, datasourceProvider schemaversion.DataSourceIndexProvider, libraryElementProvider schemaversion.LibraryElementIndexProvider, resourcePermissionsSvc *dynamic.NamespaceableResourceInterface) *DashboardsAPIBuilder { - migration.Initialize(datasourceProvider, libraryElementProvider) +func NewAPIService(ac authlib.AccessClient, features featuremgmt.FeatureToggles, folderClientProvider client.K8sHandlerProvider, datasourceProvider schemaversion.DataSourceIndexProvider, libraryElementProvider schemaversion.LibraryElementIndexProvider, resourcePermissionsSvc *dynamic.NamespaceableResourceInterface, search *SearchHandler) *DashboardsAPIBuilder { + migration.Initialize(datasourceProvider, libraryElementProvider, migration.DefaultCacheTTL) return &DashboardsAPIBuilder{ minRefreshInterval: "10s", accessClient: ac, @@ -209,6 +231,7 @@ func NewAPIService(ac authlib.AccessClient, features featuremgmt.FeatureToggles, dashboardService: &dashsvc.DashboardServiceImpl{}, // for validation helpers only folderClientProvider: folderClientProvider, resourcePermissionsSvc: resourcePermissionsSvc, + search: search, isStandalone: true, } } @@ -678,9 +701,10 @@ func (b *DashboardsAPIBuilder) storageForVersion( if err != nil { return err } - storage[dashboards.StoragePath()] = dashboardStoragePermissionWrapper{ - dashboardPermissionsSvc: b.dashboardPermissionsSvc, + storage[dashboards.StoragePath()] = dashboardStorageWrapper{ Storage: dw, + dashboardPermissionsSvc: b.dashboardPermissionsSvc, + live: b.dashboardActivityChannel, } // Register the DTO endpoint that will consolidate all dashboard bits @@ -757,11 +781,6 @@ func (b *DashboardsAPIBuilder) afterDelete(obj runtime.Object, _ *metav1.DeleteO } var defaultDashboardPermissions = []map[string]any{ - { - "kind": "BasicRole", - "name": "Admin", - "verb": "admin", - }, { "kind": "BasicRole", "name": "Editor", diff --git a/pkg/registry/apis/datasource/legacy_store.go b/pkg/registry/apis/datasource/legacy_store.go index aea7ed1daa3..e0526dd2409 100644 --- a/pkg/registry/apis/datasource/legacy_store.go +++ b/pkg/registry/apis/datasource/legacy_store.go @@ -61,20 +61,24 @@ func (s *legacyStorage) List(ctx context.Context, options *internalversion.ListO } func (s *legacyStorage) Get(ctx context.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { - start := time.Now() - defer func() { - metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Get"), time.Since(start).Seconds()) - }() + if s.dsConfigHandlerRequestsDuration != nil { + start := time.Now() + defer func() { + metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Get"), time.Since(start).Seconds()) + }() + } return s.datasources.GetDataSource(ctx, name) } // Create implements rest.Creater. func (s *legacyStorage) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { - start := time.Now() - defer func() { - metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) - }() + if s.dsConfigHandlerRequestsDuration != nil { + start := time.Now() + defer func() { + metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) + }() + } ds, ok := obj.(*v0alpha1.DataSource) if !ok { @@ -85,10 +89,12 @@ func (s *legacyStorage) Create(ctx context.Context, obj runtime.Object, createVa // Update implements rest.Updater. func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *metav1.UpdateOptions) (runtime.Object, bool, error) { - start := time.Now() - defer func() { - metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) - }() + if s.dsConfigHandlerRequestsDuration != nil { + start := time.Now() + defer func() { + metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) + }() + } old, err := s.Get(ctx, name, &metav1.GetOptions{}) if err != nil { @@ -126,10 +132,12 @@ func (s *legacyStorage) Update(ctx context.Context, name string, objInfo rest.Up // Delete implements rest.GracefulDeleter. func (s *legacyStorage) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions) (runtime.Object, bool, error) { - start := time.Now() - defer func() { - metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) - }() + if s.dsConfigHandlerRequestsDuration != nil { + start := time.Now() + defer func() { + metricutil.ObserveWithExemplar(ctx, s.dsConfigHandlerRequestsDuration.WithLabelValues("new", "Create"), time.Since(start).Seconds()) + }() + } err := s.datasources.DeleteDataSource(ctx, name) return nil, false, err diff --git a/pkg/registry/apis/datasource/register.go b/pkg/registry/apis/datasource/register.go index 92cf07053c7..4b6f27da5c0 100644 --- a/pkg/registry/apis/datasource/register.go +++ b/pkg/registry/apis/datasource/register.go @@ -3,6 +3,7 @@ package datasource import ( "context" "encoding/json" + "errors" "fmt" "maps" @@ -38,14 +39,14 @@ var ( // DataSourceAPIBuilder is used just so wire has something unique to return type DataSourceAPIBuilder struct { datasourceResourceInfo utils.ResourceInfo - - pluginJSON plugins.JSONData - client PluginClient // will only ever be called with the same plugin id! - datasources PluginDatasourceProvider - contextProvider PluginContextWrapper - accessControl accesscontrol.AccessControl - queryTypes *queryV0.QueryTypeDefinitionList - configCrudUseNewApis bool + pluginJSON plugins.JSONData + client PluginClient // will only ever be called with the same plugin id! + datasources PluginDatasourceProvider + contextProvider PluginContextWrapper + accessControl accesscontrol.AccessControl + queryTypes *queryV0.QueryTypeDefinitionList + configCrudUseNewApis bool + dataSourceCRUDMetric *prometheus.HistogramVec } func RegisterAPIService( @@ -66,6 +67,16 @@ func RegisterAPIService( var err error var builder *DataSourceAPIBuilder + dataSourceCRUDMetric := metricutil.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: "grafana", + Name: "ds_config_handler_requests_duration_seconds", + Help: "Duration of requests handled by datasource configuration handlers", + }, []string{"code_path", "handler"}) + regErr := reg.Register(dataSourceCRUDMetric) + if regErr != nil && !errors.As(regErr, &prometheus.AlreadyRegisteredError{}) { + return nil, regErr + } + pluginJSONs, err := getDatasourcePlugins(pluginSources) if err != nil { return nil, fmt.Errorf("error getting list of datasource plugins: %s", err) @@ -91,6 +102,7 @@ func RegisterAPIService( if err != nil { return nil, err } + builder.SetDataSourceCRUDMetrics(dataSourceCRUDMetric) apiRegistrar.RegisterAPI(builder) } @@ -161,6 +173,10 @@ func (b *DataSourceAPIBuilder) GetGroupVersion() schema.GroupVersion { return b.datasourceResourceInfo.GroupVersion() } +func (b *DataSourceAPIBuilder) SetDataSourceCRUDMetrics(datasourceCRUDMetric *prometheus.HistogramVec) { + b.dataSourceCRUDMetric = datasourceCRUDMetric +} + func addKnownTypes(scheme *runtime.Scheme, gv schema.GroupVersion) { scheme.AddKnownTypes(gv, &datasourceV0.DataSource{}, @@ -218,13 +234,9 @@ func (b *DataSourceAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver if b.configCrudUseNewApis { legacyStore := &legacyStorage{ - datasources: b.datasources, - resourceInfo: &ds, - dsConfigHandlerRequestsDuration: metricutil.NewHistogramVec(prometheus.HistogramOpts{ - Namespace: "grafana", - Name: "ds_config_handler_requests_duration_seconds", - Help: "Duration of requests handled by datasource configuration handlers", - }, []string{"code_path", "handler"}), + datasources: b.datasources, + resourceInfo: &ds, + dsConfigHandlerRequestsDuration: b.dataSourceCRUDMetric, } unified, err := grafanaregistry.NewRegistryStore(opts.Scheme, ds, opts.OptsGetter) if err != nil { diff --git a/pkg/registry/apis/folders/register.go b/pkg/registry/apis/folders/register.go index 72a4abf8e0a..64e51c06312 100644 --- a/pkg/registry/apis/folders/register.go +++ b/pkg/registry/apis/folders/register.go @@ -203,11 +203,6 @@ func (b *FolderAPIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.API } var defaultPermissions = []map[string]any{ - { - "kind": "BasicRole", - "name": "Admin", - "verb": "admin", - }, { "kind": "BasicRole", "name": "Editor", diff --git a/pkg/registry/apis/folders/validate.go b/pkg/registry/apis/folders/validate.go index 4f8ccd2250d..eb0c29b30a1 100644 --- a/pkg/registry/apis/folders/validate.go +++ b/pkg/registry/apis/folders/validate.go @@ -53,6 +53,7 @@ func validateOnCreate(ctx context.Context, f *folders.Folder, getter parentsGett return folder.ErrFolderCannotBeParentOfItself } + // note: `parents` will include itself as the last item parents, err := getter(ctx, f) if err != nil { return fmt.Errorf("unable to create folder inside parent: %w", err) diff --git a/pkg/registry/apis/folders/validate_test.go b/pkg/registry/apis/folders/validate_test.go index c4bf07bc71c..7fdb3cfae12 100644 --- a/pkg/registry/apis/folders/validate_test.go +++ b/pkg/registry/apis/folders/validate_test.go @@ -20,8 +20,7 @@ func TestValidateCreate(t *testing.T) { tests := []struct { name string folder *folders.Folder - getter *folders.FolderInfoList - getterError error + mockFolders map[string]*folders.Folder expectedErr string maxDepth int // defaults to 5 unless set }{ @@ -36,10 +35,23 @@ func TestValidateCreate(t *testing.T) { Title: "some title", }, }, - getter: &folders.FolderInfoList{ - Items: []folders.FolderInfo{ - {Name: "p2", Parent: "p3"}, - {Name: "p3"}, + mockFolders: map[string]*folders.Folder{ + "p2": { + ObjectMeta: metav1.ObjectMeta{ + Name: "p2", + Annotations: map[string]string{"grafana.app/folder": "p3"}, + }, + Spec: folders.FolderSpec{ + Title: "p2 title", + }, + }, + "p3": { + ObjectMeta: metav1.ObjectMeta{ + Name: "p3", + }, + Spec: folders.FolderSpec{ + Title: "p3 title", + }, }, }, }, @@ -94,12 +106,41 @@ func TestValidateCreate(t *testing.T) { Title: "some title", }, }, - getter: &folders.FolderInfoList{ - Items: []folders.FolderInfo{ - {Name: "p2", Parent: "p3"}, - {Name: "p3", Parent: "p4"}, - {Name: "p4", Parent: folder.GeneralFolderUID}, - {Name: folder.GeneralFolderUID}, + mockFolders: map[string]*folders.Folder{ + "p2": { + ObjectMeta: metav1.ObjectMeta{ + Name: "p2", + Annotations: map[string]string{"grafana.app/folder": "p3"}, + }, + Spec: folders.FolderSpec{ + Title: "p2 title", + }, + }, + "p3": { + ObjectMeta: metav1.ObjectMeta{ + Name: "p3", + Annotations: map[string]string{"grafana.app/folder": "p4"}, + }, + Spec: folders.FolderSpec{ + Title: "p3 title", + }, + }, + "p4": { + ObjectMeta: metav1.ObjectMeta{ + Name: "p4", + Annotations: map[string]string{"grafana.app/folder": folder.GeneralFolderUID}, + }, + Spec: folders.FolderSpec{ + Title: "p4 title", + }, + }, + folder.GeneralFolderUID: { + ObjectMeta: metav1.ObjectMeta{ + Name: folder.GeneralFolderUID, + }, + Spec: folders.FolderSpec{ + Title: "General", + }, }, }, maxDepth: 2, @@ -116,17 +157,95 @@ func TestValidateCreate(t *testing.T) { Title: "some title", }, }, - getter: &folders.FolderInfoList{ - Items: []folders.FolderInfo{ - {Name: "4", Parent: "3"}, - {Name: "3", Parent: "2"}, - {Name: "2", Parent: "1"}, - {Name: "1", Parent: folder.GeneralFolderUID}, - {Name: folder.GeneralFolderUID}, + mockFolders: map[string]*folders.Folder{ + "4": { + ObjectMeta: metav1.ObjectMeta{ + Name: "4", + Annotations: map[string]string{"grafana.app/folder": "3"}, + }, + Spec: folders.FolderSpec{ + Title: "4 title", + }, + }, + "3": { + ObjectMeta: metav1.ObjectMeta{ + Name: "3", + Annotations: map[string]string{"grafana.app/folder": "2"}, + }, + Spec: folders.FolderSpec{ + Title: "3 title", + }, + }, + "2": { + ObjectMeta: metav1.ObjectMeta{ + Name: "2", + Annotations: map[string]string{"grafana.app/folder": "1"}, + }, + Spec: folders.FolderSpec{ + Title: "2 title", + }, + }, + "1": { + ObjectMeta: metav1.ObjectMeta{ + Name: "1", + }, + Spec: folders.FolderSpec{ + Title: "1 title", + }, }, }, maxDepth: folder.MaxNestedFolderDepth, }, + { + name: "cannot create a circular reference", + folder: &folders.Folder{ + ObjectMeta: metav1.ObjectMeta{ + Name: "3", + Annotations: map[string]string{"grafana.app/folder": "2"}, + }, + Spec: folders.FolderSpec{ + Title: "some title", + }, + }, + expectedErr: "cyclic folder references found", + mockFolders: map[string]*folders.Folder{ + "2": { + ObjectMeta: metav1.ObjectMeta{ + Name: "2", + Annotations: map[string]string{"grafana.app/folder": "1"}, + }, + Spec: folders.FolderSpec{ + Title: "2 title", + }, + }, + "1": { + ObjectMeta: metav1.ObjectMeta{ + Name: "1", + Annotations: map[string]string{"grafana.app/folder": "3"}, + }, + Spec: folders.FolderSpec{ + Title: "1 title", + }, + }, + "3": { + ObjectMeta: metav1.ObjectMeta{ + Name: "3", + Annotations: map[string]string{"grafana.app/folder": folder.GeneralFolderUID}, + }, + Spec: folders.FolderSpec{ + Title: "3 title", + }, + }, + folder.GeneralFolderUID: { + ObjectMeta: metav1.ObjectMeta{ + Name: folder.GeneralFolderUID, + }, + Spec: folders.FolderSpec{ + Title: "General", + }, + }, + }, + }, } for _, tt := range tests { @@ -135,10 +254,16 @@ func TestValidateCreate(t *testing.T) { if maxDepth == 0 { maxDepth = 5 } - err := validateOnCreate(context.Background(), tt.folder, - func(ctx context.Context, folder *folders.Folder) (*folders.FolderInfoList, error) { - return tt.getter, tt.getterError - }, maxDepth) + + mockStorage := grafanarest.NewMockStorage(t) + for name, f := range tt.mockFolders { + f.Name = name + mockStorage.On("Get", context.Background(), name, &metav1.GetOptions{}).Return(f, nil).Maybe() + } + + getter := newParentsGetter(mockStorage, maxDepth) + + err := validateOnCreate(context.Background(), tt.folder, getter, maxDepth) if tt.expectedErr == "" { require.NoError(t, err) diff --git a/pkg/registry/apis/iam/authorizer.go b/pkg/registry/apis/iam/authorizer.go index a3997638e1e..026254ebab6 100644 --- a/pkg/registry/apis/iam/authorizer.go +++ b/pkg/registry/apis/iam/authorizer.go @@ -22,6 +22,7 @@ type iamAuthorizer struct { func newIAMAuthorizer(accessClient authlib.AccessClient, legacyAccessClient authlib.AccessClient) authorizer.Authorizer { resourceAuthorizer := make(map[string]authorizer.Authorizer) + serviceAuthorizer := gfauthorizer.NewServiceAuthorizer() // Authorizer that allows any authenticated user // To be used when authorization is handled at the storage layer allowAuthorizer := authorizer.AuthorizerFunc(func( @@ -50,8 +51,7 @@ func newIAMAuthorizer(accessClient authlib.AccessClient, legacyAccessClient auth resourceAuthorizer[iamv0.UserResourceInfo.GetName()] = authorizer resourceAuthorizer[iamv0.ExternalGroupMappingResourceInfo.GetName()] = authorizer resourceAuthorizer[iamv0.TeamResourceInfo.GetName()] = authorizer - - serviceAuthorizer := gfauthorizer.NewServiceAuthorizer() + resourceAuthorizer["searchUsers"] = serviceAuthorizer resourceAuthorizer["searchTeams"] = serviceAuthorizer return &iamAuthorizer{resourceAuthorizer: resourceAuthorizer} diff --git a/pkg/registry/apis/iam/authorizer/parent_provider.go b/pkg/registry/apis/iam/authorizer/parent_provider.go new file mode 100644 index 00000000000..4b7555d85ba --- /dev/null +++ b/pkg/registry/apis/iam/authorizer/parent_provider.go @@ -0,0 +1,164 @@ +package authorizer + +import ( + "context" + "errors" + "fmt" + "net/http" + "sync" + + "github.com/grafana/authlib/authn" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + + dashboardv1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v1beta1" + folderv1 "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" + "github.com/grafana/grafana/apps/provisioning/pkg/auth" + "github.com/grafana/grafana/pkg/apimachinery/utils" +) + +var ( + ErrNoConfigProvider = errors.New("no config provider for group resource") + ErrNoVersionInfo = errors.New("no version info for group resource") + + Versions = map[schema.GroupResource]string{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: folderv1.VERSION, + {Group: dashboardv1.GROUP, Resource: dashboardv1.DASHBOARD_RESOURCE}: dashboardv1.VERSION, + } +) + +// ConfigProvider is a function that provides a rest.Config for a given context. +type ConfigProvider func(ctx context.Context) (*rest.Config, error) + +// DynamicClientFactory is a function that creates a dynamic.Interface from a rest.Config. +// This can be overridden in tests. +type DynamicClientFactory func(config *rest.Config) (dynamic.Interface, error) + +// ParentProvider implementation that fetches the parent folder information from remote API servers. +type ParentProviderImpl struct { + configProviders map[schema.GroupResource]ConfigProvider + versions map[schema.GroupResource]string + dynamicClientFactory DynamicClientFactory + + // Cache of dynamic clients for each group resource + // This is used to avoid creating a new dynamic client for each request + // and to reuse the same client for the same group resource. + clients map[schema.GroupResource]dynamic.Interface + clientsMu sync.Mutex +} + +// DialConfig holds the configuration for dialing a remote API server. +type DialConfig struct { + Host string + Insecure bool + CAFile string + Audience string +} + +// NewLocalConfigProvider creates a map of ConfigProviders that return the same given config for local API servers. +func NewLocalConfigProvider( + configProvider ConfigProvider, +) map[schema.GroupResource]ConfigProvider { + return map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: configProvider, + {Group: dashboardv1.GROUP, Resource: dashboardv1.DASHBOARD_RESOURCE}: configProvider, + } +} + +// NewRemoteConfigProvider creates a map of ConfigProviders for remote API servers based on the given DialConfig. +func NewRemoteConfigProvider(cfg map[schema.GroupResource]DialConfig, exchangeClient authn.TokenExchanger) map[schema.GroupResource]ConfigProvider { + configProviders := make(map[schema.GroupResource]ConfigProvider, len(cfg)) + for gr, dialConfig := range cfg { + configProviders[gr] = func(ctx context.Context) (*rest.Config, error) { + return &rest.Config{ + Host: dialConfig.Host, + WrapTransport: func(rt http.RoundTripper) http.RoundTripper { + return auth.NewRoundTripper(exchangeClient, rt, dialConfig.Audience) + }, + TLSClientConfig: rest.TLSClientConfig{ + Insecure: dialConfig.Insecure, + CAFile: dialConfig.CAFile, + }, + QPS: 50, + Burst: 100, + }, nil + } + } + return configProviders +} + +// NewApiParentProvider creates a new ParentProviderImpl with the given config providers and version info. +func NewApiParentProvider( + configProviders map[schema.GroupResource]ConfigProvider, + version map[schema.GroupResource]string, +) *ParentProviderImpl { + return &ParentProviderImpl{ + configProviders: configProviders, + versions: version, + dynamicClientFactory: func(config *rest.Config) (dynamic.Interface, error) { + return dynamic.NewForConfig(config) + }, + clients: make(map[schema.GroupResource]dynamic.Interface), + } +} + +func (p *ParentProviderImpl) HasParent(gr schema.GroupResource) bool { + _, ok := p.configProviders[gr] + return ok +} + +func (p *ParentProviderImpl) getClient(ctx context.Context, gr schema.GroupResource) (dynamic.Interface, error) { + p.clientsMu.Lock() + client, ok := p.clients[gr] + p.clientsMu.Unlock() + + if ok { + return client, nil + } + + provider, ok := p.configProviders[gr] + if !ok { + return nil, fmt.Errorf("%w: %s", ErrNoConfigProvider, gr.String()) + } + restConfig, err := provider(ctx) + if err != nil { + return nil, err + } + + client, err = p.dynamicClientFactory(restConfig) + if err != nil { + return nil, err + } + + p.clientsMu.Lock() + p.clients[gr] = client + p.clientsMu.Unlock() + + return client, nil +} + +func (p *ParentProviderImpl) GetParent(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) { + client, err := p.getClient(ctx, gr) + if err != nil { + return "", err + } + + version, ok := p.versions[gr] + if !ok { + return "", fmt.Errorf("%w: %s", ErrNoVersionInfo, gr.String()) + } + resourceClient := client.Resource(schema.GroupVersionResource{ + Group: gr.Group, + Resource: gr.Resource, + Version: version, + }).Namespace(namespace) + + unstructObj, err := resourceClient.Get(ctx, name, metav1.GetOptions{}) + if err != nil { + return "", err + } + + return unstructObj.GetAnnotations()[utils.AnnoKeyFolder], nil +} diff --git a/pkg/registry/apis/iam/authorizer/parent_provider_test.go b/pkg/registry/apis/iam/authorizer/parent_provider_test.go new file mode 100644 index 00000000000..45405d81161 --- /dev/null +++ b/pkg/registry/apis/iam/authorizer/parent_provider_test.go @@ -0,0 +1,198 @@ +package authorizer + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + + folderv1 "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" + "github.com/grafana/grafana/pkg/apimachinery/utils" +) + +var configProvider = func(ctx context.Context) (*rest.Config, error) { + return &rest.Config{}, nil +} + +func TestParentProviderImpl_GetParent(t *testing.T) { + tests := []struct { + name string + gr schema.GroupResource + namespace string + resourceName string + parentFolder string + setupFake func(*fakeDynamicClient, *fakeResourceInterface) + configProviders map[schema.GroupResource]ConfigProvider + versions map[schema.GroupResource]string + expectedError string + expectedParent string + }{ + { + name: "successfully get parent folder", + gr: schema.GroupResource{Group: folderv1.GROUP, Resource: folderv1.RESOURCE}, + namespace: "org-1", + resourceName: "dash1", + parentFolder: "fold1", + setupFake: func(fakeClient *fakeDynamicClient, fakeResource *fakeResourceInterface) { + fakeClient.resourceInterface = fakeResource + fakeResource.getFunc = func(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) { + obj := &unstructured.Unstructured{} + obj.SetAnnotations(map[string]string{utils.AnnoKeyFolder: "fold1"}) + return obj, nil + } + }, + configProviders: map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: configProvider, + }, + versions: Versions, + expectedParent: "fold1", + }, + { + name: "resource without parent annotation returns empty", + gr: schema.GroupResource{Group: folderv1.GROUP, Resource: folderv1.RESOURCE}, + namespace: "org-1", + resourceName: "dash1", + setupFake: func(fakeClient *fakeDynamicClient, fakeResource *fakeResourceInterface) { + fakeClient.resourceInterface = fakeResource + fakeResource.getFunc = func(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) { + obj := &unstructured.Unstructured{} + obj.SetAnnotations(map[string]string{}) + return obj, nil + } + }, + configProviders: map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: configProvider, + }, + versions: Versions, + expectedParent: "", + }, + { + name: "no config provider returns error", + gr: schema.GroupResource{Group: "unknown.group", Resource: "unknown"}, + namespace: "org-1", + resourceName: "resource-1", + configProviders: map[schema.GroupResource]ConfigProvider{}, + versions: Versions, + expectedError: ErrNoConfigProvider.Error(), + }, + { + name: "config provider returns error", + gr: schema.GroupResource{Group: folderv1.GROUP, Resource: folderv1.RESOURCE}, + namespace: "org-1", + resourceName: "resource-1", + configProviders: map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: func(ctx context.Context) (*rest.Config, error) { + return nil, errors.New("config provider error") + }, + }, + versions: Versions, + expectedError: "config provider error", + }, + { + name: "no version info returns error", + gr: schema.GroupResource{Group: folderv1.GROUP, Resource: folderv1.RESOURCE}, + namespace: "org-1", + resourceName: "resource-1", + configProviders: map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: func(ctx context.Context) (*rest.Config, error) { + return &rest.Config{}, nil + }, + }, + versions: map[schema.GroupResource]string{}, + expectedError: ErrNoVersionInfo.Error(), + }, + { + name: "resource get returns error", + gr: schema.GroupResource{Group: folderv1.GROUP, Resource: folderv1.RESOURCE}, + namespace: "org-1", + resourceName: "resource-1", + setupFake: func(fakeClient *fakeDynamicClient, fakeResource *fakeResourceInterface) { + fakeClient.resourceInterface = fakeResource + fakeResource.getFunc = func(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) { + return nil, errors.New("resource not found") + } + }, + configProviders: map[schema.GroupResource]ConfigProvider{ + {Group: folderv1.GROUP, Resource: folderv1.RESOURCE}: func(ctx context.Context) (*rest.Config, error) { + return &rest.Config{}, nil + }, + }, + versions: Versions, + expectedError: "resource not found", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fakeClient := &fakeDynamicClient{} + fakeResource := &fakeResourceInterface{} + if tt.setupFake != nil { + tt.setupFake(fakeClient, fakeResource) + } + + provider := &ParentProviderImpl{ + configProviders: tt.configProviders, + versions: tt.versions, + dynamicClientFactory: func(config *rest.Config) (dynamic.Interface, error) { + return fakeClient, nil + }, + clients: make(map[schema.GroupResource]dynamic.Interface), + } + + parent, err := provider.GetParent(context.Background(), tt.gr, tt.namespace, tt.resourceName) + + if tt.expectedError != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.expectedError) + assert.Empty(t, parent) + } else { + require.NoError(t, err) + assert.Equal(t, tt.expectedParent, parent) + } + }) + } +} + +// fakeDynamicClient is a fake implementation of dynamic.Interface +type fakeDynamicClient struct { + resourceInterface dynamic.ResourceInterface +} + +func (f *fakeDynamicClient) Resource(resource schema.GroupVersionResource) dynamic.NamespaceableResourceInterface { + return &fakeNamespaceableResourceInterface{ + resourceInterface: f.resourceInterface, + } +} + +// fakeNamespaceableResourceInterface is a fake implementation of dynamic.NamespaceableResourceInterface +type fakeNamespaceableResourceInterface struct { + dynamic.NamespaceableResourceInterface + resourceInterface dynamic.ResourceInterface +} + +func (f *fakeNamespaceableResourceInterface) Namespace(namespace string) dynamic.ResourceInterface { + if f.resourceInterface != nil { + return f.resourceInterface + } + return &fakeResourceInterface{} +} + +// fakeResourceInterface is a fake implementation of dynamic.ResourceInterface +type fakeResourceInterface struct { + dynamic.ResourceInterface + getFunc func(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) +} + +func (f *fakeResourceInterface) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) { + if f.getFunc != nil { + return f.getFunc(ctx, name, opts, subresources...) + } + return &unstructured.Unstructured{}, nil +} diff --git a/pkg/registry/apis/iam/authorizer/resource_permissions.go b/pkg/registry/apis/iam/authorizer/resource_permissions.go index d857c50bc84..0fbf413adac 100644 --- a/pkg/registry/apis/iam/authorizer/resource_permissions.go +++ b/pkg/registry/apis/iam/authorizer/resource_permissions.go @@ -10,24 +10,44 @@ import ( iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer/storewrapper" ) // TODO: Logs, Metrics, Traces? +// ParentProvider interface for fetching parent information of resources +type ParentProvider interface { + // HasParent checks if the given GroupResource has a parent folder + HasParent(gr schema.GroupResource) bool + // GetParent fetches the parent folder name for the given resource + GetParent(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) +} + // ResourcePermissionsAuthorizer type ResourcePermissionsAuthorizer struct { - accessClient types.AccessClient + accessClient types.AccessClient + parentProvider ParentProvider + logger log.Logger } var _ storewrapper.ResourceStorageAuthorizer = (*ResourcePermissionsAuthorizer)(nil) -func NewResourcePermissionsAuthorizer(accessClient types.AccessClient) *ResourcePermissionsAuthorizer { +func NewResourcePermissionsAuthorizer( + accessClient types.AccessClient, + parentProvider ParentProvider, +) *ResourcePermissionsAuthorizer { return &ResourcePermissionsAuthorizer{ - accessClient: accessClient, + accessClient: accessClient, + parentProvider: parentProvider, + logger: log.New("iam.authorizer.resource-permissions"), } } +func isAccessPolicy(authInfo types.AuthInfo) bool { + return types.IsIdentityType(authInfo.GetIdentityType(), types.TypeAccessPolicy) +} + // AfterGet implements ResourceStorageAuthorizer. func (r *ResourcePermissionsAuthorizer) AfterGet(ctx context.Context, obj runtime.Object) error { authInfo, ok := types.AuthInfoFrom(ctx) @@ -37,9 +57,24 @@ func (r *ResourcePermissionsAuthorizer) AfterGet(ctx context.Context, obj runtim switch o := obj.(type) { case *iamv0.ResourcePermission: target := o.Spec.Resource + targetGR := schema.GroupResource{Group: target.ApiGroup, Resource: target.Resource} - // TODO: Fetch the resource to retrieve its parent folder. parent := "" + // Fetch the parent of the resource + // Access Policies have global scope, so no parent check needed + if !isAccessPolicy(authInfo) && r.parentProvider.HasParent(targetGR) { + p, err := r.parentProvider.GetParent(ctx, targetGR, o.Namespace, target.Name) + if err != nil { + r.logger.Error("after get: error fetching parent", "error", err.Error(), + "namespace", o.Namespace, + "group", target.ApiGroup, + "resource", target.Resource, + "name", target.Name, + ) + return err + } + parent = p + } checkReq := types.CheckRequest{ Namespace: o.Namespace, @@ -72,9 +107,24 @@ func (r *ResourcePermissionsAuthorizer) beforeWrite(ctx context.Context, obj run switch o := obj.(type) { case *iamv0.ResourcePermission: target := o.Spec.Resource + targetGR := schema.GroupResource{Group: target.ApiGroup, Resource: target.Resource} - // TODO: Fetch the resource to retrieve its parent folder. parent := "" + // Fetch the parent of the resource + // Access Policies have global scope, so no parent check needed + if !isAccessPolicy(authInfo) && r.parentProvider.HasParent(targetGR) { + p, err := r.parentProvider.GetParent(ctx, targetGR, o.Namespace, target.Name) + if err != nil { + r.logger.Error("before write: error fetching parent", "error", err.Error(), + "namespace", o.Namespace, + "group", target.ApiGroup, + "resource", target.Resource, + "name", target.Name, + ) + return err + } + parent = p + } checkReq := types.CheckRequest{ Namespace: o.Namespace, @@ -153,8 +203,28 @@ func (r *ResourcePermissionsAuthorizer) FilterList(ctx context.Context, list run canViewFuncs[gr] = canView } - // TODO : Fetch the resource to retrieve its parent folder. + target := item.Spec.Resource + targetGR := schema.GroupResource{Group: target.ApiGroup, Resource: target.Resource} + parent := "" + // Fetch the parent of the resource + // It's not efficient to do for every item in the list, but it's a good starting point. + // Access Policies have global scope, so no parent check needed + if !isAccessPolicy(authInfo) && r.parentProvider.HasParent(targetGR) { + p, err := r.parentProvider.GetParent(ctx, targetGR, item.Namespace, target.Name) + if err != nil { + // Skip item on error fetching parent + r.logger.Warn("filter list: error fetching parent, skipping item", + "error", err.Error(), + "namespace", item.Namespace, + "group", target.ApiGroup, + "resource", target.Resource, + "name", target.Name, + ) + continue + } + parent = p + } allowed := canView(item.Spec.Resource.Name, parent) if allowed { diff --git a/pkg/registry/apis/iam/authorizer/resource_permissions_test.go b/pkg/registry/apis/iam/authorizer/resource_permissions_test.go index 9f1762e365f..df777ee31e9 100644 --- a/pkg/registry/apis/iam/authorizer/resource_permissions_test.go +++ b/pkg/registry/apis/iam/authorizer/resource_permissions_test.go @@ -5,13 +5,15 @@ import ( "testing" "github.com/go-jose/go-jose/v4/jwt" + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "github.com/grafana/authlib/authn" "github.com/grafana/authlib/types" iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/apimachinery/utils" - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var ( @@ -63,6 +65,7 @@ func TestResourcePermissions_AfterGet(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + parent := "fold-1" checkFunc := func(id types.AuthInfo, req *types.CheckRequest, folder string) (types.CheckResponse, error) { require.NotNil(t, id) // Check is called with the user's identity @@ -74,12 +77,18 @@ func TestResourcePermissions_AfterGet(t *testing.T) { require.Equal(t, fold1.Spec.Resource.Resource, req.Resource) require.Equal(t, fold1.Spec.Resource.Name, req.Name) require.Equal(t, utils.VerbGetPermissions, req.Verb) + require.Equal(t, parent, folder) return types.CheckResponse{Allowed: tt.shouldAllow}, nil } + getParentFunc := func(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) { + // For this test, we can return a fixed parent folder ID + return parent, nil + } accessClient := &fakeAccessClient{checkFunc: checkFunc} - resPermAuthz := NewResourcePermissionsAuthorizer(accessClient) + fakeParentProvider := &fakeParentProvider{hasParent: true, getParentFunc: getParentFunc} + resPermAuthz := NewResourcePermissionsAuthorizer(accessClient, fakeParentProvider) ctx := types.WithAuthInfo(context.Background(), user) err := resPermAuthz.AfterGet(ctx, fold1) @@ -89,6 +98,7 @@ func TestResourcePermissions_AfterGet(t *testing.T) { require.Error(t, err, "expected error for denied access") } require.True(t, accessClient.checkCalled, "accessClient.Check should be called") + require.True(t, fakeParentProvider.getParentCalled, "parentProvider.GetParent should be called") }) } } @@ -121,23 +131,32 @@ func TestResourcePermissions_FilterList(t *testing.T) { require.Equal(t, "dashboards", req.Resource) } - // Return a checker that allows only specific resources: fold-1 and dash-2 + // Return a checker that allows access to fold-1 and its content return func(name, folder string) bool { - if name == "fold-1" || name == "dash-2" { + if name == "fold-1" || folder == "fold-1" { return true } return false }, &types.NoopZookie{}, nil } + getParentFunc := func(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) { + if name == "dash-2" { + return "fold-1", nil + } + return "", nil + } + accessClient := &fakeAccessClient{compileFunc: compileFunc} - resPermAuthz := NewResourcePermissionsAuthorizer(accessClient) + fakeParentProvider := &fakeParentProvider{hasParent: true, getParentFunc: getParentFunc} + resPermAuthz := NewResourcePermissionsAuthorizer(accessClient, fakeParentProvider) ctx := types.WithAuthInfo(context.Background(), user) obj, err := resPermAuthz.FilterList(ctx, list) require.NoError(t, err) require.NotNil(t, list) require.True(t, accessClient.compileCalled, "accessClient.Compile should be called") + require.True(t, fakeParentProvider.getParentCalled, "parentProvider.GetParent should be called") filtered, ok := obj.(*iamv0.ResourcePermissionList) require.True(t, ok, "response should be of type ResourcePermissionList") @@ -165,6 +184,7 @@ func TestResourcePermissions_beforeWrite(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + parent := "fold-1" checkFunc := func(id types.AuthInfo, req *types.CheckRequest, folder string) (types.CheckResponse, error) { require.NotNil(t, id) // Check is called with the user's identity @@ -176,12 +196,18 @@ func TestResourcePermissions_beforeWrite(t *testing.T) { require.Equal(t, fold1.Spec.Resource.Resource, req.Resource) require.Equal(t, fold1.Spec.Resource.Name, req.Name) require.Equal(t, utils.VerbSetPermissions, req.Verb) + require.Equal(t, parent, folder) return types.CheckResponse{Allowed: tt.shouldAllow}, nil } + getParentFunc := func(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) { + return parent, nil + } + accessClient := &fakeAccessClient{checkFunc: checkFunc} - resPermAuthz := NewResourcePermissionsAuthorizer(accessClient) + fakeParentProvider := &fakeParentProvider{hasParent: true, getParentFunc: getParentFunc} + resPermAuthz := NewResourcePermissionsAuthorizer(accessClient, fakeParentProvider) ctx := types.WithAuthInfo(context.Background(), user) err := resPermAuthz.beforeWrite(ctx, fold1) @@ -191,6 +217,7 @@ func TestResourcePermissions_beforeWrite(t *testing.T) { require.Error(t, err, "expected error for denied delete") } require.True(t, accessClient.checkCalled, "accessClient.Check should be called") + require.True(t, fakeParentProvider.getParentCalled, "parentProvider.GetParent should be called") }) } } @@ -214,3 +241,18 @@ func (m *fakeAccessClient) Compile(ctx context.Context, id types.AuthInfo, req t } var _ types.AccessClient = (*fakeAccessClient)(nil) + +type fakeParentProvider struct { + hasParent bool + getParentCalled bool + getParentFunc func(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) +} + +func (f *fakeParentProvider) HasParent(gr schema.GroupResource) bool { + return f.hasParent +} + +func (f *fakeParentProvider) GetParent(ctx context.Context, gr schema.GroupResource, namespace, name string) (string, error) { + f.getParentCalled = true + return f.getParentFunc(ctx, gr, namespace, name) +} diff --git a/pkg/registry/apis/iam/models.go b/pkg/registry/apis/iam/models.go index b851122ffd9..f8ae4219b65 100644 --- a/pkg/registry/apis/iam/models.go +++ b/pkg/registry/apis/iam/models.go @@ -7,6 +7,7 @@ import ( "github.com/grafana/authlib/types" "github.com/grafana/grafana/pkg/infra/log" + iamauthorizer "github.com/grafana/grafana/pkg/registry/apis/iam/authorizer" "github.com/grafana/grafana/pkg/registry/apis/iam/externalgroupmapping" "github.com/grafana/grafana/pkg/registry/apis/iam/legacy" "github.com/grafana/grafana/pkg/registry/apis/iam/serviceaccount" @@ -60,6 +61,10 @@ type IdentityAccessManagementAPIBuilder struct { roleBindingsStorage RoleBindingStorageBackend externalGroupMappingStorage ExternalGroupMappingStorageBackend + // Required for resource permissions authorization + // fetches resources parent folders + resourceParentProvider iamauthorizer.ParentProvider + // Access Control authorizer authorizer.Authorizer // legacyAccessClient is used for the identity apis, we need to migrate to the access client @@ -77,10 +82,11 @@ type IdentityAccessManagementAPIBuilder struct { reg prometheus.Registerer logger log.Logger - dual dualwrite.Service - unified resource.ResourceClient - userSearchClient resourcepb.ResourceIndexClient - teamSearch *TeamSearchHandler + dual dualwrite.Service + unified resource.ResourceClient + userSearchClient resourcepb.ResourceIndexClient + userSearchHandler *user.SearchHandler + teamSearch *TeamSearchHandler teamGroupsHandler externalgroupmapping.TeamGroupsHandler diff --git a/pkg/registry/apis/iam/register.go b/pkg/registry/apis/iam/register.go index 85d8bc4e4f1..a9a68e90d2c 100644 --- a/pkg/registry/apis/iam/register.go +++ b/pkg/registry/apis/iam/register.go @@ -21,6 +21,7 @@ import ( "k8s.io/kube-openapi/pkg/spec3" "k8s.io/kube-openapi/pkg/validation/spec" + "github.com/grafana/authlib/authn" "github.com/grafana/authlib/types" iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" @@ -41,11 +42,13 @@ import ( "github.com/grafana/grafana/pkg/registry/apis/iam/teambinding" "github.com/grafana/grafana/pkg/registry/apis/iam/user" "github.com/grafana/grafana/pkg/services/accesscontrol" + "github.com/grafana/grafana/pkg/services/apiserver" gfauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer/storewrapper" "github.com/grafana/grafana/pkg/services/apiserver/builder" "github.com/grafana/grafana/pkg/services/authz/zanzana" "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/ssosettings" teamservice "github.com/grafana/grafana/pkg/services/team" legacyuser "github.com/grafana/grafana/pkg/services/user" @@ -76,8 +79,10 @@ func RegisterAPIService( teamGroupsHandlerImpl externalgroupmapping.TeamGroupsHandler, dual dualwrite.Service, unified resource.ResourceClient, + orgService org.Service, userService legacyuser.Service, teamService teamservice.Service, + restConfig apiserver.RestConfigProvider, ) (*IdentityAccessManagementAPIBuilder, error) { dbProvider := legacysql.NewDatabaseProvider(sql) store := legacy.NewLegacySQLStores(dbProvider) @@ -88,6 +93,11 @@ func RegisterAPIService( //nolint:staticcheck // not yet migrated to OpenFeature enableAuthnMutation := features.IsEnabledGlobally(featuremgmt.FlagKubernetesAuthnMutation) + resourceParentProvider := iamauthorizer.NewApiParentProvider( + iamauthorizer.NewLocalConfigProvider(restConfig.GetRestConfig), + iamauthorizer.Versions, + ) + builder := &IdentityAccessManagementAPIBuilder{ store: store, userLegacyStore: user.NewLegacyStore(store, accessClient, enableAuthnMutation, tracing), @@ -102,6 +112,7 @@ func RegisterAPIService( externalGroupMappingStorage: externalGroupMappingStorageBackend, teamGroupsHandler: teamGroupsHandlerImpl, sso: ssoService, + resourceParentProvider: resourceParentProvider, authorizer: authorizer, legacyAccessClient: legacyAccessClient, accessClient: accessClient, @@ -114,9 +125,11 @@ func RegisterAPIService( dual: dual, unified: unified, userSearchClient: resource.NewSearchClient(dualwrite.NewSearchAdapter(dual), iamv0.UserResourceInfo.GroupResource(), - unified, user.NewUserLegacySearchClient(userService, tracing), features), + unified, user.NewUserLegacySearchClient(orgService, tracing, cfg), features), teamSearch: NewTeamSearchHandler(tracing, dual, team.NewLegacyTeamSearchClient(teamService), unified, features), } + builder.userSearchHandler = user.NewSearchHandler(tracing, builder.userSearchClient, features, cfg) + apiregistration.RegisterAPI(builder) return builder, nil @@ -130,6 +143,8 @@ func NewAPIService( features featuremgmt.FeatureToggles, zClient zanzana.Client, reg prometheus.Registerer, + tokenExchanger authn.TokenExchanger, + authorizerDialConfigs map[schema.GroupResource]iamauthorizer.DialConfig, ) *IdentityAccessManagementAPIBuilder { store := legacy.NewLegacySQLStores(dbProvider) resourcePermissionsStorage := resourcepermission.ProvideStorageBackend(dbProvider) @@ -138,6 +153,11 @@ func NewAPIService( resourceAuthorizer := gfauthorizer.NewResourceAuthorizer(accessClient) coreRoleAuthorizer := iamauthorizer.NewCoreRoleAuthorizer(accessClient) + resourceParentProvider := iamauthorizer.NewApiParentProvider( + iamauthorizer.NewRemoteConfigProvider(authorizerDialConfigs, tokenExchanger), + iamauthorizer.Versions, + ) + return &IdentityAccessManagementAPIBuilder{ store: store, display: user.NewLegacyDisplayREST(store), @@ -148,6 +168,7 @@ func NewAPIService( logger: log.New("iam.apis"), features: features, accessClient: accessClient, + resourceParentProvider: resourceParentProvider, zClient: zClient, zTickets: make(chan bool, MaxConcurrentZanzanaWrites), reg: reg, @@ -440,7 +461,7 @@ func (b *IdentityAccessManagementAPIBuilder) UpdateResourcePermissionsAPIGroup( return fmt.Errorf("expected RegistryStoreDualWrite, got %T", dw) } - authzWrapper := storewrapper.New(regStoreDW, iamauthorizer.NewResourcePermissionsAuthorizer(b.accessClient)) + authzWrapper := storewrapper.New(regStoreDW, iamauthorizer.NewResourcePermissionsAuthorizer(b.accessClient, b.resourceParentProvider)) storage[iamv0.ResourcePermissionInfo.StoragePath()] = authzWrapper return nil @@ -510,10 +531,18 @@ func (b *IdentityAccessManagementAPIBuilder) PostProcessOpenAPI(oas *spec3.OpenA func (b *IdentityAccessManagementAPIBuilder) GetAPIRoutes(gv schema.GroupVersion) *builder.APIRoutes { defs := b.GetOpenAPIDefinitions()(func(path string) spec.Ref { return spec.Ref{} }) - routes := b.teamSearch.GetAPIRoutes(defs) - routes.Namespace = append(routes.Namespace, b.display.GetAPIRoutes(defs).Namespace...) + searchRoutes := make([]*builder.APIRoutes, 0, 2) + if b.userSearchHandler != nil { + searchRoutes = append(searchRoutes, b.userSearchHandler.GetAPIRoutes(defs)) + } - return routes + if b.teamSearch != nil { + searchRoutes = append(searchRoutes, b.teamSearch.GetAPIRoutes(defs)) + } + + routes := []*builder.APIRoutes{b.display.GetAPIRoutes(defs)} + routes = append(routes, searchRoutes...) + return mergeAPIRoutes(routes...) } func (b *IdentityAccessManagementAPIBuilder) GetAuthorizer() authorizer.Authorizer { @@ -621,3 +650,15 @@ func NewLocalStore(resourceInfo utils.ResourceInfo, scheme *runtime.Scheme, defa store, err := grafanaregistry.NewRegistryStore(scheme, resourceInfo, optsGetter) return store, err } + +func mergeAPIRoutes(routes ...*builder.APIRoutes) *builder.APIRoutes { + merged := &builder.APIRoutes{} + for _, r := range routes { + if r == nil { + continue + } + merged.Root = append(merged.Root, r.Root...) + merged.Namespace = append(merged.Namespace, r.Namespace...) + } + return merged +} diff --git a/pkg/registry/apis/iam/user/legacy_search.go b/pkg/registry/apis/iam/user/legacy_search.go index 7fb6c13f7a6..41b54995c38 100644 --- a/pkg/registry/apis/iam/user/legacy_search.go +++ b/pkg/registry/apis/iam/user/legacy_search.go @@ -2,16 +2,22 @@ package user import ( "context" + "encoding/binary" "fmt" "log/slog" "math" + "regexp" + "sort" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc" "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/services/user" - res "github.com/grafana/grafana/pkg/storage/unified/resource" + "github.com/grafana/grafana/pkg/services/org" + "github.com/grafana/grafana/pkg/services/search/model" + "github.com/grafana/grafana/pkg/services/searchusers/sortopts" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/unified/resource" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" "github.com/grafana/grafana/pkg/storage/unified/search/builders" ) @@ -21,28 +27,36 @@ const ( UserResourceGroup = "iam.grafana.com" ) -var _ resourcepb.ResourceIndexClient = (*UserLegacySearchClient)(nil) +var ( + _ resourcepb.ResourceIndexClient = (*UserLegacySearchClient)(nil) + fieldLogin = fmt.Sprintf("%s%s", resource.SEARCH_FIELD_PREFIX, builders.USER_LOGIN) + fieldEmail = fmt.Sprintf("%s%s", resource.SEARCH_FIELD_PREFIX, builders.USER_EMAIL) + fieldLastSeenAt = fmt.Sprintf("%s%s", resource.SEARCH_FIELD_PREFIX, builders.USER_LAST_SEEN_AT) + fieldRole = fmt.Sprintf("%s%s", resource.SEARCH_FIELD_PREFIX, builders.USER_ROLE) + wildcardsMatcher = regexp.MustCompile(`[\*\?\\]`) +) // UserLegacySearchClient is a client for searching for users in the legacy search engine. type UserLegacySearchClient struct { resourcepb.ResourceIndexClient - userService user.Service - log *slog.Logger - tracer trace.Tracer + orgService org.Service + log *slog.Logger + tracer trace.Tracer + cfg *setting.Cfg } // NewUserLegacySearchClient creates a new UserLegacySearchClient. -func NewUserLegacySearchClient(userService user.Service, tracer trace.Tracer) *UserLegacySearchClient { +func NewUserLegacySearchClient(orgService org.Service, tracer trace.Tracer, cfg *setting.Cfg) *UserLegacySearchClient { return &UserLegacySearchClient{ - userService: userService, - log: slog.Default().With("logger", "legacy-user-search-client"), - tracer: tracer, + orgService: orgService, + log: slog.Default().With("logger", "legacy-user-search-client"), + tracer: tracer, + cfg: cfg, } } // Search searches for users in the legacy search engine. // It only supports exact matching for title, login, or email. -// FIXME: This implementation only supports a single field query and will be extended in the future. func (c *UserLegacySearchClient) Search(ctx context.Context, req *resourcepb.ResourceSearchRequest, _ ...grpc.CallOption) (*resourcepb.ResourceSearchResponse, error) { ctx, span := c.tracer.Start(ctx, "user.Search") defer span.End() @@ -52,21 +66,30 @@ func (c *UserLegacySearchClient) Search(ctx context.Context, req *resourcepb.Res return nil, err } - if req.Limit > 100 { - req.Limit = 100 + if req.Limit > maxLimit { + req.Limit = maxLimit } if req.Limit <= 0 { - req.Limit = 1 + req.Limit = 30 } if req.Page > math.MaxInt32 || req.Page < 0 { return nil, fmt.Errorf("invalid page number: %d", req.Page) } - query := &user.SearchUsersQuery{ - SignedInUser: signedInUser, - Limit: int(req.Limit), - Page: int(req.Page), + if req.Page < 1 { + req.Page = 1 + } + + legacySortOptions := convertToSortOptions(req.SortBy) + + query := &org.SearchOrgUsersQuery{ + OrgID: signedInUser.GetOrgID(), + Limit: int(req.Limit), + Page: int(req.Page), + SortOpts: legacySortOptions, + + User: signedInUser, } var title, login, email string @@ -76,19 +99,15 @@ func (c *UserLegacySearchClient) Search(ctx context.Context, req *resourcepb.Res c.log.Warn("only single value fields are supported for legacy search, using first value", "field", field.Key, "values", vals) } switch field.Key { - case res.SEARCH_FIELD_TITLE: + case resource.SEARCH_FIELD_TITLE: title = vals[0] - case "fields.login": + case fieldLogin: login = vals[0] - case "fields.email": + case fieldEmail: email = vals[0] } } - if title == "" && login == "" && email == "" { - return nil, fmt.Errorf("at least one of title, login, or email must be provided for the query") - } - // The user store's Search method combines these into an OR. // For legacy search we can only supply one. if title != "" { @@ -99,20 +118,35 @@ func (c *UserLegacySearchClient) Search(ctx context.Context, req *resourcepb.Res query.Query = email } - columns := getColumns(req.Fields) + // Unified search `query` has wildcards, but legacy search does not support them. + // We have to remove them here to make legacy search work as expected with SQL LIKE queries. + if req.Query != "" { + query.Query = wildcardsMatcher.ReplaceAllString(req.Query, "") + } + + fields := req.Fields + if len(fields) == 0 { + fields = []string{resource.SEARCH_FIELD_TITLE, fieldEmail, fieldLogin, fieldLastSeenAt, fieldRole} + } + + columns := getColumns(fields) list := &resourcepb.ResourceSearchResponse{ Results: &resourcepb.ResourceTable{ Columns: columns, }, } - res, err := c.userService.Search(ctx, query) + res, err := c.orgService.SearchOrgUsers(ctx, query) if err != nil { return nil, err } - for _, u := range res.Users { - cells := createBaseCells(u, req.Fields) + for _, u := range res.OrgUsers { + if c.isHiddenUser(u.Login, signedInUser) { + continue + } + + cells := createCells(u, req.Fields) list.Results.Rows = append(list.Results.Rows, &resourcepb.ResourceTableRow{ Key: getResourceKey(u, req.Options.Key.Namespace), Cells: cells, @@ -123,7 +157,19 @@ func (c *UserLegacySearchClient) Search(ctx context.Context, req *resourcepb.Res return list, nil } -func getResourceKey(item *user.UserSearchHitDTO, namespace string) *resourcepb.ResourceKey { +func (c *UserLegacySearchClient) isHiddenUser(login string, signedInUser identity.Requester) bool { + if login == "" || signedInUser.GetIsGrafanaAdmin() || login == signedInUser.GetUsername() { + return false + } + + if _, hidden := c.cfg.HiddenUsers[login]; hidden { + return true + } + + return false +} + +func getResourceKey(item *org.OrgUserDTO, namespace string) *resourcepb.ResourceKey { return &resourcepb.ResourceKey{ Namespace: namespace, Group: UserResourceGroup, @@ -133,42 +179,74 @@ func getResourceKey(item *user.UserSearchHitDTO, namespace string) *resourcepb.R } func getColumns(fields []string) []*resourcepb.ResourceTableColumnDefinition { - columns := defaultColumns() + cols := make([]*resourcepb.ResourceTableColumnDefinition, 0, len(fields)) + standardSearchFields := resource.StandardSearchFields() for _, field := range fields { switch field { - case "email": - columns = append(columns, builders.UserTableColumnDefinitions[builders.USER_EMAIL]) - case "login": - columns = append(columns, builders.UserTableColumnDefinitions[builders.USER_LOGIN]) + case resource.SEARCH_FIELD_TITLE: + cols = append(cols, standardSearchFields.Field(resource.SEARCH_FIELD_TITLE)) + case fieldLastSeenAt: + cols = append(cols, builders.UserTableColumnDefinitions[builders.USER_LAST_SEEN_AT]) + case fieldRole: + cols = append(cols, builders.UserTableColumnDefinitions[builders.USER_ROLE]) + case fieldEmail: + cols = append(cols, builders.UserTableColumnDefinitions[builders.USER_EMAIL]) + case fieldLogin: + cols = append(cols, builders.UserTableColumnDefinitions[builders.USER_LOGIN]) } } - return columns + return cols } -func createBaseCells(u *user.UserSearchHitDTO, fields []string) [][]byte { - cells := createDefaultCells(u) +func createCells(u *org.OrgUserDTO, fields []string) [][]byte { + cells := make([][]byte, 0, len(fields)) for _, field := range fields { switch field { - case "email": + case resource.SEARCH_FIELD_TITLE: + cells = append(cells, []byte(u.Name)) + case fieldEmail: cells = append(cells, []byte(u.Email)) - case "login": + case fieldLogin: cells = append(cells, []byte(u.Login)) + case fieldLastSeenAt: + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, uint64(u.LastSeenAt.Unix())) + cells = append(cells, b) + case fieldRole: + cells = append(cells, []byte(u.Role)) } } return cells } -func createDefaultCells(u *user.UserSearchHitDTO) [][]byte { - return [][]byte{ - []byte(u.UID), - []byte(u.Name), - } -} +func convertToSortOptions(sortBy []*resourcepb.ResourceSearchRequest_Sort) []model.SortOption { + opts := []model.SortOption{} + for _, s := range sortBy { + field := s.Field + // Handle mapping if necessary + switch field { + case fieldLastSeenAt: + field = "lastSeenAtAge" + case resource.SEARCH_FIELD_TITLE: + field = "name" + case fieldLogin: + field = "login" + case fieldEmail: + field = "email" + } -func defaultColumns() []*resourcepb.ResourceTableColumnDefinition { - searchFields := res.StandardSearchFields() - return []*resourcepb.ResourceTableColumnDefinition{ - searchFields.Field(res.SEARCH_FIELD_NAME), - searchFields.Field(res.SEARCH_FIELD_TITLE), + suffix := "asc" + if s.Desc { + suffix = "desc" + } + key := fmt.Sprintf("%s-%s", field, suffix) + + if opt, ok := sortopts.SortOptionsByQueryParam[key]; ok { + opts = append(opts, opt) + } } + sort.Slice(opts, func(i, j int) bool { + return opts[i].Index < opts[j].Index || (opts[i].Index == opts[j].Index && opts[i].Name < opts[j].Name) + }) + return opts } diff --git a/pkg/registry/apis/iam/user/legacy_search_fake.go b/pkg/registry/apis/iam/user/legacy_search_fake.go index b68e944c84c..e2effd7947e 100644 --- a/pkg/registry/apis/iam/user/legacy_search_fake.go +++ b/pkg/registry/apis/iam/user/legacy_search_fake.go @@ -5,7 +5,7 @@ import ( "google.golang.org/grpc" - "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" ) @@ -13,7 +13,7 @@ import ( type FakeUserLegacySearchClient struct { resourcepb.ResourceIndexClient SearchFunc func(ctx context.Context, req *resourcepb.ResourceSearchRequest, opts ...grpc.CallOption) (*resourcepb.ResourceSearchResponse, error) - Users []*user.UserSearchHitDTO + Users []*org.OrgUserDTO } // Search calls the underlying SearchFunc or simulates a search over the Users slice. @@ -23,7 +23,7 @@ func (c *FakeUserLegacySearchClient) Search(ctx context.Context, req *resourcepb } // Basic filtering for testing purposes - var filteredUsers []*user.UserSearchHitDTO + var filteredUsers []*org.OrgUserDTO var queryValue string for _, field := range req.Options.Fields { @@ -43,7 +43,7 @@ func (c *FakeUserLegacySearchClient) Search(ctx context.Context, req *resourcepb for _, u := range filteredUsers { rows = append(rows, &resourcepb.ResourceTableRow{ Key: getResourceKey(u, req.Options.Key.Namespace), - Cells: createBaseCells(u, req.Fields), + Cells: createCells(u, req.Fields), }) } diff --git a/pkg/registry/apis/iam/user/legacy_search_test.go b/pkg/registry/apis/iam/user/legacy_search_test.go index 6bd49185786..e3dc873fe3c 100644 --- a/pkg/registry/apis/iam/user/legacy_search_test.go +++ b/pkg/registry/apis/iam/user/legacy_search_test.go @@ -9,29 +9,15 @@ import ( "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/infra/tracing" + "github.com/grafana/grafana/pkg/services/org" + "github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/user" - "github.com/grafana/grafana/pkg/services/user/usertest" + "github.com/grafana/grafana/pkg/setting" res "github.com/grafana/grafana/pkg/storage/unified/resource" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" ) func TestUserLegacySearchClient_Search(t *testing.T) { - t.Run("should return error if no query fields are provided", func(t *testing.T) { - mockUserService := usertest.NewMockService(t) - client := NewUserLegacySearchClient(mockUserService, tracing.NewNoopTracerService()) - ctx := identity.WithRequester(context.Background(), &user.SignedInUser{OrgID: 1, UserID: 1}) - req := &resourcepb.ResourceSearchRequest{ - Options: &resourcepb.ListOptions{ - Key: &resourcepb.ResourceKey{Namespace: "default"}, - }, - } - - _, err := client.Search(ctx, req) - - require.Error(t, err) - require.Equal(t, "at least one of title, login, or email must be provided for the query", err.Error()) - }) - testCases := []struct { name string fieldKey string @@ -66,8 +52,8 @@ func TestUserLegacySearchClient_Search(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - mockUserService := usertest.NewMockService(t) - client := NewUserLegacySearchClient(mockUserService, tracing.NewNoopTracerService()) + mockOrgService := orgtest.NewMockService(t) + client := NewUserLegacySearchClient(mockOrgService, tracing.NewNoopTracerService(), &setting.Cfg{}) ctx := identity.WithRequester(context.Background(), &user.SignedInUser{OrgID: 1, UserID: 1}) req := &resourcepb.ResourceSearchRequest{ Limit: 10, @@ -81,14 +67,14 @@ func TestUserLegacySearchClient_Search(t *testing.T) { Fields: []string{"email", "login"}, } - mockUsers := []*user.UserSearchHitDTO{ - {ID: 1, UID: "uid1", Name: "Test User 1", Email: "test1@example.com", Login: "testlogin1"}, + mockUsers := []*org.OrgUserDTO{ + {UID: "uid1", Name: "Test User 1", Email: "test1@example.com", Login: "testlogin1"}, } - mockUserService.On("Search", mock.Anything, mock.MatchedBy(func(q *user.SearchUsersQuery) bool { + mockOrgService.On("SearchOrgUsers", mock.Anything, mock.MatchedBy(func(q *org.SearchOrgUsersQuery) bool { return q.Query == tc.expectedQuery && q.Limit == 10 && q.Page == 1 - })).Return(&user.SearchUserQueryResult{ - Users: mockUsers, + })).Return(&org.SearchOrgUsersQueryResult{ + OrgUsers: mockUsers, TotalCount: 1, }, nil) @@ -113,7 +99,7 @@ func TestUserLegacySearchClient_Search(t *testing.T) { require.Equal(t, UserResource, row.Key.Resource) require.Equal(t, u.UID, row.Key.Name) - expectedCells := createBaseCells(&user.UserSearchHitDTO{ + expectedCells := createCells(&org.OrgUserDTO{ UID: u.UID, Name: u.Name, Email: u.Email, @@ -125,8 +111,8 @@ func TestUserLegacySearchClient_Search(t *testing.T) { } t.Run("title should have precedence over login and email", func(t *testing.T) { - mockUserService := usertest.NewMockService(t) - client := NewUserLegacySearchClient(mockUserService, tracing.NewNoopTracerService()) + mockOrgService := orgtest.NewMockService(t) + client := NewUserLegacySearchClient(mockOrgService, tracing.NewNoopTracerService(), &setting.Cfg{}) ctx := identity.WithRequester(context.Background(), &user.SignedInUser{OrgID: 1, UserID: 1}) req := &resourcepb.ResourceSearchRequest{ Options: &resourcepb.ListOptions{ @@ -139,9 +125,9 @@ func TestUserLegacySearchClient_Search(t *testing.T) { }, } - mockUserService.On("Search", mock.Anything, mock.MatchedBy(func(q *user.SearchUsersQuery) bool { + mockOrgService.On("SearchOrgUsers", mock.Anything, mock.MatchedBy(func(q *org.SearchOrgUsersQuery) bool { return q.Query == "title" - })).Return(&user.SearchUserQueryResult{Users: []*user.UserSearchHitDTO{}, TotalCount: 0}, nil) + })).Return(&org.SearchOrgUsersQueryResult{OrgUsers: []*org.OrgUserDTO{}, TotalCount: 0}, nil) _, err := client.Search(ctx, req) require.NoError(t, err) diff --git a/pkg/registry/apis/iam/user/search.go b/pkg/registry/apis/iam/user/search.go new file mode 100644 index 00000000000..d2de838105a --- /dev/null +++ b/pkg/registry/apis/iam/user/search.go @@ -0,0 +1,399 @@ +package user + +import ( + "encoding/binary" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "go.opentelemetry.io/otel/trace" + "k8s.io/apimachinery/pkg/selection" + "k8s.io/kube-openapi/pkg/common" + "k8s.io/kube-openapi/pkg/spec3" + "k8s.io/kube-openapi/pkg/validation/spec" + + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/services/apiserver/builder" + "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/unified/resource" + "github.com/grafana/grafana/pkg/storage/unified/resourcepb" + "github.com/grafana/grafana/pkg/storage/unified/search/builders" + "github.com/grafana/grafana/pkg/util" + "github.com/grafana/grafana/pkg/util/errhttp" +) + +const maxLimit = 100 + +type SearchHandler struct { + log *slog.Logger + client resourcepb.ResourceIndexClient + tracer trace.Tracer + features featuremgmt.FeatureToggles + cfg *setting.Cfg +} + +func NewSearchHandler(tracer trace.Tracer, searchClient resourcepb.ResourceIndexClient, features featuremgmt.FeatureToggles, cfg *setting.Cfg) *SearchHandler { + return &SearchHandler{ + client: searchClient, + log: slog.Default().With("logger", "grafana-apiserver.user.search"), + tracer: tracer, + features: features, + cfg: cfg, + } +} + +func (s *SearchHandler) GetAPIRoutes(defs map[string]common.OpenAPIDefinition) *builder.APIRoutes { + searchResults := defs["github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetSearchUsers"].Schema + return &builder.APIRoutes{ + Namespace: []builder.APIRouteHandler{ + { + Path: "searchUsers", + Spec: &spec3.PathProps{ + Get: &spec3.Operation{ + OperationProps: spec3.OperationProps{ + Description: "User search", + Tags: []string{"Search"}, + OperationId: "getSearchUsers", + Parameters: []*spec3.Parameter{ + { + ParameterProps: spec3.ParameterProps{ + Name: "namespace", + In: "path", + Required: true, + Example: "default", + Description: "workspace", + Schema: spec.StringProperty(), + }, + }, + { + ParameterProps: spec3.ParameterProps{ + Name: "query", + In: "query", + Required: false, + Schema: spec.StringProperty(), + }, + }, + { + ParameterProps: spec3.ParameterProps{ + Name: "limit", + In: "query", + Description: "number of results to return", + Example: 30, + Required: false, + Schema: spec.Int64Property(), + }, + }, + { + ParameterProps: spec3.ParameterProps{ + Name: "page", + In: "query", + Description: "page number (starting from 1)", + Example: 1, + Required: false, + Schema: spec.Int64Property(), + }, + }, + { + ParameterProps: spec3.ParameterProps{ + Name: "offset", + In: "query", + Description: "number of results to skip", + Example: 0, + Required: false, + Schema: spec.Int64Property(), + }, + }, + { + ParameterProps: spec3.ParameterProps{ + Name: "sort", + In: "query", + Description: "sortable field", + Example: "", + Examples: map[string]*spec3.Example{ + "": { + ExampleProps: spec3.ExampleProps{ + Summary: "default sorting", + Value: "", + }, + }, + "title": { + ExampleProps: spec3.ExampleProps{ + Summary: "title ascending", + Value: "title", + }, + }, + "-title": { + ExampleProps: spec3.ExampleProps{ + Summary: "title descending", + Value: "-title", + }, + }, + "lastSeenAt": { + ExampleProps: spec3.ExampleProps{ + Summary: "last seen at ascending", + Value: "lastSeenAt", + }, + }, + "-lastSeenAt": { + ExampleProps: spec3.ExampleProps{ + Summary: "last seen at descending", + Value: "-lastSeenAt", + }, + }, + "email": { + ExampleProps: spec3.ExampleProps{ + Summary: "email ascending", + Value: "email", + }, + }, + "-email": { + ExampleProps: spec3.ExampleProps{ + Summary: "email descending", + Value: "-email", + }, + }, + "login": { + ExampleProps: spec3.ExampleProps{ + Summary: "login ascending", + Value: "login", + }, + }, + "-login": { + ExampleProps: spec3.ExampleProps{ + Summary: "login descending", + Value: "-login", + }, + }, + }, + Required: false, + Schema: spec.StringProperty(), + }, + }, + }, + Responses: &spec3.Responses{ + ResponsesProps: spec3.ResponsesProps{ + Default: &spec3.Response{ + ResponseProps: spec3.ResponseProps{ + Description: "Default OK response", + Content: map[string]*spec3.MediaType{ + "application/json": { + MediaTypeProps: spec3.MediaTypeProps{ + Schema: &searchResults, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + Handler: s.DoSearch, + }, + }, + } +} + +func (s *SearchHandler) DoSearch(w http.ResponseWriter, r *http.Request) { + ctx, span := s.tracer.Start(r.Context(), "user.search") + defer span.End() + + queryParams, err := url.ParseQuery(r.URL.RawQuery) + if err != nil { + errhttp.Write(ctx, err, w) + return + } + + requester, err := identity.GetRequester(ctx) + if err != nil { + errhttp.Write(ctx, fmt.Errorf("no identity found for request: %w", err), w) + return + } + + limit := 30 + offset := 0 + page := 1 + if queryParams.Has("limit") { + limit, _ = strconv.Atoi(queryParams.Get("limit")) + } + if queryParams.Has("offset") { + offset, _ = strconv.Atoi(queryParams.Get("offset")) + if offset > 0 && limit > 0 { + page = (offset / limit) + 1 + } + } else if queryParams.Has("page") { + page, _ = strconv.Atoi(queryParams.Get("page")) + offset = (page - 1) * limit + } + + // Escape characters that are used by bleve wildcard search to be literal strings. + rawQuery := escapeBleveQuery(queryParams.Get("query")) + + searchQuery := fmt.Sprintf(`*%s*`, rawQuery) + + userGvr := iamv0.UserResourceInfo.GroupResource() + request := &resourcepb.ResourceSearchRequest{ + Options: &resourcepb.ListOptions{ + Key: &resourcepb.ResourceKey{ + Group: userGvr.Group, + Resource: userGvr.Resource, + Namespace: requester.GetNamespace(), + }, + }, + Query: searchQuery, + Fields: []string{resource.SEARCH_FIELD_TITLE, fieldEmail, fieldLogin, fieldLastSeenAt, fieldRole}, + Limit: int64(limit), + Page: int64(page), + Offset: int64(offset), + } + + if !requester.GetIsGrafanaAdmin() { + // FIXME: Use the new config service instead of the legacy one + hiddenUsers := []string{} + for user := range s.cfg.HiddenUsers { + if user != requester.GetUsername() { + hiddenUsers = append(hiddenUsers, user) + } + } + if len(hiddenUsers) > 0 { + request.Options.Fields = append(request.Options.Fields, &resourcepb.Requirement{ + Key: fieldLogin, + Operator: string(selection.NotIn), + Values: hiddenUsers, + }) + } + } + + if queryParams.Has("sort") { + for _, sort := range queryParams["sort"] { + currField := sort + desc := false + if strings.HasPrefix(sort, "-") { + currField = sort[1:] + desc = true + } + if slices.Contains(builders.UserSortableExtraFields, currField) { + sort = resource.SEARCH_FIELD_PREFIX + currField + } else { + sort = currField + } + s := &resourcepb.ResourceSearchRequest_Sort{ + Field: sort, + Desc: desc, + } + request.SortBy = append(request.SortBy, s) + } + } + + resp, err := s.client.Search(ctx, request) + if err != nil { + errhttp.Write(ctx, err, w) + return + } + + result, err := ParseResults(resp) + if err != nil { + errhttp.Write(ctx, err, w) + return + } + s.write(w, result) +} + +func (s *SearchHandler) write(w http.ResponseWriter, obj any) { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(obj); err != nil { + s.log.Error("failed to encode JSON response", "error", err) + } +} + +func ParseResults(result *resourcepb.ResourceSearchResponse) (*iamv0.GetSearchUsers, error) { + if result == nil { + return iamv0.NewGetSearchUsers(), nil + } else if result.Error != nil { + return iamv0.NewGetSearchUsers(), fmt.Errorf("%d error searching: %s: %s", result.Error.Code, result.Error.Message, result.Error.Details) + } else if result.Results == nil { + return iamv0.NewGetSearchUsers(), nil + } + + titleIDX := -1 + emailIDX := -1 + loginIDX := -1 + lastSeenAtIDX := -1 + roleIDX := -1 + + for i, v := range result.Results.Columns { + switch v.Name { + case resource.SEARCH_FIELD_TITLE: + titleIDX = i + case builders.USER_EMAIL: + emailIDX = i + case builders.USER_LOGIN: + loginIDX = i + case builders.USER_LAST_SEEN_AT: + lastSeenAtIDX = i + case builders.USER_ROLE: + roleIDX = i + } + } + + sr := iamv0.NewGetSearchUsers() + sr.TotalHits = result.TotalHits + sr.QueryCost = result.QueryCost + sr.MaxScore = result.MaxScore + sr.Hits = make([]iamv0.UserHit, 0, len(result.Results.Rows)) + + for _, row := range result.Results.Rows { + if len(row.Cells) != len(result.Results.Columns) { + return iamv0.NewGetSearchUsers(), fmt.Errorf("error parsing user search response: mismatch number of columns and cells") + } + + var login string + if loginIDX >= 0 && row.Cells[loginIDX] != nil { + login = string(row.Cells[loginIDX]) + } + + hit := iamv0.UserHit{ + Name: row.Key.Name, + Login: login, + } + + if titleIDX >= 0 && row.Cells[titleIDX] != nil { + hit.Title = string(row.Cells[titleIDX]) + } + + if emailIDX >= 0 && row.Cells[emailIDX] != nil { + hit.Email = string(row.Cells[emailIDX]) + } + + if roleIDX >= 0 && row.Cells[roleIDX] != nil { + hit.Role = string(row.Cells[roleIDX]) + } + + if lastSeenAtIDX >= 0 && row.Cells[lastSeenAtIDX] != nil { + if len(row.Cells[lastSeenAtIDX]) == 8 { + hit.LastSeenAt = int64(binary.BigEndian.Uint64(row.Cells[lastSeenAtIDX])) + hit.LastSeenAtAge = util.GetAgeString(time.Unix(hit.LastSeenAt, 0)) + } + } + + sr.Hits = append(sr.Hits, hit) + } + + return sr, nil +} + +var bleveEscapeRegex = regexp.MustCompile(`([\\*?])`) + +func escapeBleveQuery(query string) string { + return bleveEscapeRegex.ReplaceAllString(query, `\$1`) +} diff --git a/pkg/registry/apis/iam/user/search_test.go b/pkg/registry/apis/iam/user/search_test.go new file mode 100644 index 00000000000..588ab37da39 --- /dev/null +++ b/pkg/registry/apis/iam/user/search_test.go @@ -0,0 +1,169 @@ +package user + +import ( + "context" + "net/http/httptest" + "testing" + + "google.golang.org/grpc" + + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/apiserver/rest" + "github.com/grafana/grafana/pkg/infra/tracing" + "github.com/grafana/grafana/pkg/services/featuremgmt" + legacyuser "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/legacysql/dualwrite" + "github.com/grafana/grafana/pkg/storage/unified/resource" + "github.com/grafana/grafana/pkg/storage/unified/resourcepb" +) + +func TestSearchFallback(t *testing.T) { + tests := []struct { + name string + mode rest.DualWriterMode + expectUnified bool + }{ + {name: "should hit legacy search handler on mode 0", mode: rest.Mode0, expectUnified: false}, + {name: "should hit legacy search handler on mode 1", mode: rest.Mode1, expectUnified: false}, + {name: "should hit legacy search handler on mode 2", mode: rest.Mode2, expectUnified: false}, + {name: "should hit unified storage search handler on mode 3", mode: rest.Mode3, expectUnified: true}, + {name: "should hit unified storage search handler on mode 4", mode: rest.Mode4, expectUnified: true}, + {name: "should hit unified storage search handler on mode 5", mode: rest.Mode5, expectUnified: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mockClient := &MockClient{} + mockLegacyClient := &MockClient{} + + cfg := &setting.Cfg{ + UnifiedStorage: map[string]setting.UnifiedStorageConfig{ + "users.iam.grafana.app": {DualWriterMode: tt.mode}, + }, + } + dual := dualwrite.ProvideStaticServiceForTests(cfg) + + searchClient := resource.NewSearchClient(dualwrite.NewSearchAdapter(dual), iamv0.UserResourceInfo.GroupResource(), mockClient, mockLegacyClient, featuremgmt.WithFeatures()) + searchHandler := NewSearchHandler(tracing.NewNoopTracerService(), searchClient, featuremgmt.WithFeatures(), cfg) + + rr := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/searchUsers", nil) + req.Header.Add("content-type", "application/json") + req = req.WithContext(identity.WithRequester(req.Context(), &legacyuser.SignedInUser{Namespace: "test"})) + + searchHandler.DoSearch(rr, req) + + if tt.expectUnified { + if mockClient.LastSearchRequest == nil { + t.Fatalf("expected Unified Search to be called, but it was not") + } + } else { + if mockLegacyClient.LastSearchRequest == nil { + t.Fatalf("expected Legacy Search to be called, but it was not") + } + } + }) + } +} + +// MockClient implements the ResourceIndexClient interface for testing +type MockClient struct { + resourcepb.ResourceIndexClient + resource.ResourceIndex + + LastSearchRequest *resourcepb.ResourceSearchRequest + + MockResponses []*resourcepb.ResourceSearchResponse + MockCalls []*resourcepb.ResourceSearchRequest + CallCount int +} + +func (m *MockClient) Search(ctx context.Context, in *resourcepb.ResourceSearchRequest, opts ...grpc.CallOption) (*resourcepb.ResourceSearchResponse, error) { + m.LastSearchRequest = in + m.MockCalls = append(m.MockCalls, in) + + var response *resourcepb.ResourceSearchResponse + if m.CallCount < len(m.MockResponses) { + response = m.MockResponses[m.CallCount] + } + + m.CallCount = m.CallCount + 1 + + if response == nil { + response = &resourcepb.ResourceSearchResponse{} + } + + return response, nil +} +func (m *MockClient) GetStats(ctx context.Context, in *resourcepb.ResourceStatsRequest, opts ...grpc.CallOption) (*resourcepb.ResourceStatsResponse, error) { + return nil, nil +} +func (m *MockClient) CountManagedObjects(ctx context.Context, in *resourcepb.CountManagedObjectsRequest, opts ...grpc.CallOption) (*resourcepb.CountManagedObjectsResponse, error) { + return nil, nil +} +func (m *MockClient) Watch(ctx context.Context, in *resourcepb.WatchRequest, opts ...grpc.CallOption) (resourcepb.ResourceStore_WatchClient, error) { + return nil, nil +} +func (m *MockClient) Delete(ctx context.Context, in *resourcepb.DeleteRequest, opts ...grpc.CallOption) (*resourcepb.DeleteResponse, error) { + return nil, nil +} +func (m *MockClient) Create(ctx context.Context, in *resourcepb.CreateRequest, opts ...grpc.CallOption) (*resourcepb.CreateResponse, error) { + return nil, nil +} +func (m *MockClient) Update(ctx context.Context, in *resourcepb.UpdateRequest, opts ...grpc.CallOption) (*resourcepb.UpdateResponse, error) { + return nil, nil +} +func (m *MockClient) Read(ctx context.Context, in *resourcepb.ReadRequest, opts ...grpc.CallOption) (*resourcepb.ReadResponse, error) { + return nil, nil +} +func (m *MockClient) GetBlob(ctx context.Context, in *resourcepb.GetBlobRequest, opts ...grpc.CallOption) (*resourcepb.GetBlobResponse, error) { + return nil, nil +} +func (m *MockClient) PutBlob(ctx context.Context, in *resourcepb.PutBlobRequest, opts ...grpc.CallOption) (*resourcepb.PutBlobResponse, error) { + return nil, nil +} +func (m *MockClient) List(ctx context.Context, in *resourcepb.ListRequest, opts ...grpc.CallOption) (*resourcepb.ListResponse, error) { + return nil, nil +} +func (m *MockClient) ListManagedObjects(ctx context.Context, in *resourcepb.ListManagedObjectsRequest, opts ...grpc.CallOption) (*resourcepb.ListManagedObjectsResponse, error) { + return nil, nil +} +func (m *MockClient) IsHealthy(ctx context.Context, in *resourcepb.HealthCheckRequest, opts ...grpc.CallOption) (*resourcepb.HealthCheckResponse, error) { + return nil, nil +} +func (m *MockClient) BulkProcess(ctx context.Context, opts ...grpc.CallOption) (resourcepb.BulkStore_BulkProcessClient, error) { + return nil, nil +} +func (m *MockClient) UpdateIndex(ctx context.Context, reason string) error { + return nil +} + +func (m *MockClient) GetQuotaUsage(ctx context.Context, req *resourcepb.QuotaUsageRequest, opts ...grpc.CallOption) (*resourcepb.QuotaUsageResponse, error) { + return nil, nil +} + +func TestEscapeBleveQuery(t *testing.T) { + tests := []struct { + input string + expected string + }{ + {input: "normal", expected: "normal"}, + {input: "*", expected: "\\*"}, + {input: "?", expected: "\\?"}, + {input: "\\", expected: "\\\\"}, + {input: "\\*", expected: "\\\\\\*"}, + {input: "*\\?", expected: "\\*\\\\\\?"}, + {input: "foo*bar", expected: "foo\\*bar"}, + } + + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + got := escapeBleveQuery(tt.input) + if got != tt.expected { + t.Errorf("escapeBleveQuery(%q) = %q, want %q", tt.input, got, tt.expected) + } + }) + } +} diff --git a/pkg/registry/apis/iam/user/store.go b/pkg/registry/apis/iam/user/store.go index 97daee3af18..53a146412ea 100644 --- a/pkg/registry/apis/iam/user/store.go +++ b/pkg/registry/apis/iam/user/store.go @@ -3,7 +3,6 @@ package user import ( "context" "fmt" - "time" "go.opentelemetry.io/otel/trace" "k8s.io/apimachinery/pkg/apis/meta/internalversion" @@ -35,7 +34,7 @@ var ( _ rest.TableConvertor = (*LegacyStore)(nil) ) -var resource = iamv0alpha1.UserResourceInfo +var userResource = iamv0alpha1.UserResourceInfo func NewLegacyStore(store legacy.LegacyIdentityStore, ac claims.AccessClient, enableAuthnMutation bool, tracer trace.Tracer) *LegacyStore { return &LegacyStore{store, ac, enableAuthnMutation, tracer} @@ -54,7 +53,7 @@ func (s *LegacyStore) Update(ctx context.Context, name string, objInfo rest.Upda defer span.End() if !s.enableAuthnMutation { - return nil, false, apierrors.NewMethodNotSupported(resource.GroupResource(), "update") + return nil, false, apierrors.NewMethodNotSupported(userResource.GroupResource(), "update") } ns, err := request.NamespaceInfoFrom(ctx, true) @@ -105,7 +104,7 @@ func (s *LegacyStore) Update(ctx context.Context, name string, objInfo rest.Upda // DeleteCollection implements rest.CollectionDeleter. func (s *LegacyStore) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *internalversion.ListOptions) (runtime.Object, error) { - return nil, apierrors.NewMethodNotSupported(resource.GroupResource(), "deletecollection") + return nil, apierrors.NewMethodNotSupported(userResource.GroupResource(), "deletecollection") } // Delete implements rest.GracefulDeleter. @@ -114,7 +113,7 @@ func (s *LegacyStore) Delete(ctx context.Context, name string, deleteValidation defer span.End() if !s.enableAuthnMutation { - return nil, false, apierrors.NewMethodNotSupported(resource.GroupResource(), "delete") + return nil, false, apierrors.NewMethodNotSupported(userResource.GroupResource(), "delete") } ns, err := request.NamespaceInfoFrom(ctx, true) @@ -131,7 +130,7 @@ func (s *LegacyStore) Delete(ctx context.Context, name string, deleteValidation return nil, false, err } if found == nil || len(found.Items) < 1 { - return nil, false, resource.NewNotFound(name) + return nil, false, userResource.NewNotFound(name) } userToDelete := &found.Items[0] @@ -157,7 +156,7 @@ func (s *LegacyStore) Delete(ctx context.Context, name string, deleteValidation } func (s *LegacyStore) New() runtime.Object { - return resource.NewFunc() + return userResource.NewFunc() } func (s *LegacyStore) Destroy() {} @@ -167,15 +166,15 @@ func (s *LegacyStore) NamespaceScoped() bool { } func (s *LegacyStore) GetSingularName() string { - return resource.GetSingularName() + return userResource.GetSingularName() } func (s *LegacyStore) NewList() runtime.Object { - return resource.NewListFunc() + return userResource.NewListFunc() } func (s *LegacyStore) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { - return resource.TableConverter().ConvertToTable(ctx, object, tableOptions) + return userResource.TableConverter().ConvertToTable(ctx, object, tableOptions) } func (s *LegacyStore) List(ctx context.Context, options *internalversion.ListOptions) (runtime.Object, error) { @@ -183,7 +182,7 @@ func (s *LegacyStore) List(ctx context.Context, options *internalversion.ListOpt defer span.End() res, err := common.List( - ctx, resource, s.ac, common.PaginationFromListOptions(options), + ctx, userResource, s.ac, common.PaginationFromListOptions(options), func(ctx context.Context, ns claims.NamespaceInfo, p common.Pagination) (*common.ListResponse[iamv0alpha1.User], error) { found, err := s.store.ListUsers(ctx, ns, legacy.ListUserQuery{ Pagination: p, @@ -231,10 +230,10 @@ func (s *LegacyStore) Get(ctx context.Context, name string, options *metav1.GetO Pagination: common.Pagination{Limit: 1}, }) if found == nil || err != nil { - return nil, resource.NewNotFound(name) + return nil, userResource.NewNotFound(name) } if len(found.Items) < 1 { - return nil, resource.NewNotFound(name) + return nil, userResource.NewNotFound(name) } obj := toUserItem(&found.Items[0], ns.Value) @@ -247,7 +246,7 @@ func (s *LegacyStore) Create(ctx context.Context, obj runtime.Object, createVali defer span.End() if !s.enableAuthnMutation { - return nil, apierrors.NewMethodNotSupported(resource.GroupResource(), "create") + return nil, apierrors.NewMethodNotSupported(userResource.GroupResource(), "create") } ns, err := request.NamespaceInfoFrom(ctx, true) @@ -310,18 +309,12 @@ func toUserItem(u *common.UserWithRole, ns string) iamv0alpha1.User { Provisioned: u.IsProvisioned, Role: u.Role, }, + Status: iamv0alpha1.UserStatus{ + LastSeenAt: u.LastSeenAt.Unix(), + }, } obj, _ := utils.MetaAccessor(item) obj.SetUpdatedTimestamp(&u.Updated) - obj.SetAnnotation(AnnoKeyLastSeenAt, formatTime(&u.LastSeenAt)) obj.SetDeprecatedInternalID(u.ID) // nolint:staticcheck return *item } - -func formatTime(v *time.Time) string { - txt := "" - if v != nil && v.Unix() != 0 { - txt = v.UTC().Format(time.RFC3339) - } - return txt -} diff --git a/pkg/registry/apis/iam/user/validate.go b/pkg/registry/apis/iam/user/validate.go index fb4e0791689..1fa1d28a875 100644 --- a/pkg/registry/apis/iam/user/validate.go +++ b/pkg/registry/apis/iam/user/validate.go @@ -128,7 +128,7 @@ func validateEmail(ctx context.Context, searchClient resourcepb.ResourceIndexCli Operator: string(selection.Equals), Values: []string{email}, }, - }, []string{"name", "email", "login"}) + }, []string{"fields.email", "fields.login"}) resp, err := searchClient.Search(ctx, req) if err != nil { @@ -159,7 +159,7 @@ func validateLogin(ctx context.Context, searchClient resourcepb.ResourceIndexCli Operator: string(selection.Equals), Values: []string{login}, }, - }, []string{"name", "email", "login"}) + }, []string{"fields.email", "fields.login"}) resp, err := searchClient.Search(ctx, req) if err != nil { return err diff --git a/pkg/registry/apis/iam/user/validate_test.go b/pkg/registry/apis/iam/user/validate_test.go index fb558912ab0..17909f2ca7a 100644 --- a/pkg/registry/apis/iam/user/validate_test.go +++ b/pkg/registry/apis/iam/user/validate_test.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/authlib/types" iamv0alpha1 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -178,7 +178,7 @@ func TestValidateOnCreate(t *testing.T) { IsGrafanaAdmin: false, }, searchClient: &FakeUserLegacySearchClient{ - Users: []*user.UserSearchHitDTO{ + Users: []*org.OrgUserDTO{ {Email: "existing@example"}, }, }, @@ -202,7 +202,7 @@ func TestValidateOnCreate(t *testing.T) { IsGrafanaAdmin: false, }, searchClient: &FakeUserLegacySearchClient{ - Users: []*user.UserSearchHitDTO{ + Users: []*org.OrgUserDTO{ {Login: "existinguser"}, }, }, @@ -490,7 +490,7 @@ func TestValidateOnUpdate(t *testing.T) { IsGrafanaAdmin: true, }, searchClient: &FakeUserLegacySearchClient{ - Users: []*user.UserSearchHitDTO{ + Users: []*org.OrgUserDTO{ {Email: "two@example"}, }, }, @@ -516,7 +516,7 @@ func TestValidateOnUpdate(t *testing.T) { IsGrafanaAdmin: true, }, searchClient: &FakeUserLegacySearchClient{ - Users: []*user.UserSearchHitDTO{ + Users: []*org.OrgUserDTO{ {Name: "other", UID: "uid456", Login: "two"}, }, }, @@ -536,7 +536,7 @@ func TestValidateOnUpdate(t *testing.T) { IsGrafanaAdmin: true, }, searchClient: &FakeUserLegacySearchClient{ - Users: []*user.UserSearchHitDTO{ + Users: []*org.OrgUserDTO{ {Login: "testuser", Email: "test@example"}, }, }, diff --git a/pkg/registry/apis/preferences/register.go b/pkg/registry/apis/preferences/register.go index 8964b0e0cd7..e0e6ff947fc 100644 --- a/pkg/registry/apis/preferences/register.go +++ b/pkg/registry/apis/preferences/register.go @@ -42,12 +42,6 @@ func RegisterAPIService( users user.Service, apiregistration builder.APIRegistrar, ) *APIBuilder { - // Requires development settings and clearly experimental - //nolint:staticcheck // not yet migrated to OpenFeature - if !features.IsEnabledGlobally(featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs) { - return nil - } - sql := legacy.NewLegacySQL(legacysql.NewDatabaseProvider(db)) builder := &APIBuilder{ merger: newMerger(cfg, sql), diff --git a/pkg/registry/apis/provisioning/controller/health.go b/pkg/registry/apis/provisioning/controller/health.go index ed5f19c6ed0..a35846ed20e 100644 --- a/pkg/registry/apis/provisioning/controller/health.go +++ b/pkg/registry/apis/provisioning/controller/health.go @@ -26,6 +26,18 @@ type StatusPatcher interface { Patch(ctx context.Context, repo *provisioning.Repository, patchOperations ...map[string]interface{}) error } +// HealthCheckerInterface defines the interface for health checking operations +// +//go:generate mockery --name=HealthCheckerInterface --structname=MockHealthChecker +type HealthCheckerInterface interface { + ShouldCheckHealth(repo *provisioning.Repository) bool + RefreshHealth(ctx context.Context, repo repository.Repository) (*provisioning.TestResults, provisioning.HealthStatus, error) + RefreshHealthWithPatchOps(ctx context.Context, repo repository.Repository) (*provisioning.TestResults, provisioning.HealthStatus, []map[string]interface{}, error) + RefreshTimestamp(ctx context.Context, repo *provisioning.Repository) error + RecordFailure(ctx context.Context, failureType provisioning.HealthFailureType, err error, repo *provisioning.Repository) error + HasRecentFailure(healthStatus provisioning.HealthStatus, failureType provisioning.HealthFailureType) bool +} + // HealthChecker provides unified health checking for repositories type HealthChecker struct { statusPatcher StatusPatcher @@ -162,6 +174,33 @@ func (hc *HealthChecker) RefreshHealth(ctx context.Context, repo repository.Repo return testResults, newHealthStatus, nil } +// RefreshHealthWithPatchOps performs a health check on an existing repository +// and returns the test results, health status, and patch operations to apply. +// This method does NOT apply the patch itself, allowing the caller to batch +// multiple status updates together to avoid race conditions. +func (hc *HealthChecker) RefreshHealthWithPatchOps(ctx context.Context, repo repository.Repository) (*provisioning.TestResults, provisioning.HealthStatus, []map[string]interface{}, error) { + cfg := repo.Config() + + // Use health checker to perform comprehensive health check with existing status + testResults, newHealthStatus, err := hc.refreshHealth(ctx, repo, cfg.Status.Health) + if err != nil { + return nil, provisioning.HealthStatus{}, nil, fmt.Errorf("health check failed: %w", err) + } + + var patchOps []map[string]interface{} + + // Only return patch operation if health status actually changed + if hc.hasHealthStatusChanged(cfg.Status.Health, newHealthStatus) { + patchOps = append(patchOps, map[string]interface{}{ + "op": "replace", + "path": "/status/health", + "value": newHealthStatus, + }) + } + + return testResults, newHealthStatus, patchOps, nil +} + // RefreshTimestamp updates the health status timestamp without changing other fields func (hc *HealthChecker) RefreshTimestamp(ctx context.Context, repo *provisioning.Repository) error { // Update the timestamp on the existing health status diff --git a/pkg/registry/apis/provisioning/controller/health_test.go b/pkg/registry/apis/provisioning/controller/health_test.go index 91a0a67a131..003f14bcee6 100644 --- a/pkg/registry/apis/provisioning/controller/health_test.go +++ b/pkg/registry/apis/provisioning/controller/health_test.go @@ -532,6 +532,136 @@ func TestRefreshHealth(t *testing.T) { } } +func TestRefreshHealthWithPatchOps(t *testing.T) { + tests := []struct { + name string + testResult *provisioning.TestResults + testError error + existingStatus provisioning.HealthStatus + expectError bool + expectedHealth bool + expectPatchOps bool + expectedPatchPath string + }{ + { + name: "successful health check with status change", + testResult: &provisioning.TestResults{ + Success: true, + Code: 200, + }, + testError: nil, + existingStatus: provisioning.HealthStatus{ + Healthy: false, + Error: provisioning.HealthFailureHealth, + Checked: time.Now().Add(-time.Hour).UnixMilli(), + }, + expectError: false, + expectedHealth: true, + expectPatchOps: true, + expectedPatchPath: "/status/health", + }, + { + name: "failed health check with status change", + testResult: &provisioning.TestResults{ + Success: false, + Code: 500, + Errors: []provisioning.ErrorDetails{ + {Detail: "connection failed"}, + }, + }, + testError: nil, + existingStatus: provisioning.HealthStatus{ + Healthy: true, + Checked: time.Now().Add(-time.Hour).UnixMilli(), + }, + expectError: false, + expectedHealth: false, + expectPatchOps: true, + expectedPatchPath: "/status/health", + }, + { + name: "no status change - no patch ops returned", + testResult: &provisioning.TestResults{ + Success: true, + Code: 200, + }, + testError: nil, + existingStatus: provisioning.HealthStatus{ + Healthy: true, + Checked: time.Now().Add(-15 * time.Second).UnixMilli(), + }, + expectError: false, + expectedHealth: true, + expectPatchOps: false, + }, + { + name: "test repository error", + testResult: nil, + testError: errors.New("repository test failed"), + existingStatus: provisioning.HealthStatus{ + Healthy: true, + Checked: time.Now().Add(-time.Hour).UnixMilli(), + }, + expectError: true, + expectedHealth: false, + expectPatchOps: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create mock repository + mockRepo := &mockRepository{ + config: &provisioning.Repository{ + Spec: provisioning.RepositorySpec{ + Title: "Test Repository", + Type: provisioning.LocalRepositoryType, + }, + Status: provisioning.RepositoryStatus{ + Health: tt.existingStatus, + }, + }, + testResult: tt.testResult, + testError: tt.testError, + } + + // Create health checker with validator and tester + validator := repository.NewValidator(30*time.Second, []provisioning.SyncTargetType{provisioning.SyncTargetTypeFolder, provisioning.SyncTargetTypeInstance}, true) + hc := NewHealthChecker(nil, prometheus.NewPedanticRegistry(), repository.NewSimpleRepositoryTester(validator)) + + // Call RefreshHealthWithPatchOps + testResults, healthStatus, patchOps, err := hc.RefreshHealthWithPatchOps(context.Background(), mockRepo) + + // Verify error + if tt.expectError { + assert.Error(t, err) + assert.Nil(t, testResults) + return + } + assert.NoError(t, err) + + // Verify health status + assert.Equal(t, tt.expectedHealth, healthStatus.Healthy) + + // Verify patch operations + if tt.expectPatchOps { + assert.NotEmpty(t, patchOps, "expected patch operations to be returned") + assert.Len(t, patchOps, 1) + assert.Equal(t, "replace", patchOps[0]["op"]) + assert.Equal(t, tt.expectedPatchPath, patchOps[0]["path"]) + assert.Equal(t, healthStatus, patchOps[0]["value"]) + } else { + assert.Empty(t, patchOps, "expected no patch operations to be returned") + } + + // Verify test results + if tt.testResult != nil { + assert.Equal(t, tt.testResult, testResults) + } + }) + } +} + func TestHasHealthStatusChanged(t *testing.T) { tests := []struct { name string diff --git a/pkg/registry/apis/provisioning/controller/mocks/HealthCheckerInterface.go b/pkg/registry/apis/provisioning/controller/mocks/HealthCheckerInterface.go new file mode 100644 index 00000000000..e70711463bf --- /dev/null +++ b/pkg/registry/apis/provisioning/controller/mocks/HealthCheckerInterface.go @@ -0,0 +1,187 @@ +// Code generated by mockery v2.53.4. DO NOT EDIT. + +package mocks + +import ( + context "context" + + mock "github.com/stretchr/testify/mock" + + repository "github.com/grafana/grafana/apps/provisioning/pkg/repository" + + v0alpha1 "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" +) + +// MockHealthChecker is an autogenerated mock type for the HealthCheckerInterface type +type MockHealthChecker struct { + mock.Mock +} + +// HasRecentFailure provides a mock function with given fields: healthStatus, failureType +func (_m *MockHealthChecker) HasRecentFailure(healthStatus v0alpha1.HealthStatus, failureType v0alpha1.HealthFailureType) bool { + ret := _m.Called(healthStatus, failureType) + + if len(ret) == 0 { + panic("no return value specified for HasRecentFailure") + } + + var r0 bool + if rf, ok := ret.Get(0).(func(v0alpha1.HealthStatus, v0alpha1.HealthFailureType) bool); ok { + r0 = rf(healthStatus, failureType) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// RecordFailure provides a mock function with given fields: ctx, failureType, err, repo +func (_m *MockHealthChecker) RecordFailure(ctx context.Context, failureType v0alpha1.HealthFailureType, err error, repo *v0alpha1.Repository) error { + ret := _m.Called(ctx, failureType, err, repo) + + if len(ret) == 0 { + panic("no return value specified for RecordFailure") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, v0alpha1.HealthFailureType, error, *v0alpha1.Repository) error); ok { + r0 = rf(ctx, failureType, err, repo) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// RefreshHealth provides a mock function with given fields: ctx, repo +func (_m *MockHealthChecker) RefreshHealth(ctx context.Context, repo repository.Repository) (*v0alpha1.TestResults, v0alpha1.HealthStatus, error) { + ret := _m.Called(ctx, repo) + + if len(ret) == 0 { + panic("no return value specified for RefreshHealth") + } + + var r0 *v0alpha1.TestResults + var r1 v0alpha1.HealthStatus + var r2 error + if rf, ok := ret.Get(0).(func(context.Context, repository.Repository) (*v0alpha1.TestResults, v0alpha1.HealthStatus, error)); ok { + return rf(ctx, repo) + } + if rf, ok := ret.Get(0).(func(context.Context, repository.Repository) *v0alpha1.TestResults); ok { + r0 = rf(ctx, repo) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*v0alpha1.TestResults) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, repository.Repository) v0alpha1.HealthStatus); ok { + r1 = rf(ctx, repo) + } else { + r1 = ret.Get(1).(v0alpha1.HealthStatus) + } + + if rf, ok := ret.Get(2).(func(context.Context, repository.Repository) error); ok { + r2 = rf(ctx, repo) + } else { + r2 = ret.Error(2) + } + + return r0, r1, r2 +} + +// RefreshHealthWithPatchOps provides a mock function with given fields: ctx, repo +func (_m *MockHealthChecker) RefreshHealthWithPatchOps(ctx context.Context, repo repository.Repository) (*v0alpha1.TestResults, v0alpha1.HealthStatus, []map[string]interface{}, error) { + ret := _m.Called(ctx, repo) + + if len(ret) == 0 { + panic("no return value specified for RefreshHealthWithPatchOps") + } + + var r0 *v0alpha1.TestResults + var r1 v0alpha1.HealthStatus + var r2 []map[string]interface{} + var r3 error + if rf, ok := ret.Get(0).(func(context.Context, repository.Repository) (*v0alpha1.TestResults, v0alpha1.HealthStatus, []map[string]interface{}, error)); ok { + return rf(ctx, repo) + } + if rf, ok := ret.Get(0).(func(context.Context, repository.Repository) *v0alpha1.TestResults); ok { + r0 = rf(ctx, repo) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*v0alpha1.TestResults) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, repository.Repository) v0alpha1.HealthStatus); ok { + r1 = rf(ctx, repo) + } else { + r1 = ret.Get(1).(v0alpha1.HealthStatus) + } + + if rf, ok := ret.Get(2).(func(context.Context, repository.Repository) []map[string]interface{}); ok { + r2 = rf(ctx, repo) + } else { + if ret.Get(2) != nil { + r2 = ret.Get(2).([]map[string]interface{}) + } + } + + if rf, ok := ret.Get(3).(func(context.Context, repository.Repository) error); ok { + r3 = rf(ctx, repo) + } else { + r3 = ret.Error(3) + } + + return r0, r1, r2, r3 +} + +// RefreshTimestamp provides a mock function with given fields: ctx, repo +func (_m *MockHealthChecker) RefreshTimestamp(ctx context.Context, repo *v0alpha1.Repository) error { + ret := _m.Called(ctx, repo) + + if len(ret) == 0 { + panic("no return value specified for RefreshTimestamp") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *v0alpha1.Repository) error); ok { + r0 = rf(ctx, repo) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// ShouldCheckHealth provides a mock function with given fields: repo +func (_m *MockHealthChecker) ShouldCheckHealth(repo *v0alpha1.Repository) bool { + ret := _m.Called(repo) + + if len(ret) == 0 { + panic("no return value specified for ShouldCheckHealth") + } + + var r0 bool + if rf, ok := ret.Get(0).(func(*v0alpha1.Repository) bool); ok { + r0 = rf(repo) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// NewMockHealthChecker creates a new instance of MockHealthChecker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMockHealthChecker(t interface { + mock.TestingT + Cleanup(func()) +}) *MockHealthChecker { + mock := &MockHealthChecker{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/pkg/registry/apis/provisioning/controller/mocks/StatusPatcher.go b/pkg/registry/apis/provisioning/controller/mocks/StatusPatcher.go index 7cfe0b737bf..9999eee9006 100644 --- a/pkg/registry/apis/provisioning/controller/mocks/StatusPatcher.go +++ b/pkg/registry/apis/provisioning/controller/mocks/StatusPatcher.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.52.4. DO NOT EDIT. +// Code generated by mockery v2.53.4. DO NOT EDIT. package mocks diff --git a/pkg/registry/apis/provisioning/controller/repository.go b/pkg/registry/apis/provisioning/controller/repository.go index d624879b984..00821db3655 100644 --- a/pkg/registry/apis/provisioning/controller/repository.go +++ b/pkg/registry/apis/provisioning/controller/repository.go @@ -561,11 +561,16 @@ func (rc *RepositoryController) process(item *queueItem) error { } // Handle health checks using the health checker - _, healthStatus, err := rc.healthChecker.RefreshHealth(ctx, repo) + _, healthStatus, healthPatchOps, err := rc.healthChecker.RefreshHealthWithPatchOps(ctx, repo) if err != nil { return fmt.Errorf("update health status: %w", err) } + // Add health patch operations first + if len(healthPatchOps) > 0 { + patchOperations = append(patchOperations, healthPatchOps...) + } + // determine the sync strategy and sync status to apply syncOptions := rc.determineSyncStrategy(ctx, obj, repo, shouldResync, healthStatus) patchOperations = append(patchOperations, rc.determineSyncStatusOps(obj, syncOptions, healthStatus)...) diff --git a/pkg/registry/apis/provisioning/controller/repository_test.go b/pkg/registry/apis/provisioning/controller/repository_test.go index 8eab43d847f..9390d98ec34 100644 --- a/pkg/registry/apis/provisioning/controller/repository_test.go +++ b/pkg/registry/apis/provisioning/controller/repository_test.go @@ -39,6 +39,10 @@ func (m mockProvisioningV0alpha1Interface) Jobs(namespace string) client.JobInte panic("not needed for testing") } +func (m mockProvisioningV0alpha1Interface) Connections(namespace string) client.ConnectionInterface { + panic("not needed for testing") +} + func (m mockProvisioningV0alpha1Interface) Repositories(namespace string) client.RepositoryInterface { if m.repositoriesFunc != nil { return m.repositoriesFunc(namespace) @@ -350,6 +354,161 @@ type mockJobsQueueStore struct { *jobs.MockStore } +func TestRepositoryController_process_UnhealthyRepositoryStatusUpdate(t *testing.T) { + testCases := []struct { + name string + repo *provisioning.Repository + healthStatus provisioning.HealthStatus + hasHealthStatusChanged bool + expectedUnhealthyMessage bool + description string + }{ + { + name: "unhealthy repository should set unhealthy message in sync status", + repo: &provisioning.Repository{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-repo", + Namespace: "default", + Generation: 1, + }, + Spec: provisioning.RepositorySpec{ + Sync: provisioning.SyncOptions{ + Enabled: true, + IntervalSeconds: 300, + }, + }, + Status: provisioning.RepositoryStatus{ + ObservedGeneration: 1, + Health: provisioning.HealthStatus{ + Healthy: true, + Checked: time.Now().Add(-10 * time.Minute).UnixMilli(), + }, + Sync: provisioning.SyncStatus{ + State: provisioning.JobStateSuccess, + Finished: time.Now().Add(-1 * time.Minute).UnixMilli(), + Message: []string{}, + }, + }, + }, + healthStatus: provisioning.HealthStatus{ + Healthy: false, + Error: provisioning.HealthFailureHealth, + Checked: time.Now().UnixMilli(), + Message: []string{"connection failed"}, + }, + hasHealthStatusChanged: true, + expectedUnhealthyMessage: true, + description: "should set unhealthy message when repository becomes unhealthy", + }, + { + name: "unhealthy repository should not duplicate unhealthy message", + repo: &provisioning.Repository{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-repo", + Namespace: "default", + Generation: 1, + }, + Spec: provisioning.RepositorySpec{ + Sync: provisioning.SyncOptions{ + Enabled: true, + IntervalSeconds: 300, + }, + }, + Status: provisioning.RepositoryStatus{ + ObservedGeneration: 1, + Health: provisioning.HealthStatus{ + Healthy: false, + Checked: time.Now().Add(-2 * time.Minute).UnixMilli(), + }, + Sync: provisioning.SyncStatus{ + State: provisioning.JobStateError, + Finished: time.Now().Add(-1 * time.Minute).UnixMilli(), + Message: []string{"Repository is unhealthy"}, + }, + }, + }, + healthStatus: provisioning.HealthStatus{ + Healthy: false, + Error: provisioning.HealthFailureHealth, + Checked: time.Now().UnixMilli(), + Message: []string{"connection failed"}, + }, + hasHealthStatusChanged: false, + expectedUnhealthyMessage: false, + description: "should not set unhealthy message when it already exists", + }, + { + name: "healthy repository should clear unhealthy message", + repo: &provisioning.Repository{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-repo", + Namespace: "default", + Generation: 1, + }, + Spec: provisioning.RepositorySpec{ + Sync: provisioning.SyncOptions{ + Enabled: true, + IntervalSeconds: 300, + }, + }, + Status: provisioning.RepositoryStatus{ + ObservedGeneration: 1, + Health: provisioning.HealthStatus{ + Healthy: false, + Checked: time.Now().Add(-2 * time.Minute).UnixMilli(), + }, + Sync: provisioning.SyncStatus{ + State: provisioning.JobStateError, + Finished: time.Now().Add(-1 * time.Minute).UnixMilli(), + Message: []string{"Repository is unhealthy"}, + }, + }, + }, + healthStatus: provisioning.HealthStatus{ + Healthy: true, + Checked: time.Now().UnixMilli(), + Message: []string{}, + }, + hasHealthStatusChanged: true, + expectedUnhealthyMessage: false, + description: "should clear unhealthy message when repository becomes healthy", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Create controller + rc := &RepositoryController{} + + // Determine sync status ops (this is a pure function, no mocks needed) + syncOps := rc.determineSyncStatusOps(tc.repo, nil, tc.healthStatus) + + // Verify expectations + hasUnhealthyOp := false + hasClearUnhealthyOp := false + for _, op := range syncOps { + if path, ok := op["path"].(string); ok { + if path == "/status/sync/message" { + if messages, ok := op["value"].([]string); ok { + if len(messages) > 0 && messages[0] == "Repository is unhealthy" { + hasUnhealthyOp = true + } else if len(messages) == 0 { + hasClearUnhealthyOp = true + } + } + } + } + } + + if tc.expectedUnhealthyMessage { + assert.True(t, hasUnhealthyOp, tc.description+": expected unhealthy message operation") + } else if len(tc.repo.Status.Sync.Message) > 0 && tc.healthStatus.Healthy { + assert.True(t, hasClearUnhealthyOp, tc.description+": expected clear unhealthy message operation") + } + }) + } +} + func TestRepositoryController_shouldResync_StaleSyncStatus(t *testing.T) { testCases := []struct { name string diff --git a/pkg/registry/apis/provisioning/jobs/progress.go b/pkg/registry/apis/provisioning/jobs/progress.go index 97a293a5d8c..2cb9dc9ddcf 100644 --- a/pkg/registry/apis/provisioning/jobs/progress.go +++ b/pkg/registry/apis/provisioning/jobs/progress.go @@ -35,12 +35,13 @@ func maybeNotifyProgress(threshold time.Duration, fn ProgressFn) ProgressFn { // FIXME: ProgressRecorder should be initialized in the queue type JobResourceResult struct { - Name string - Group string - Kind string - Path string - Action repository.FileAction - Error error + Name string + Group string + Kind string + Path string + Action repository.FileAction + Error error + Warning error } type jobProgressRecorder struct { @@ -193,6 +194,10 @@ func (r *jobProgressRecorder) updateSummary(result JobResourceResult) { errorMsg := fmt.Sprintf("%s (file: %s, name: %s, action: %s)", result.Error.Error(), result.Path, result.Name, result.Action) summary.Errors = append(summary.Errors, errorMsg) summary.Error++ + } else if result.Warning != nil { + warningMsg := fmt.Sprintf("%s (file: %s, name: %s, action: %s)", result.Warning.Error(), result.Path, result.Name, result.Action) + summary.Warnings = append(summary.Warnings, warningMsg) + summary.Warning++ } else { switch result.Action { case repository.FileActionDeleted: @@ -266,8 +271,17 @@ func (r *jobProgressRecorder) Complete(ctx context.Context, err error) provision jobStatus.Message = err.Error() } - jobStatus.Summary = r.summary() + summaries := r.summary() + jobStatus.Summary = summaries jobStatus.Errors = r.errors + + // Extract warnings from summaries + warnings := make([]string, 0) + for _, summary := range summaries { + warnings = append(warnings, summary.Warnings...) + } + jobStatus.Warnings = warnings + jobStatus.URLs = r.refURLs tooManyErrors := r.maxErrors > 0 && r.errorCount >= r.maxErrors @@ -283,6 +297,9 @@ func (r *jobProgressRecorder) Complete(ctx context.Context, err error) provision jobStatus.Message = "completed with errors" jobStatus.State = provisioning.JobStateWarning } + } else if len(jobStatus.Warnings) > 0 { + jobStatus.State = provisioning.JobStateWarning + jobStatus.Message = "completed with warnings" } // Override message if progress have a more explicit message diff --git a/pkg/registry/apis/provisioning/jobs/progress_test.go b/pkg/registry/apis/provisioning/jobs/progress_test.go index caf44c767ff..7e849491bbe 100644 --- a/pkg/registry/apis/provisioning/jobs/progress_test.go +++ b/pkg/registry/apis/provisioning/jobs/progress_test.go @@ -2,9 +2,11 @@ package jobs import ( "context" + "errors" "testing" provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/apps/provisioning/pkg/repository" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -83,3 +85,170 @@ func TestJobProgressRecorderCompleteIncludesRefURLs(t *testing.T) { assert.Equal(t, provisioning.JobStateSuccess, finalStatus.State) assert.Equal(t, "completed successfully", finalStatus.Message) } + +func TestJobProgressRecorderWarningStatus(t *testing.T) { + ctx := context.Background() + + // Create a progress recorder + mockProgressFn := func(ctx context.Context, status provisioning.JobStatus) error { + return nil + } + recorder := newJobProgressRecorder(mockProgressFn).(*jobProgressRecorder) + + // Record a result with a warning + warningErr := errors.New("deprecated API used") + result := JobResourceResult{ + Name: "test-resource", + Group: "test.grafana.app", + Kind: "Dashboard", + Path: "dashboards/test.json", + Action: repository.FileActionUpdated, + Warning: warningErr, + } + recorder.Record(ctx, result) + + // Record another result with a different warning + warningErr2 := errors.New("missing optional field") + result2 := JobResourceResult{ + Name: "test-resource-2", + Group: "test.grafana.app", + Kind: "Dashboard", + Path: "dashboards/test2.json", + Action: repository.FileActionCreated, + Warning: warningErr2, + } + recorder.Record(ctx, result2) + + // Record a result with a warning from a different resource type + warningErr3 := errors.New("validation warning") + result3 := JobResourceResult{ + Name: "test-resource-3", + Group: "test.grafana.app", + Kind: "DataSource", + Path: "datasources/test.yaml", + Action: repository.FileActionCreated, + Warning: warningErr3, + } + recorder.Record(ctx, result3) + + // Verify warnings are stored in summaries + recorder.mu.RLock() + require.Len(t, recorder.summaries, 2) // Dashboard and DataSource + dashboardSummary := recorder.summaries["test.grafana.app:Dashboard"] + require.NotNil(t, dashboardSummary) + assert.Equal(t, int64(2), dashboardSummary.Warning) + assert.Len(t, dashboardSummary.Warnings, 2) + assert.Contains(t, dashboardSummary.Warnings[0], "deprecated API used") + assert.Contains(t, dashboardSummary.Warnings[1], "missing optional field") + + datasourceSummary := recorder.summaries["test.grafana.app:DataSource"] + require.NotNil(t, datasourceSummary) + assert.Equal(t, int64(1), datasourceSummary.Warning) + assert.Len(t, datasourceSummary.Warnings, 1) + assert.Contains(t, datasourceSummary.Warnings[0], "validation warning") + recorder.mu.RUnlock() + + // Complete the job + finalStatus := recorder.Complete(ctx, nil) + + // Verify the final status includes warnings + require.NotNil(t, finalStatus.Warnings) + assert.Len(t, finalStatus.Warnings, 3) + expectedWarnings := []string{ + "deprecated API used (file: dashboards/test.json, name: test-resource, action: updated)", + "missing optional field (file: dashboards/test2.json, name: test-resource-2, action: created)", + "validation warning (file: datasources/test.yaml, name: test-resource-3, action: created)", + } + assert.ElementsMatch(t, finalStatus.Warnings, expectedWarnings) + + // Verify the state is set to Warning + assert.Equal(t, provisioning.JobStateWarning, finalStatus.State) + assert.Equal(t, "completed with warnings", finalStatus.Message) + + // Verify summaries are included + require.Len(t, finalStatus.Summary, 2) + + // Verify no errors were recorded + assert.Empty(t, finalStatus.Errors) +} + +func TestJobProgressRecorderWarningWithErrors(t *testing.T) { + ctx := context.Background() + + // Create a progress recorder + mockProgressFn := func(ctx context.Context, status provisioning.JobStatus) error { + return nil + } + recorder := newJobProgressRecorder(mockProgressFn).(*jobProgressRecorder) + + // Record a result with an error (errors take precedence) + errorErr := errors.New("failed to process") + result := JobResourceResult{ + Name: "test-resource", + Group: "test.grafana.app", + Kind: "Dashboard", + Path: "dashboards/test.json", + Action: repository.FileActionUpdated, + Error: errorErr, + } + recorder.Record(ctx, result) + + // Record a result with only a warning + warningErr := errors.New("deprecated API used") + result2 := JobResourceResult{ + Name: "test-resource-2", + Group: "test.grafana.app", + Kind: "Dashboard", + Path: "dashboards/test2.json", + Action: repository.FileActionCreated, + Warning: warningErr, + } + recorder.Record(ctx, result2) + + // Complete the job + finalStatus := recorder.Complete(ctx, nil) + + // When there are errors, the state should be Warning (not Error unless too many) + // and warnings should still be included + assert.Equal(t, provisioning.JobStateWarning, finalStatus.State) + assert.Equal(t, "completed with errors", finalStatus.Message) + assert.Len(t, finalStatus.Errors, 1) + assert.Contains(t, finalStatus.Errors[0], "failed to process") + + // Warnings should still be extracted from summaries + require.NotNil(t, finalStatus.Warnings) + assert.Len(t, finalStatus.Warnings, 1) + assert.Contains(t, finalStatus.Warnings[0], "deprecated API used") +} + +func TestJobProgressRecorderWarningOnlyNoErrors(t *testing.T) { + ctx := context.Background() + + // Create a progress recorder + mockProgressFn := func(ctx context.Context, status provisioning.JobStatus) error { + return nil + } + recorder := newJobProgressRecorder(mockProgressFn).(*jobProgressRecorder) + + // Record only warnings, no errors + warningErr := errors.New("deprecated API used") + result := JobResourceResult{ + Name: "test-resource", + Group: "test.grafana.app", + Kind: "Dashboard", + Path: "dashboards/test.json", + Action: repository.FileActionUpdated, + Warning: warningErr, + } + recorder.Record(ctx, result) + + // Complete the job + finalStatus := recorder.Complete(ctx, nil) + + // Verify the state is Warning (not Error) when only warnings exist + assert.Equal(t, provisioning.JobStateWarning, finalStatus.State) + assert.Equal(t, "completed with warnings", finalStatus.Message) + assert.Empty(t, finalStatus.Errors) + require.NotNil(t, finalStatus.Warnings) + assert.Len(t, finalStatus.Warnings, 1) +} diff --git a/pkg/registry/apis/provisioning/register.go b/pkg/registry/apis/provisioning/register.go index d18fc1156a8..b479dc3f8c8 100644 --- a/pkg/registry/apis/provisioning/register.go +++ b/pkg/registry/apis/provisioning/register.go @@ -31,6 +31,7 @@ import ( dashboard "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v0alpha1" folders "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + connectionvalidation "github.com/grafana/grafana/apps/provisioning/pkg/connection" appcontroller "github.com/grafana/grafana/apps/provisioning/pkg/controller" clientset "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned" client "github.com/grafana/grafana/apps/provisioning/pkg/generated/clientset/versioned/typed/provisioning/v0alpha1" @@ -328,91 +329,148 @@ func (b *APIBuilder) GetAuthorizer() authorizer.Authorizer { return authorizer.DecisionDeny, "failed to find requester", err } - // Different routes may need different permissions. - // * Reading and modifying a repository's configuration requires administrator privileges. - // * Reading a repository's limited configuration (/stats & /settings) requires viewer privileges. - // * Reading a repository's files requires viewer privileges. - // * Reading a repository's refs requires viewer privileges. - // * Editing a repository's files requires editor privileges. - // * Syncing a repository requires editor privileges. - // * Exporting a repository requires administrator privileges. - // * Migrating a repository requires administrator privileges. - // * Testing a repository configuration requires administrator privileges. - // * Viewing a repository's history requires editor privileges. - - switch a.GetResource() { - case provisioning.RepositoryResourceInfo.GetName(): - // TODO: Support more fine-grained permissions than the basic roles. Especially on Enterprise. - switch a.GetSubresource() { - case "", "test", "jobs": - // Doing something with the repository itself. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil - - case "refs": - // This is strictly a read operation. It is handy on the frontend for viewers. - if id.GetOrgRole().Includes(identity.RoleViewer) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "viewer role is required", nil - case "files": - // Access to files is controlled by the AccessClient - return authorizer.DecisionAllow, "", nil - - case "resources", "sync", "history": - // These are strictly read operations. - // Sync can also be somewhat destructive, but it's expected to be fine to import changes. - if id.GetOrgRole().Includes(identity.RoleEditor) { - return authorizer.DecisionAllow, "", nil - } else { - return authorizer.DecisionDeny, "editor role is required", nil - } - case "status": - if id.GetOrgRole().Includes(identity.RoleViewer) && a.GetVerb() == apiutils.VerbGet { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "users cannot update the status of a repository", nil - default: - if id.GetIsGrafanaAdmin() { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "unmapped subresource defaults to no access", nil - } - - case "stats": - // This can leak information one shouldn't necessarily have access to. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil - - case "settings": - // This is strictly a read operation. It is handy on the frontend for viewers. - if id.GetOrgRole().Includes(identity.RoleViewer) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "viewer role is required", nil - - case provisioning.JobResourceInfo.GetName(), - provisioning.HistoricJobResourceInfo.GetName(): - // Jobs are shown on the configuration page. - if id.GetOrgRole().Includes(identity.RoleAdmin) { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "admin role is required", nil - - default: - // We haven't bothered with this kind yet. - if id.GetIsGrafanaAdmin() { - return authorizer.DecisionAllow, "", nil - } - return authorizer.DecisionDeny, "unmapped kind defaults to no access", nil - } + return b.authorizeResource(ctx, a, id) }) } +// authorizeResource handles authorization for different resources. +// Different routes may need different permissions. +// * Reading and modifying a repository's configuration requires administrator privileges. +// * Reading a repository's limited configuration (/stats & /settings) requires viewer privileges. +// * Reading a repository's files requires viewer privileges. +// * Reading a repository's refs requires viewer privileges. +// * Editing a repository's files requires editor privileges. +// * Syncing a repository requires editor privileges. +// * Exporting a repository requires administrator privileges. +// * Migrating a repository requires administrator privileges. +// * Testing a repository configuration requires administrator privileges. +// * Viewing a repository's history requires editor privileges. +func (b *APIBuilder) authorizeResource(ctx context.Context, a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { + switch a.GetResource() { + case provisioning.RepositoryResourceInfo.GetName(): + return b.authorizeRepositorySubresource(a, id) + case "stats": + return b.authorizeStats(id) + case "settings": + return b.authorizeSettings(id) + case provisioning.JobResourceInfo.GetName(), provisioning.HistoricJobResourceInfo.GetName(): + return b.authorizeJobs(id) + case provisioning.ConnectionResourceInfo.GetName(): + return b.authorizeConnectionSubresource(a, id) + default: + return b.authorizeDefault(id) + } +} + +// authorizeRepositorySubresource handles authorization for repository subresources. +func (b *APIBuilder) authorizeRepositorySubresource(a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { + // TODO: Support more fine-grained permissions than the basic roles. Especially on Enterprise. + switch a.GetSubresource() { + case "", "test": + // Doing something with the repository itself. + if id.GetOrgRole().Includes(identity.RoleAdmin) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "admin role is required", nil + + case "jobs": + // Posting jobs requires editor privileges (for syncing). + if id.GetOrgRole().Includes(identity.RoleAdmin) || id.GetOrgRole().Includes(identity.RoleEditor) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "editor role is required", nil + + case "refs": + // This is strictly a read operation. It is handy on the frontend for viewers. + if id.GetOrgRole().Includes(identity.RoleViewer) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "viewer role is required", nil + + case "files": + // Access to files is controlled by the AccessClient + return authorizer.DecisionAllow, "", nil + + case "resources", "sync", "history": + // These are strictly read operations. + // Sync can also be somewhat destructive, but it's expected to be fine to import changes. + if id.GetOrgRole().Includes(identity.RoleEditor) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "editor role is required", nil + + case "status": + if id.GetOrgRole().Includes(identity.RoleViewer) && a.GetVerb() == apiutils.VerbGet { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "users cannot update the status of a repository", nil + + default: + if id.GetIsGrafanaAdmin() { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "unmapped subresource defaults to no access", nil + } +} + +// authorizeStats handles authorization for stats resource. +func (b *APIBuilder) authorizeStats(id identity.Requester) (authorizer.Decision, string, error) { + // This can leak information one shouldn't necessarily have access to. + if id.GetOrgRole().Includes(identity.RoleAdmin) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "admin role is required", nil +} + +// authorizeSettings handles authorization for settings resource. +func (b *APIBuilder) authorizeSettings(id identity.Requester) (authorizer.Decision, string, error) { + // This is strictly a read operation. It is handy on the frontend for viewers. + if id.GetOrgRole().Includes(identity.RoleViewer) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "viewer role is required", nil +} + +// authorizeJobs handles authorization for job resources. +func (b *APIBuilder) authorizeJobs(id identity.Requester) (authorizer.Decision, string, error) { + // Jobs are shown on the configuration page. + if id.GetOrgRole().Includes(identity.RoleAdmin) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "admin role is required", nil +} + +// authorizeRepositorySubresource handles authorization for connections subresources. +func (b *APIBuilder) authorizeConnectionSubresource(a authorizer.Attributes, id identity.Requester) (authorizer.Decision, string, error) { + switch a.GetSubresource() { + case "": + // Doing something with the connection itself. + if id.GetOrgRole().Includes(identity.RoleAdmin) { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "admin role is required", nil + case "status": + if id.GetOrgRole().Includes(identity.RoleViewer) && a.GetVerb() == apiutils.VerbGet { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "users cannot update the status of a connection", nil + default: + if id.GetIsGrafanaAdmin() { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "unmapped subresource defaults to no access", nil + } +} + +// authorizeDefault handles authorization for unmapped resources. +func (b *APIBuilder) authorizeDefault(id identity.Requester) (authorizer.Decision, string, error) { + // We haven't bothered with this kind yet. + if id.GetIsGrafanaAdmin() { + return authorizer.DecisionAllow, "", nil + } + return authorizer.DecisionDeny, "unmapped kind defaults to no access", nil +} + func (b *APIBuilder) GetGroupVersion() schema.GroupVersion { return provisioning.SchemeGroupVersion } @@ -487,10 +545,19 @@ func (b *APIBuilder) UpdateAPIGroupInfo(apiGroupInfo *genericapiserver.APIGroupI storage[provisioning.HistoricJobResourceInfo.StoragePath()] = historicJobStore } + connectionsStore, err := grafanaregistry.NewRegistryStore(opts.Scheme, provisioning.ConnectionResourceInfo, opts.OptsGetter) + if err != nil { + return fmt.Errorf("failed to create connection storage: %w", err) + } + connectionStatusStorage := grafanaregistry.NewRegistryStatusStore(opts.Scheme, connectionsStore) + storage[provisioning.JobResourceInfo.StoragePath()] = jobStore storage[provisioning.RepositoryResourceInfo.StoragePath()] = repositoryStorage storage[provisioning.RepositoryResourceInfo.StoragePath("status")] = repositoryStatusStorage + storage[provisioning.ConnectionResourceInfo.StoragePath()] = connectionsStore + storage[provisioning.ConnectionResourceInfo.StoragePath("status")] = connectionStatusStorage + // TODO: Add some logic so that the connectors can registered themselves and we don't have logic all over the place storage[provisioning.RepositoryResourceInfo.StoragePath("test")] = NewTestConnector(b, repository.NewRepositoryTesterWithExistingChecker(repository.NewSimpleRepositoryTester(b.validator), b.VerifyAgainstExistingRepositories)) storage[provisioning.RepositoryResourceInfo.StoragePath("files")] = NewFilesConnector(b, b.parsers, b.clients, b.access) @@ -533,6 +600,11 @@ func (b *APIBuilder) Mutate(ctx context.Context, a admission.Attributes, o admis if ok { return nil } + // TODO: complete this as part of https://github.com/grafana/git-ui-sync-project/issues/700 + c, ok := obj.(*provisioning.Connection) + if ok { + return connectionvalidation.MutateConnection(c) + } r, ok := obj.(*provisioning.Repository) if !ok { @@ -582,6 +654,11 @@ func (b *APIBuilder) Validate(ctx context.Context, a admission.Attributes, o adm return nil } + connection, ok := obj.(*provisioning.Connection) + if ok { + return connectionvalidation.ValidateConnection(connection) + } + // Validate Jobs job, ok := obj.(*provisioning.Job) if ok { diff --git a/pkg/registry/apis/provisioning/resources/dualwriter.go b/pkg/registry/apis/provisioning/resources/dualwriter.go index 62f4ffd3b98..7c9005a8dd5 100644 --- a/pkg/registry/apis/provisioning/resources/dualwriter.go +++ b/pkg/registry/apis/provisioning/resources/dualwriter.go @@ -3,6 +3,7 @@ package resources import ( "context" "fmt" + "net/http" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -315,7 +316,19 @@ func (r *DualReadWriter) MoveResource(ctx context.Context, opts DualWriteOptions } func (r *DualReadWriter) moveDirectory(ctx context.Context, opts DualWriteOptions) (*ParsedResource, error) { - // For directory moves, we just perform the repository move without parsing + // Reject directory move operations for configured branch - use bulk operations instead + if r.isConfiguredBranch(opts) { + return nil, &apierrors.StatusError{ + ErrStatus: metav1.Status{ + Status: metav1.StatusFailure, + Code: http.StatusMethodNotAllowed, + Reason: metav1.StatusReasonMethodNotAllowed, + Message: "directory move operations are not available for configured branch. Use bulk move operations via the jobs API instead", + }, + } + } + + // For branch operations, we just perform the repository move without updating Grafana DB // Always use the provisioning identity when writing ctx, _, err := identity.WithProvisioningIdentity(ctx, r.repo.Config().Namespace) if err != nil { @@ -349,35 +362,6 @@ func (r *DualReadWriter) moveDirectory(ctx context.Context, opts DualWriteOption }, } - // Handle folder management for main branch - if r.shouldUpdateGrafanaDB(opts, nil) { - // Ensure destination folder path exists - if _, err := r.folders.EnsureFolderPathExist(ctx, opts.Path); err != nil { - return nil, fmt.Errorf("ensure destination folder path exists: %w", err) - } - - // Try to delete the old folder structure from grafana (if it exists) - // This handles cleanup when folders are moved to new locations - oldFolderName, err := r.folders.EnsureFolderPathExist(ctx, opts.OriginalPath) - if err != nil { - return nil, fmt.Errorf("ensure original folder path exists: %w", err) - } - - if oldFolderName != "" { - oldFolder, err := r.folders.GetFolder(ctx, oldFolderName) - if err != nil && !apierrors.IsNotFound(err) { - return nil, fmt.Errorf("get old folder for cleanup: %w", err) - } - - if err == nil { - err = r.folders.Client().Delete(ctx, oldFolder.GetName(), metav1.DeleteOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return nil, fmt.Errorf("delete old folder from storage: %w", err) - } - } - } - } - return parsed, nil } @@ -519,73 +503,62 @@ func (r *DualReadWriter) authorize(ctx context.Context, parsed *ParsedResource, }, parsed.Meta.GetFolder()) if err != nil || !rsp.Allowed { return apierrors.NewForbidden(parsed.GVR.GroupResource(), parsed.Obj.GetName(), - fmt.Errorf("no access to read the embedded file")) + fmt.Errorf("no access to perform %s on the resource", verb)) } - idType, _, err := authlib.ParseTypeID(id.GetID()) - if err != nil { - return apierrors.NewForbidden(parsed.GVR.GroupResource(), parsed.Obj.GetName(), fmt.Errorf("could not determine identity type to check access")) - } - // only apply role based access if identity is not of type access policy - if idType == authlib.TypeAccessPolicy || id.GetOrgRole().Includes(identity.RoleEditor) { - return nil - } - - return apierrors.NewForbidden(parsed.GVR.GroupResource(), parsed.Obj.GetName(), - fmt.Errorf("must be admin or editor to access files from provisioning")) + return nil } -func (r *DualReadWriter) authorizeCreateFolder(ctx context.Context, _ string) error { +func (r *DualReadWriter) authorizeCreateFolder(ctx context.Context, path string) error { id, err := identity.GetRequester(ctx) if err != nil { return apierrors.NewUnauthorized(err.Error()) } - // Simple role based access for now - if id.GetOrgRole().Includes(identity.RoleEditor) { - return nil + // Determine parent folder from path + parentFolder := "" + if path != "" { + parentPath := safepath.Dir(path) + if parentPath != "" { + parentFolder = ParseFolder(parentPath, r.repo.Config().Name).ID + } else { + parentFolder = RootFolder(r.repo.Config()) + } } - return apierrors.NewForbidden(FolderResource.GroupResource(), "", - fmt.Errorf("must be admin or editor to access folders with provisioning")) + // For folder create operations, use empty name to check parent folder permissions + rsp, err := r.access.Check(ctx, id, authlib.CheckRequest{ + Group: FolderResource.Group, + Resource: FolderResource.Resource, + Namespace: id.GetNamespace(), + Name: "", // Empty name for create operations + Verb: utils.VerbCreate, + }, parentFolder) + if err != nil || !rsp.Allowed { + return apierrors.NewForbidden(FolderResource.GroupResource(), path, + fmt.Errorf("no access to create folder in parent folder '%s'", parentFolder)) + } + + return nil } func (r *DualReadWriter) deleteFolder(ctx context.Context, opts DualWriteOptions) (*ParsedResource, error) { - // if the ref is set, it is not the active branch, so just delete the files from the branch - // and do not delete the items from grafana itself - if !r.shouldUpdateGrafanaDB(opts, nil) { - err := r.repo.Delete(ctx, opts.Path, opts.Ref, opts.Message) - if err != nil { - return nil, fmt.Errorf("error deleting folder from repository: %w", err) + // Reject directory delete operations for configured branch - use bulk operations instead + if r.isConfiguredBranch(opts) { + return nil, &apierrors.StatusError{ + ErrStatus: metav1.Status{ + Status: metav1.StatusFailure, + Code: http.StatusMethodNotAllowed, + Reason: metav1.StatusReasonMethodNotAllowed, + Message: "directory delete operations are not available for configured branch. Use bulk delete operations via the jobs API instead", + }, } - - return folderDeleteResponse(ctx, opts.Path, opts.Ref, r.repo) } - // before deleting from the repo, first get all children resources to delete from grafana afterwards - treeEntries, err := r.repo.ReadTree(ctx, "") + // For branch operations, just delete from the repository without updating Grafana DB + err := r.repo.Delete(ctx, opts.Path, opts.Ref, opts.Message) if err != nil { - return nil, fmt.Errorf("read repository tree: %w", err) - } - // note: parsedFolders will include the folder itself - parsedResources, parsedFolders, err := r.getChildren(ctx, opts.Path, treeEntries) - if err != nil { - return nil, fmt.Errorf("parse resources in folder: %w", err) - } - - // delete from the repo - err = r.repo.Delete(ctx, opts.Path, opts.Ref, opts.Message) - if err != nil { - return nil, fmt.Errorf("delete folder from repository: %w", err) - } - - // delete from grafana - ctx, _, err = identity.WithProvisioningIdentity(ctx, r.repo.Config().Namespace) - if err != nil { - return nil, err - } - if err := r.deleteChildren(ctx, parsedResources, parsedFolders); err != nil { - return nil, fmt.Errorf("delete folder from grafana: %w", err) + return nil, fmt.Errorf("error deleting folder from repository: %w", err) } return folderDeleteResponse(ctx, opts.Path, opts.Ref, r.repo) @@ -640,60 +613,11 @@ func folderDeleteResponse(ctx context.Context, path, ref string, repo repository return parsed, nil } -func (r *DualReadWriter) getChildren(ctx context.Context, folderPath string, treeEntries []repository.FileTreeEntry) ([]*ParsedResource, []Folder, error) { - var resourcesInFolder []repository.FileTreeEntry - var foldersInFolder []Folder - for _, entry := range treeEntries { - // make sure the path is supported (i.e. not ignored by git sync) and that the path is the folder itself or a child of the folder - if IsPathSupported(entry.Path) != nil || !safepath.InDir(entry.Path, folderPath) { - continue - } - // folders cannot be parsed as resources, so handle them separately - if entry.Blob { - resourcesInFolder = append(resourcesInFolder, entry) - } else { - folder := ParseFolder(entry.Path, r.repo.Config().Name) - foldersInFolder = append(foldersInFolder, folder) - } - } - - parsedResources := make([]*ParsedResource, len(resourcesInFolder)) - for i, entry := range resourcesInFolder { - fileInfo, err := r.repo.Read(ctx, entry.Path, "") - if err != nil && !apierrors.IsNotFound(err) { - return nil, nil, fmt.Errorf("could not find resource in repository: %w", err) - } - - parsed, err := r.parser.Parse(ctx, fileInfo) - if err != nil { - return nil, nil, fmt.Errorf("could not parse resource: %w", err) - } - - parsedResources[i] = parsed - } - - return parsedResources, foldersInFolder, nil -} - -func (r *DualReadWriter) deleteChildren(ctx context.Context, childrenResources []*ParsedResource, folders []Folder) error { - for _, parsed := range childrenResources { - err := parsed.Client.Delete(ctx, parsed.Obj.GetName(), metav1.DeleteOptions{}) - if err != nil && !apierrors.IsNotFound(err) { - return fmt.Errorf("failed to delete nested resource from grafana: %w", err) - } - } - - // we need to delete the folders furthest down in the tree first, as folder deletion will fail if there is anything inside of it - safepath.SortByDepth(folders, func(f Folder) string { return f.Path }, false) - - for _, f := range folders { - err := r.folders.Client().Delete(ctx, f.ID, metav1.DeleteOptions{}) - if err != nil { - return fmt.Errorf("failed to delete folder from grafana: %w", err) - } - } - - return nil +// isConfiguredBranch returns true if the ref targets the configured branch +// (empty ref means configured branch, or ref explicitly matches configured branch) +func (r *DualReadWriter) isConfiguredBranch(opts DualWriteOptions) bool { + configuredBranch := r.repo.Config().Branch() + return opts.Ref == "" || opts.Ref == configuredBranch } // shouldUpdateGrafanaDB returns true if we have an empty ref (targeting the configured branch) @@ -703,9 +627,5 @@ func (r *DualReadWriter) shouldUpdateGrafanaDB(opts DualWriteOptions, parsed *Pa return false } - if opts.Ref != "" && opts.Ref != opts.Branch { - return false - } - - return true + return r.isConfiguredBranch(opts) } diff --git a/pkg/registry/apis/query/query.go b/pkg/registry/apis/query/query.go index 99323eb2721..ad9c9ac9888 100644 --- a/pkg/registry/apis/query/query.go +++ b/pkg/registry/apis/query/query.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" + "github.com/grafana/authlib/authn" + claims "github.com/grafana/authlib/types" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/experimental/apis/data/v0alpha1" "github.com/grafana/grafana/pkg/api/dtos" @@ -154,11 +156,11 @@ func (r *queryREST) Connect(connectCtx context.Context, name string, _ runtime.O } } } - connectLogger.Debug("responder sending status code", "statusCode", statusCode) + connectLogger.Debug("responder sending status code", "statusCode", statusCode, "caller", getCaller(ctx)) }, func(err error) { - connectLogger.Error("error caught in handler", "err", err) + connectLogger.Error("error caught in handler", "err", err, "caller", getCaller(ctx)) span.SetStatus(codes.Error, "query error") if err == nil { @@ -480,3 +482,12 @@ func getValidDataSourceRef(ctx context.Context, ds *v0alpha1.DataSourceRef, id i return ds, nil } + +func getCaller(ctx context.Context) string { + authInfo, ok := claims.AuthInfoFrom(ctx) + if !ok { + return "" + } else { + return strings.Join(authInfo.GetExtra()[authn.ServiceIdentityKey], ",") + } +} diff --git a/pkg/registry/apis/query/query_test.go b/pkg/registry/apis/query/query_test.go index b23c78d55bc..56025d3893b 100644 --- a/pkg/registry/apis/query/query_test.go +++ b/pkg/registry/apis/query/query_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + claims "github.com/grafana/authlib/types" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" dataapi "github.com/grafana/grafana-plugin-sdk-go/experimental/apis/data/v0alpha1" @@ -180,7 +181,7 @@ func TestQueryAPI(t *testing.T) { legacyDatasourceLookup: &mockLegacyDataSourceLookup{}, } - reqCtx := identity.WithRequester(context.Background(), mockUser{}) + reqCtx := claims.WithAuthInfo(identity.WithRequester(context.Background(), mockUser{}), &mockAuthInfo{}) req := httptest.NewRequestWithContext(reqCtx, http.MethodPost, "/some-path", bytes.NewReader([]byte(tc.queryJSON))) req.Header.Set("Content-Type", "application/json") @@ -439,3 +440,11 @@ func TestMergeHeaders(t *testing.T) { }) } } + +type mockAuthInfo struct { + claims.AuthInfo +} + +func (main mockAuthInfo) GetExtra() map[string][]string { + return nil +} diff --git a/pkg/registry/apis/service/register.go b/pkg/registry/apis/service/register.go index 7f51ad844e0..db909b08777 100644 --- a/pkg/registry/apis/service/register.go +++ b/pkg/registry/apis/service/register.go @@ -12,6 +12,7 @@ import ( service "github.com/grafana/grafana/pkg/apis/service/v0alpha1" grafanaregistry "github.com/grafana/grafana/pkg/apiserver/registry/generic" + roleauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/apiserver/builder" "github.com/grafana/grafana/pkg/services/featuremgmt" ) @@ -37,7 +38,8 @@ func RegisterAPIService(features featuremgmt.FeatureToggles, apiregistration bui } func (b *ServiceAPIBuilder) GetAuthorizer() authorizer.Authorizer { - return nil // default authorizer is fine + //nolint:staticcheck // not yet migrated to Resource Authorizer + return roleauthorizer.NewRoleAuthorizer() } func (b *ServiceAPIBuilder) GetGroupVersion() schema.GroupVersion { diff --git a/pkg/registry/apis/wireset.go b/pkg/registry/apis/wireset.go index 12153f812a1..df38965759b 100644 --- a/pkg/registry/apis/wireset.go +++ b/pkg/registry/apis/wireset.go @@ -3,6 +3,7 @@ package apiregistry import ( "github.com/google/wire" + "github.com/grafana/grafana/pkg/apiserver/auditing" "github.com/grafana/grafana/pkg/registry/apis/collections" dashboardinternal "github.com/grafana/grafana/pkg/registry/apis/dashboard" "github.com/grafana/grafana/pkg/registry/apis/datasource" @@ -33,6 +34,10 @@ var WireSetExts = wire.NewSet( externalgroupmapping.ProvideNoopTeamGroupsREST, wire.Bind(new(externalgroupmapping.TeamGroupsHandler), new(*externalgroupmapping.NoopTeamGroupsREST)), + + // Auditing Options + auditing.ProvideNoopBackend, + auditing.ProvideNoopPolicyRuleProvider, ) var provisioningExtras = wire.NewSet( diff --git a/pkg/registry/apps/advisor/accesscontrol.go b/pkg/registry/apps/advisor/accesscontrol.go new file mode 100644 index 00000000000..2b59e55aa4e --- /dev/null +++ b/pkg/registry/apps/advisor/accesscontrol.go @@ -0,0 +1,150 @@ +package advisor + +import ( + "github.com/grafana/grafana/pkg/services/accesscontrol" + "github.com/grafana/grafana/pkg/services/org" +) + +const ( + // Check + ActionAdvisorCheckCreate = "advisor.checks:create" // CREATE. + ActionAdvisorCheckWrite = "advisor.checks:write" // UPDATE. + ActionAdvisorCheckRead = "advisor.checks:read" // GET + LIST. + ActionAdvisorCheckDelete = "advisor.checks:delete" // DELETE. + + // CheckTypes + ActionAdvisorCheckTypesCreate = "advisor.checktypes:create" // CREATE. + ActionAdvisorCheckTypesWrite = "advisor.checktypes:write" // UPDATE. + ActionAdvisorCheckTypesRead = "advisor.checktypes:read" // GET + LIST. + ActionAdvisorCheckTypesDelete = "advisor.checktypes:delete" // DELETE. + + // Register + ActionAdvisorRegisterCreate = "advisor.register:create" // CREATE (register check types). +) + +var ( + ScopeProviderAdvisorCheck = accesscontrol.NewScopeProvider("advisor.checks") + ScopeProviderAdvisorCheckTypes = accesscontrol.NewScopeProvider("advisor.checktypes") + ScopeProviderAdvisorRegister = accesscontrol.NewScopeProvider("advisor.register") + + ScopeAllAdvisorCheck = ScopeProviderAdvisorCheck.GetResourceAllScope() + ScopeAllAdvisorCheckTypes = ScopeProviderAdvisorCheckTypes.GetResourceAllScope() + ScopeAllAdvisorRegister = ScopeProviderAdvisorRegister.GetResourceAllScope() +) + +func registerAccessControlRoles(service accesscontrol.Service) error { + // Check + checkReader := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:advisor.checks:reader", + DisplayName: "Advisor Check Reader", + Description: "Read and list advisor checks.", + Group: "Advisor", + Permissions: []accesscontrol.Permission{ + { + Action: ActionAdvisorCheckRead, + Scope: ScopeAllAdvisorCheck, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + checkWriter := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:advisor.checks:writer", + DisplayName: "Advisor Check Writer", + Description: "Create, update and delete advisor checks.", + Group: "Advisor", + Permissions: []accesscontrol.Permission{ + { + Action: ActionAdvisorCheckCreate, + Scope: ScopeAllAdvisorCheck, + }, + { + Action: ActionAdvisorCheckRead, + Scope: ScopeAllAdvisorCheck, + }, + { + Action: ActionAdvisorCheckWrite, + Scope: ScopeAllAdvisorCheck, + }, + { + Action: ActionAdvisorCheckDelete, + Scope: ScopeAllAdvisorCheck, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + // CheckTypes + checkTypesReader := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:advisor.checktypes:reader", + DisplayName: "Advisor Check Types Reader", + Description: "Read and list advisor check types.", + Group: "Advisor", + Permissions: []accesscontrol.Permission{ + { + Action: ActionAdvisorCheckTypesRead, + Scope: ScopeAllAdvisorCheckTypes, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + checkTypesWriter := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:advisor.checktypes:writer", + DisplayName: "Advisor Check Types Writer", + Description: "Create, update and delete advisor check types.", + Group: "Advisor", + Permissions: []accesscontrol.Permission{ + { + Action: ActionAdvisorCheckTypesCreate, + Scope: ScopeAllAdvisorCheckTypes, + }, + { + Action: ActionAdvisorCheckTypesRead, + Scope: ScopeAllAdvisorCheckTypes, + }, + { + Action: ActionAdvisorCheckTypesWrite, + Scope: ScopeAllAdvisorCheckTypes, + }, + { + Action: ActionAdvisorCheckTypesDelete, + Scope: ScopeAllAdvisorCheckTypes, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + // Register + registerWriter := accesscontrol.RoleRegistration{ + Role: accesscontrol.RoleDTO{ + Name: "fixed:advisor.register:writer", + DisplayName: "Advisor Register Writer", + Description: "Register default advisor check types.", + Group: "Advisor", + Permissions: []accesscontrol.Permission{ + { + Action: ActionAdvisorRegisterCreate, + Scope: ScopeAllAdvisorRegister, + }, + }, + }, + Grants: []string{string(org.RoleAdmin)}, + } + + return service.DeclareFixedRoles( + checkReader, + checkWriter, + checkTypesReader, + checkTypesWriter, + registerWriter, + ) +} diff --git a/pkg/registry/apps/advisor/register.go b/pkg/registry/apps/advisor/register.go index 2cafb630803..31ad7d7e7d5 100644 --- a/pkg/registry/apps/advisor/register.go +++ b/pkg/registry/apps/advisor/register.go @@ -1,17 +1,17 @@ package advisor import ( - "github.com/grafana/grafana-app-sdk/app" + "fmt" + + authlib "github.com/grafana/authlib/types" appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" - "github.com/grafana/grafana-app-sdk/simple" - advisorapi "github.com/grafana/grafana/apps/advisor/pkg/apis" advisorapp "github.com/grafana/grafana/apps/advisor/pkg/app" "github.com/grafana/grafana/apps/advisor/pkg/app/checkregistry" + "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/apiserver/appinstaller" + grafanaauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/setting" - "k8s.io/apiserver/pkg/authorization/authorizer" - "k8s.io/client-go/rest" ) var ( @@ -20,37 +20,26 @@ var ( ) type AdvisorAppInstaller struct { - appsdkapiserver.AppInstaller -} - -// GetAuthorizer returns the authorizer for the plugins app. -func (a *AdvisorAppInstaller) GetAuthorizer() authorizer.Authorizer { - return advisorapp.GetAuthorizer() + *advisorapp.AdvisorAppInstaller } func ProvideAppInstaller( + accessControlService accesscontrol.Service, + accessClient authlib.AccessClient, checkRegistry checkregistry.CheckService, cfg *setting.Cfg, orgService org.Service, ) (*AdvisorAppInstaller, error) { - provider := simple.NewAppProvider(advisorapi.LocalManifest(), nil, advisorapp.New) - pluginConfig := cfg.PluginSettings["grafana-advisor-app"] - specificConfig := checkregistry.AdvisorAppConfig{ - CheckRegistry: checkRegistry, - PluginConfig: pluginConfig, - StackID: cfg.StackID, - OrgService: orgService, + if err := registerAccessControlRoles(accessControlService); err != nil { + return nil, fmt.Errorf("registering access control roles: %w", err) } - appCfg := app.Config{ - KubeConfig: rest.Config{}, - ManifestData: *advisorapi.LocalManifest().ManifestData, - SpecificConfig: specificConfig, - } - installer := &AdvisorAppInstaller{} - i, err := appsdkapiserver.NewDefaultAppInstaller(provider, appCfg, advisorapi.NewGoTypeAssociator()) + + authorizer := grafanaauthorizer.NewResourceAuthorizer(accessClient) + i, err := advisorapp.ProvideAppInstaller(authorizer, checkRegistry, cfg, orgService) if err != nil { return nil, err } - installer.AppInstaller = i - return installer, nil + return &AdvisorAppInstaller{ + AdvisorAppInstaller: i, + }, nil } diff --git a/pkg/registry/apps/alerting/historian/register.go b/pkg/registry/apps/alerting/historian/register.go index 68830dcd0ef..725cb2fae8d 100644 --- a/pkg/registry/apps/alerting/historian/register.go +++ b/pkg/registry/apps/alerting/historian/register.go @@ -1,9 +1,12 @@ package historian import ( + "context" + "github.com/grafana/grafana-app-sdk/app" appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" "github.com/grafana/grafana-app-sdk/simple" + "k8s.io/apiserver/pkg/authorization/authorizer" restclient "k8s.io/client-go/rest" "github.com/grafana/grafana/apps/alerting/historian/pkg/apis" @@ -23,6 +26,14 @@ type AlertingHistorianAppInstaller struct { appsdkapiserver.AppInstaller } +func (a *AlertingHistorianAppInstaller) GetAuthorizer() authorizer.Authorizer { + return authorizer.AuthorizerFunc( + func(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) { + return authorizer.DecisionAllow, "", nil + }, + ) +} + func RegisterAppInstaller( cfg *setting.Cfg, ng *ngalert.AlertNG, diff --git a/pkg/registry/apps/alerting/notifications/receiver/conversions.go b/pkg/registry/apps/alerting/notifications/receiver/conversions.go index b0d79121912..993c63a46fd 100644 --- a/pkg/registry/apps/alerting/notifications/receiver/conversions.go +++ b/pkg/registry/apps/alerting/notifications/receiver/conversions.go @@ -110,10 +110,11 @@ func convertToK8sResource( } var permissionMapper = map[ngmodels.ReceiverPermission]string{ - ngmodels.ReceiverPermissionReadSecret: "canReadSecrets", - ngmodels.ReceiverPermissionAdmin: "canAdmin", - ngmodels.ReceiverPermissionWrite: "canWrite", - ngmodels.ReceiverPermissionDelete: "canDelete", + ngmodels.ReceiverPermissionReadSecret: "canReadSecrets", + ngmodels.ReceiverPermissionAdmin: "canAdmin", + ngmodels.ReceiverPermissionWrite: "canWrite", + ngmodels.ReceiverPermissionDelete: "canDelete", + ngmodels.ReceiverPermissionModifyProtected: "canModifyProtected", } func convertToDomainModel(receiver *model.Receiver) (*ngmodels.Receiver, map[string][]string, error) { diff --git a/pkg/registry/apps/correlations/register.go b/pkg/registry/apps/correlations/register.go index 757af68a8ce..2a3b1f0bde5 100644 --- a/pkg/registry/apps/correlations/register.go +++ b/pkg/registry/apps/correlations/register.go @@ -5,6 +5,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/authorization/authorizer" restclient "k8s.io/client-go/rest" "github.com/grafana/grafana-app-sdk/app" @@ -16,6 +17,7 @@ import ( "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/apiserver/rest" "github.com/grafana/grafana/pkg/services/apiserver/appinstaller" + roleauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/apiserver/endpoints/request" "github.com/grafana/grafana/pkg/services/correlations" "github.com/grafana/grafana/pkg/services/featuremgmt" @@ -60,6 +62,11 @@ func RegisterAppInstaller( return installer, nil } +func (a *AppInstaller) GetAuthorizer() authorizer.Authorizer { + //nolint:staticcheck // not yet migrated to Resource Authorizer + return roleauthorizer.NewRoleAuthorizer() +} + func (a *AppInstaller) GetLegacyStorage(requested schema.GroupVersionResource) rest.Storage { kind := correlationsV0.CorrelationKind() gvr := schema.GroupVersionResource{ diff --git a/pkg/registry/apps/playlist/register.go b/pkg/registry/apps/playlist/register.go index 52bbc0210f9..336270098e4 100644 --- a/pkg/registry/apps/playlist/register.go +++ b/pkg/registry/apps/playlist/register.go @@ -6,17 +6,20 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/authorization/authorizer" restclient "k8s.io/client-go/rest" "github.com/grafana/grafana-app-sdk/app" appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" "github.com/grafana/grafana-app-sdk/simple" + "github.com/grafana/grafana/apps/playlist/pkg/apis" playlistv0alpha1 "github.com/grafana/grafana/apps/playlist/pkg/apis/playlist/v0alpha1" playlistapp "github.com/grafana/grafana/apps/playlist/pkg/app" "github.com/grafana/grafana/pkg/apimachinery/utils" grafanarest "github.com/grafana/grafana/pkg/apiserver/rest" "github.com/grafana/grafana/pkg/services/apiserver/appinstaller" + roleauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/apiserver/endpoints/request" "github.com/grafana/grafana/pkg/services/featuremgmt" playlistsvc "github.com/grafana/grafana/pkg/services/playlist" @@ -63,6 +66,11 @@ func RegisterAppInstaller( return installer, nil } +func (p *PlaylistAppInstaller) GetAuthorizer() authorizer.Authorizer { + //nolint:staticcheck // not yet migrated to Resource Authorizer + return roleauthorizer.NewRoleAuthorizer() +} + // GetLegacyStorage returns the legacy storage for the playlist app. func (p *PlaylistAppInstaller) GetLegacyStorage(requested schema.GroupVersionResource) grafanarest.Storage { gvr := playlistv0alpha1.PlaylistKind().GroupVersionResource() diff --git a/pkg/registry/apps/plugins/accesscontrol.go b/pkg/registry/apps/plugins/accesscontrol.go index d41efa86f97..e0a8c9b6c23 100644 --- a/pkg/registry/apps/plugins/accesscontrol.go +++ b/pkg/registry/apps/plugins/accesscontrol.go @@ -13,15 +13,15 @@ const ( ActionPluginsPluginsDelete = "plugins.plugins:delete" // DELETE. // PluginMetas - ActionPluginsPluginsMetaCreate = "plugins.pluginsmeta:create" // CREATE. - ActionPluginsPluginsMetaWrite = "plugins.pluginsmeta:write" // UPDATE. - ActionPluginsPluginsMetaRead = "plugins.pluginsmeta:read" // GET + LIST. - ActionPluginsPluginsMetaDelete = "plugins.pluginsmeta:delete" // DELETE. + ActionPluginsPluginsMetaCreate = "plugins.metas:create" // CREATE. + ActionPluginsPluginsMetaWrite = "plugins.metas:write" // UPDATE. + ActionPluginsPluginsMetaRead = "plugins.metas:read" // GET + LIST. + ActionPluginsPluginsMetaDelete = "plugins.metas:delete" // DELETE. ) var ( ScopeProviderPluginsPlugins = accesscontrol.NewScopeProvider("plugins.plugins") - ScopeProviderPluginsPluginsMeta = accesscontrol.NewScopeProvider("plugins.pluginsmeta") + ScopeProviderPluginsPluginsMeta = accesscontrol.NewScopeProvider("plugins.metas") ScopeAllPluginsPlugins = ScopeProviderPluginsPlugins.GetResourceAllScope() ScopeAllPluginsPluginsMeta = ScopeProviderPluginsPluginsMeta.GetResourceAllScope() @@ -76,7 +76,7 @@ func registerAccessControlRoles(service accesscontrol.Service) error { // PluginMetas pluginsMetaReader := accesscontrol.RoleRegistration{ Role: accesscontrol.RoleDTO{ - Name: "fixed:plugins.pluginsmeta:reader", + Name: "fixed:plugins.metas:reader", DisplayName: "Plugin Metas Reader", Description: "Read and list plugin metadata.", Group: "Plugins", @@ -92,7 +92,7 @@ func registerAccessControlRoles(service accesscontrol.Service) error { pluginsMetaWriter := accesscontrol.RoleRegistration{ Role: accesscontrol.RoleDTO{ - Name: "fixed:plugins.pluginsmeta:writer", + Name: "fixed:plugins.metas:writer", DisplayName: "Plugin Metas Writer", Description: "Create, update and delete plugin metadata.", Group: "Plugins", diff --git a/pkg/registry/apps/plugins/register.go b/pkg/registry/apps/plugins/register.go index 6831d31ef9b..9113d927a29 100644 --- a/pkg/registry/apps/plugins/register.go +++ b/pkg/registry/apps/plugins/register.go @@ -6,12 +6,12 @@ import ( authlib "github.com/grafana/authlib/types" appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" - "k8s.io/apiserver/pkg/authorization/authorizer" pluginsapp "github.com/grafana/grafana/apps/plugins/pkg/app" "github.com/grafana/grafana/apps/plugins/pkg/app/meta" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/apiserver/appinstaller" + grafanaauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" ) var ( @@ -34,21 +34,16 @@ func ProvideAppInstaller(accessControlService accesscontrol.Service, accessClien } coreProvider := meta.NewCoreProvider() - cloudProvider := meta.NewCloudProvider(grafanaComAPIURL) + cloudProvider := meta.NewCatalogProvider(grafanaComAPIURL) metaProviderManager := meta.NewProviderManager(coreProvider, cloudProvider) - i, err := pluginsapp.ProvideAppInstaller(metaProviderManager) + authorizer := grafanaauthorizer.NewResourceAuthorizer(accessClient) + i, err := pluginsapp.ProvideAppInstaller(authorizer, metaProviderManager) if err != nil { return nil, err } - i.WithAccessChecker(accessClient) - return &AppInstaller{ PluginAppInstaller: i, }, nil } - -func (a *AppInstaller) GetAuthorizer() authorizer.Authorizer { - return pluginsapp.GetAuthorizer() -} diff --git a/pkg/registry/apps/quotas/register.go b/pkg/registry/apps/quotas/register.go index b81d4fef5cf..c6b33bc4d00 100644 --- a/pkg/registry/apps/quotas/register.go +++ b/pkg/registry/apps/quotas/register.go @@ -3,12 +3,14 @@ package quotas import ( "github.com/grafana/grafana/apps/quotas/pkg/apis" "github.com/grafana/grafana/pkg/storage/unified/resource" + "k8s.io/apiserver/pkg/authorization/authorizer" restclient "k8s.io/client-go/rest" "github.com/grafana/grafana-app-sdk/app" appsdkapiserver "github.com/grafana/grafana-app-sdk/k8s/apiserver" "github.com/grafana/grafana-app-sdk/simple" quotasapp "github.com/grafana/grafana/apps/quotas/pkg/app" + roleauthorizer "github.com/grafana/grafana/pkg/services/apiserver/auth/authorizer" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/setting" ) @@ -22,6 +24,11 @@ type QuotasAppInstaller struct { cfg *setting.Cfg } +func (a *QuotasAppInstaller) GetAuthorizer() authorizer.Authorizer { + //nolint:staticcheck // not yet migrated to Resource Authorizer + return roleauthorizer.NewRoleAuthorizer() +} + func RegisterAppInstaller( cfg *setting.Cfg, features featuremgmt.FeatureToggles, diff --git a/pkg/registry/backgroundsvcs/adapter/service_test.go b/pkg/registry/backgroundsvcs/adapter/service_test.go index ed357d66443..275068967c0 100644 --- a/pkg/registry/backgroundsvcs/adapter/service_test.go +++ b/pkg/registry/backgroundsvcs/adapter/service_test.go @@ -55,15 +55,9 @@ func TestServiceAdapter_ErrorHandling(t *testing.T) { adapter := asNamedService(mockSvc) - t.Cleanup(func() { - adapter.StopAsync() - err := adapter.AwaitTerminated(context.Background()) - require.ErrorIs(t, err, expectedErr) - }) - err := adapter.StartAsync(context.Background()) require.NoError(t, err) - err = adapter.AwaitRunning(context.Background()) + err = adapter.AwaitTerminated(context.Background()) require.ErrorIs(t, err, expectedErr) require.True(t, mockSvc.runCalled) }) @@ -95,14 +89,9 @@ func TestServiceAdapter_ErrorHandling(t *testing.T) { adapter := asNamedService(mockSvc) - t.Cleanup(func() { - adapter.StopAsync() - err := adapter.AwaitTerminated(context.Background()) - require.ErrorIs(t, err, expectedErr) - }) err := adapter.StartAsync(context.Background()) require.NoError(t, err) - err = adapter.AwaitRunning(context.Background()) + err = adapter.AwaitTerminated(context.Background()) require.ErrorIs(t, err, expectedErr) require.True(t, mockSvc.runCalled) }) diff --git a/pkg/server/wire.go b/pkg/server/wire.go index 0d4bb10c0b5..9864bed4e12 100644 --- a/pkg/server/wire.go +++ b/pkg/server/wire.go @@ -280,6 +280,7 @@ var wireBasicSet = wire.NewSet( store.ProvideService, store.ProvideSystemUsersService, live.ProvideService, + live.ProvideDashboardActivityChannel, pushhttp.ProvideService, contexthandler.ProvideService, ldapservice.ProvideService, @@ -348,6 +349,7 @@ var wireBasicSet = wire.NewSet( dashboardservice.ProvideDashboardService, dashboardservice.ProvideDashboardProvisioningService, dashboardservice.ProvideDashboardPluginService, + dashboardservice.ProvideDashboardAccessService, dashboardstore.ProvideDashboardStore, folderimpl.ProvideService, wire.Bind(new(folder.Service), new(*folderimpl.Service)), diff --git a/pkg/server/wire_gen.go b/pkg/server/wire_gen.go index 8500130aeea..5ed04adf12b 100644 --- a/pkg/server/wire_gen.go +++ b/pkg/server/wire_gen.go @@ -14,6 +14,7 @@ import ( "github.com/grafana/grafana/pkg/api" "github.com/grafana/grafana/pkg/api/avatar" "github.com/grafana/grafana/pkg/api/routing" + "github.com/grafana/grafana/pkg/apiserver/auditing" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/configprovider" "github.com/grafana/grafana/pkg/expr" @@ -672,10 +673,8 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api starService := starimpl.ProvideService(sqlStore) searchSearchService := search2.ProvideService(cfg, sqlStore, starService, dashboardService, folderimplService, featureToggles, sortService) plugincontextProvider := plugincontext.ProvideService(cfg, cacheService, pluginstoreService, cacheServiceImpl, service15, service13, requestConfigProvider) - qsDatasourceClientBuilder := dsquerierclient.NewNullQSDatasourceClientBuilder() - exprService := expr.ProvideService(cfg, middlewareHandler, plugincontextProvider, featureToggles, registerer, tracingService, qsDatasourceClientBuilder) - queryServiceImpl := query.ProvideService(cfg, cacheServiceImpl, exprService, ossDataSourceRequestValidator, middlewareHandler, plugincontextProvider, qsDatasourceClientBuilder) - grafanaLive, err := live.ProvideService(plugincontextProvider, cfg, routeRegisterImpl, pluginstoreService, middlewareHandler, cacheService, cacheServiceImpl, sqlStore, secretsService, usageStats, queryServiceImpl, featureToggles, accessControl, dashboardService, orgService, eventualRestConfigProvider) + dashboardAccessService := service7.ProvideDashboardAccessService(featureToggles, dashboardServiceImpl) + grafanaLive, err := live.ProvideService(cfg, routeRegisterImpl, plugincontextProvider, pluginstoreService, middlewareHandler, cacheServiceImpl, usageStats, featureToggles, dashboardAccessService, eventualRestConfigProvider) if err != nil { return nil, err } @@ -684,6 +683,8 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api authnAuthenticator := authnimpl.ProvideAuthnServiceAuthenticateOnly(authnimplService) contexthandlerContextHandler := contexthandler.ProvideService(cfg, authnAuthenticator, featureToggles) logger := loggermw.Provide(cfg, featureToggles) + qsDatasourceClientBuilder := dsquerierclient.NewNullQSDatasourceClientBuilder() + exprService := expr.ProvideService(cfg, middlewareHandler, plugincontextProvider, featureToggles, registerer, tracingService, qsDatasourceClientBuilder) ngAlert := metrics2.ProvideService() repositoryImpl := annotationsimpl.ProvideService(sqlStore, cfg, featureToggles, tagimplService, tracingService, dBstore, dashboardService, registerer) alertNG, err := ngalert.ProvideService(cfg, featureToggles, cacheServiceImpl, service15, routeRegisterImpl, sqlStore, kvStore, exprService, dataSourceProxyService, quotaService, secretsService, notificationService, ngAlert, folderimplService, accessControl, dashboardService, renderingService, inProcBus, acimplService, repositoryImpl, pluginstoreService, tracingService, dBstore, httpclientProvider, plugincontextProvider, receiverPermissionsService, userService) @@ -708,6 +709,7 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api } ossSearchUserFilter := filters.ProvideOSSSearchUserFilter() ossService := searchusers.ProvideUsersService(cfg, ossSearchUserFilter, userService) + queryServiceImpl := query.ProvideService(cfg, cacheServiceImpl, exprService, ossDataSourceRequestValidator, middlewareHandler, plugincontextProvider, qsDatasourceClientBuilder) serviceAccountsProxy, err := proxy.ProvideServiceAccountsProxy(cfg, accessControl, acimplService, featureToggles, serviceAccountPermissionsService, serviceAccountsService, routeRegisterImpl) if err != nil { return nil, err @@ -817,7 +819,7 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api return nil, err } checkregistryService := checkregistry.ProvideService(service15, pluginstoreService, plugincontextProvider, middlewareHandler, plugincheckerService, repoManager, preinstallImpl, managedpluginsNoop, noop, ssosettingsimplService, cfg, pluginerrsStore) - advisorAppInstaller, err := advisor2.ProvideAppInstaller(checkregistryService, cfg, orgService) + advisorAppInstaller, err := advisor2.ProvideAppInstaller(acimplService, accessClient, checkregistryService, cfg, orgService) if err != nil { return nil, err } @@ -831,7 +833,9 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api } v2 := appregistry.ProvideAppInstallers(featureToggles, playlistAppInstaller, appInstaller, shortURLAppInstaller, alertingRulesAppInstaller, correlationsAppInstaller, alertingNotificationsAppInstaller, logsDrilldownAppInstaller, annotationAppInstaller, exampleAppInstaller, advisorAppInstaller, alertingHistorianAppInstaller, quotasAppInstaller) builderMetrics := builder.ProvideBuilderMetrics(registerer) - apiserverService, err := apiserver.ProvideService(cfg, featureToggles, routeRegisterImpl, tracingService, serverLockService, sqlStore, kvStore, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, pluginstoreService, dualwriteService, resourceClient, inlineSecureValueSupport, eventualRestConfigProvider, v, eventualRestConfigProvider, registerer, aggregatorRunner, v2, builderMetrics) + backend := auditing.ProvideNoopBackend() + policyRuleProvider := auditing.ProvideNoopPolicyRuleProvider() + apiserverService, err := apiserver.ProvideService(cfg, featureToggles, routeRegisterImpl, tracingService, serverLockService, sqlStore, kvStore, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, pluginstoreService, dualwriteService, resourceClient, inlineSecureValueSupport, eventualRestConfigProvider, v, eventualRestConfigProvider, registerer, aggregatorRunner, v2, builderMetrics, backend, policyRuleProvider) if err != nil { return nil, err } @@ -870,7 +874,8 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api identitySynchronizer := authnimpl.ProvideIdentitySynchronizer(authnimplService) ldapImpl := service12.ProvideService(cfg, featureToggles, ssosettingsimplService) apiService := api4.ProvideService(cfg, routeRegisterImpl, accessControl, userService, authinfoimplService, ossGroups, identitySynchronizer, orgService, ldapImpl, userAuthTokenService, bundleregistryService) - dashboardsAPIBuilder := dashboard.RegisterAPIService(cfg, featureToggles, apiserverService, dashboardService, dashboardProvisioningService, service15, dashboardServiceImpl, dashboardPermissionsService, accessControl, accessClient, provisioningServiceImpl, dashboardsStore, registerer, sqlStore, tracingService, resourceClient, dualwriteService, sortService, quotaService, libraryPanelService, eventualRestConfigProvider, userService, libraryElementService, publicDashboardServiceImpl, serviceImpl) + dashboardActivityChannel := live.ProvideDashboardActivityChannel(grafanaLive) + dashboardsAPIBuilder := dashboard.RegisterAPIService(cfg, featureToggles, apiserverService, dashboardService, dashboardProvisioningService, service15, dashboardServiceImpl, dashboardPermissionsService, accessControl, accessClient, provisioningServiceImpl, dashboardsStore, registerer, sqlStore, tracingService, resourceClient, dualwriteService, sortService, quotaService, libraryPanelService, eventualRestConfigProvider, userService, libraryElementService, publicDashboardServiceImpl, serviceImpl, dashboardActivityChannel) dataSourceAPIBuilder, err := datasource.RegisterAPIService(featureToggles, apiserverService, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, accessControl, registerer, sourcesService) if err != nil { return nil, err @@ -878,7 +883,7 @@ func Initialize(ctx context.Context, cfg *setting.Cfg, opts Options, apiOpts api folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient) storageBackendImpl := noopstorage.ProvideStorageBackend() noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST() - identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, storageBackendImpl, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, userService, teamService) + identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, storageBackendImpl, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider) if err != nil { return nil, err } @@ -1328,10 +1333,8 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac starService := starimpl.ProvideService(sqlStore) searchSearchService := search2.ProvideService(cfg, sqlStore, starService, dashboardService, folderimplService, featureToggles, sortService) plugincontextProvider := plugincontext.ProvideService(cfg, cacheService, pluginstoreService, cacheServiceImpl, service15, service13, requestConfigProvider) - qsDatasourceClientBuilder := dsquerierclient.NewNullQSDatasourceClientBuilder() - exprService := expr.ProvideService(cfg, middlewareHandler, plugincontextProvider, featureToggles, registerer, tracingService, qsDatasourceClientBuilder) - queryServiceImpl := query.ProvideService(cfg, cacheServiceImpl, exprService, ossDataSourceRequestValidator, middlewareHandler, plugincontextProvider, qsDatasourceClientBuilder) - grafanaLive, err := live.ProvideService(plugincontextProvider, cfg, routeRegisterImpl, pluginstoreService, middlewareHandler, cacheService, cacheServiceImpl, sqlStore, secretsService, usageStats, queryServiceImpl, featureToggles, accessControl, dashboardService, orgService, eventualRestConfigProvider) + dashboardAccessService := service7.ProvideDashboardAccessService(featureToggles, dashboardServiceImpl) + grafanaLive, err := live.ProvideService(cfg, routeRegisterImpl, plugincontextProvider, pluginstoreService, middlewareHandler, cacheServiceImpl, usageStats, featureToggles, dashboardAccessService, eventualRestConfigProvider) if err != nil { return nil, err } @@ -1340,6 +1343,8 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac authnAuthenticator := authnimpl.ProvideAuthnServiceAuthenticateOnly(authnimplService) contexthandlerContextHandler := contexthandler.ProvideService(cfg, authnAuthenticator, featureToggles) logger := loggermw.Provide(cfg, featureToggles) + qsDatasourceClientBuilder := dsquerierclient.NewNullQSDatasourceClientBuilder() + exprService := expr.ProvideService(cfg, middlewareHandler, plugincontextProvider, featureToggles, registerer, tracingService, qsDatasourceClientBuilder) notificationServiceMock := notifications.MockNotificationService() ngAlert := metrics2.ProvideServiceForTest() repositoryImpl := annotationsimpl.ProvideService(sqlStore, cfg, featureToggles, tagimplService, tracingService, dBstore, dashboardService, registerer) @@ -1365,6 +1370,7 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac } ossSearchUserFilter := filters.ProvideOSSSearchUserFilter() ossService := searchusers.ProvideUsersService(cfg, ossSearchUserFilter, userService) + queryServiceImpl := query.ProvideService(cfg, cacheServiceImpl, exprService, ossDataSourceRequestValidator, middlewareHandler, plugincontextProvider, qsDatasourceClientBuilder) serviceAccountsProxy, err := proxy.ProvideServiceAccountsProxy(cfg, accessControl, acimplService, featureToggles, serviceAccountPermissionsService, serviceAccountsService, routeRegisterImpl) if err != nil { return nil, err @@ -1474,7 +1480,7 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac return nil, err } checkregistryService := checkregistry.ProvideService(service15, pluginstoreService, plugincontextProvider, middlewareHandler, plugincheckerService, repoManager, preinstallImpl, managedpluginsNoop, noop, ssosettingsimplService, cfg, pluginerrsStore) - advisorAppInstaller, err := advisor2.ProvideAppInstaller(checkregistryService, cfg, orgService) + advisorAppInstaller, err := advisor2.ProvideAppInstaller(acimplService, accessClient, checkregistryService, cfg, orgService) if err != nil { return nil, err } @@ -1488,7 +1494,9 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac } v2 := appregistry.ProvideAppInstallers(featureToggles, playlistAppInstaller, appInstaller, shortURLAppInstaller, alertingRulesAppInstaller, correlationsAppInstaller, alertingNotificationsAppInstaller, logsDrilldownAppInstaller, annotationAppInstaller, exampleAppInstaller, advisorAppInstaller, alertingHistorianAppInstaller, quotasAppInstaller) builderMetrics := builder.ProvideBuilderMetrics(registerer) - apiserverService, err := apiserver.ProvideService(cfg, featureToggles, routeRegisterImpl, tracingService, serverLockService, sqlStore, kvStore, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, pluginstoreService, dualwriteService, resourceClient, inlineSecureValueSupport, eventualRestConfigProvider, v, eventualRestConfigProvider, registerer, aggregatorRunner, v2, builderMetrics) + backend := auditing.ProvideNoopBackend() + policyRuleProvider := auditing.ProvideNoopPolicyRuleProvider() + apiserverService, err := apiserver.ProvideService(cfg, featureToggles, routeRegisterImpl, tracingService, serverLockService, sqlStore, kvStore, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, pluginstoreService, dualwriteService, resourceClient, inlineSecureValueSupport, eventualRestConfigProvider, v, eventualRestConfigProvider, registerer, aggregatorRunner, v2, builderMetrics, backend, policyRuleProvider) if err != nil { return nil, err } @@ -1527,7 +1535,8 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac identitySynchronizer := authnimpl.ProvideIdentitySynchronizer(authnimplService) ldapImpl := service12.ProvideService(cfg, featureToggles, ssosettingsimplService) apiService := api4.ProvideService(cfg, routeRegisterImpl, accessControl, userService, authinfoimplService, ossGroups, identitySynchronizer, orgService, ldapImpl, userAuthTokenService, bundleregistryService) - dashboardsAPIBuilder := dashboard.RegisterAPIService(cfg, featureToggles, apiserverService, dashboardService, dashboardProvisioningService, service15, dashboardServiceImpl, dashboardPermissionsService, accessControl, accessClient, provisioningServiceImpl, dashboardsStore, registerer, sqlStore, tracingService, resourceClient, dualwriteService, sortService, quotaService, libraryPanelService, eventualRestConfigProvider, userService, libraryElementService, publicDashboardServiceImpl, serviceImpl) + dashboardActivityChannel := live.ProvideDashboardActivityChannel(grafanaLive) + dashboardsAPIBuilder := dashboard.RegisterAPIService(cfg, featureToggles, apiserverService, dashboardService, dashboardProvisioningService, service15, dashboardServiceImpl, dashboardPermissionsService, accessControl, accessClient, provisioningServiceImpl, dashboardsStore, registerer, sqlStore, tracingService, resourceClient, dualwriteService, sortService, quotaService, libraryPanelService, eventualRestConfigProvider, userService, libraryElementService, publicDashboardServiceImpl, serviceImpl, dashboardActivityChannel) dataSourceAPIBuilder, err := datasource.RegisterAPIService(featureToggles, apiserverService, middlewareHandler, scopedPluginDatasourceProvider, plugincontextProvider, accessControl, registerer, sourcesService) if err != nil { return nil, err @@ -1535,7 +1544,7 @@ func InitializeForTest(ctx context.Context, t sqlutil.ITestDB, testingT interfac folderAPIBuilder := folders.RegisterAPIService(cfg, featureToggles, apiserverService, folderimplService, folderPermissionsService, accessControl, acimplService, accessClient, registerer, resourceClient, zanzanaClient) storageBackendImpl := noopstorage.ProvideStorageBackend() noopTeamGroupsREST := externalgroupmapping.ProvideNoopTeamGroupsREST() - identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, storageBackendImpl, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, userService, teamService) + identityAccessManagementAPIBuilder, err := iam.RegisterAPIService(cfg, featureToggles, apiserverService, ssosettingsimplService, sqlStore, accessControl, accessClient, zanzanaClient, registerer, storageBackendImpl, storageBackendImpl, tracingService, storageBackendImpl, storageBackendImpl, noopTeamGroupsREST, dualwriteService, resourceClient, orgService, userService, teamService, eventualRestConfigProvider) if err != nil { return nil, err } @@ -1791,7 +1800,7 @@ var withOTelSet = wire.NewSet( otelTracer, grpcserver.ProvideService, interceptors.ProvideAuthenticator, ) -var wireBasicSet = wire.NewSet(annotationsimpl.ProvideService, wire.Bind(new(annotations.Repository), new(*annotationsimpl.RepositoryImpl)), New, api.ProvideHTTPServer, query.ProvideService, wire.Bind(new(query.Service), new(*query.ServiceImpl)), bus.ProvideBus, wire.Bind(new(bus.Bus), new(*bus.InProcBus)), rendering.ProvideService, wire.Bind(new(rendering.Service), new(*rendering.RenderingService)), routing.ProvideRegister, wire.Bind(new(routing.RouteRegister), new(*routing.RouteRegisterImpl)), hooks.ProvideService, kvstore.ProvideService, localcache.ProvideService, bundleregistry.ProvideService, wire.Bind(new(supportbundles.Service), new(*bundleregistry.Service)), updatemanager.ProvideGrafanaService, updatemanager.ProvidePluginsService, service.ProvideService, wire.Bind(new(usagestats.Service), new(*service.UsageStats)), validator3.ProvideService, provisioning.ProvideStubProvisioningService, legacy.ProvideMigratorDashboardAccessor, migrations2.ProvideUnifiedMigrator, pluginsintegration.WireSet, dashboards.ProvideFileStoreManager, wire.Bind(new(dashboards.FileStore), new(*dashboards.FileStoreManager)), cloudwatch.ProvideService, cloudmonitoring.ProvideService, azuremonitor.ProvideService, postgres.ProvideService, mysql.ProvideService, mssql.ProvideService, store.ProvideEntityEventsService, dualwrite.ProvideService, httpclientprovider.New, wire.Bind(new(httpclient.Provider), new(*httpclient2.Provider)), serverlock.ProvideService, wire.Bind(new(installsync.ServerLock), new(*serverlock.ServerLockService)), annotationsimpl.ProvideCleanupService, wire.Bind(new(annotations.Cleaner), new(*annotationsimpl.CleanupServiceImpl)), cleanup.ProvideService, shorturlimpl.ProvideService, wire.Bind(new(shorturls.Service), new(*shorturlimpl.ShortURLService)), queryhistory.ProvideService, wire.Bind(new(queryhistory.Service), new(*queryhistory.QueryHistoryService)), correlations.ProvideService, wire.Bind(new(correlations.Service), new(*correlations.CorrelationsService)), quotaimpl.ProvideService, remotecache.ProvideService, wire.Bind(new(remotecache.CacheStorage), new(*remotecache.RemoteCache)), authinfoimpl.ProvideService, wire.Bind(new(login.AuthInfoService), new(*authinfoimpl.Service)), authinfoimpl.ProvideStore, datasourceproxy.ProvideService, sort.ProvideService, search2.ProvideService, searchV2.ProvideService, searchV2.ProvideSearchHTTPService, store.ProvideService, store.ProvideSystemUsersService, live.ProvideService, pushhttp.ProvideService, contexthandler.ProvideService, service12.ProvideService, wire.Bind(new(service12.LDAP), new(*service12.LDAPImpl)), jwt.ProvideService, wire.Bind(new(jwt.JWTService), new(*jwt.AuthService)), store2.ProvideDBStore, image.ProvideDeleteExpiredService, ngalert.ProvideService, librarypanels.ProvideService, wire.Bind(new(librarypanels.Service), new(*librarypanels.LibraryPanelService)), libraryelements.ProvideService, wire.Bind(new(libraryelements.Service), new(*libraryelements.LibraryElementService)), notifications.ProvideService, notifications.ProvideSmtpService, github.ProvideFactory, tracing.ProvideService, tracing.ProvideTracingConfig, wire.Bind(new(tracing.Tracer), new(*tracing.TracingService)), withOTelSet, testdatasource.ProvideService, api4.ProvideService, opentsdb.ProvideService, socialimpl.ProvideService, influxdb.ProvideService, wire.Bind(new(social.Service), new(*socialimpl.SocialService)), tempo.ProvideService, loki.ProvideService, graphite.ProvideService, prometheus.ProvideService, elasticsearch.ProvideService, pyroscope.ProvideService, parca.ProvideService, zipkin.ProvideService, jaeger.ProvideService, service9.ProvideCacheService, wire.Bind(new(datasources.CacheService), new(*service9.CacheServiceImpl)), service2.ProvideEncryptionService, wire.Bind(new(encryption2.Internal), new(*service2.Service)), manager.ProvideSecretsService, wire.Bind(new(secrets.Service), new(*manager.SecretsService)), database.ProvideSecretsStore, wire.Bind(new(secrets.Store), new(*database.SecretsStoreImpl)), garbagecollectionworker.ProvideWorker, grafanads.ProvideService, wire.Bind(new(dashboardsnapshots.Store), new(*database5.DashboardSnapshotStore)), database5.ProvideStore, wire.Bind(new(dashboardsnapshots.Service), new(*service10.ServiceImpl)), service10.ProvideService, service9.ProvideService, wire.Bind(new(datasources.DataSourceService), new(*service9.Service)), service9.ProvideLegacyDataSourceLookup, retriever.ProvideService, wire.Bind(new(serviceaccounts.ServiceAccountRetriever), new(*retriever.Service)), ossaccesscontrol.ProvideServiceAccountPermissions, wire.Bind(new(accesscontrol.ServiceAccountPermissionsService), new(*ossaccesscontrol.ServiceAccountPermissionsService)), manager3.ProvideServiceAccountsService, proxy.ProvideServiceAccountsProxy, wire.Bind(new(serviceaccounts.Service), new(*proxy.ServiceAccountsProxy)), dsquerierclient.NewNullQSDatasourceClientBuilder, expr.ProvideService, featuremgmt.ProvideManagerService, featuremgmt.ProvideToggles, service7.ProvideDashboardServiceImpl, wire.Bind(new(dashboards2.PermissionsRegistrationService), new(*service7.DashboardServiceImpl)), service7.ProvideDashboardService, service7.ProvideDashboardProvisioningService, service7.ProvideDashboardPluginService, database2.ProvideDashboardStore, folderimpl.ProvideService, wire.Bind(new(folder.Service), new(*folderimpl.Service)), wire.Bind(new(folder.LegacyService), new(*folderimpl.Service)), folderimpl.ProvideStore, wire.Bind(new(folder.Store), new(*folderimpl.FolderStoreImpl)), service11.ProvideService, wire.Bind(new(dashboardimport.Service), new(*service11.ImportDashboardService)), service8.ProvideService, wire.Bind(new(plugindashboards.Service), new(*service8.Service)), service8.ProvideDashboardUpdater, kvstore2.ProvideService, avatar.ProvideAvatarCacheServer, statscollector.ProvideService, csrf.ProvideCSRFFilter, wire.Bind(new(csrf.Service), new(*csrf.CSRF)), ossaccesscontrol.ProvideTeamPermissions, wire.Bind(new(accesscontrol.TeamPermissionsService), new(*ossaccesscontrol.TeamPermissionsService)), ossaccesscontrol.ProvideFolderPermissions, wire.Bind(new(accesscontrol.FolderPermissionsService), new(*ossaccesscontrol.FolderPermissionsService)), ossaccesscontrol.ProvideDashboardPermissions, wire.Bind(new(accesscontrol.DashboardPermissionsService), new(*ossaccesscontrol.DashboardPermissionsService)), ossaccesscontrol.ProvideReceiverPermissionsService, wire.Bind(new(accesscontrol.ReceiverPermissionsService), new(*ossaccesscontrol.ReceiverPermissionsService)), starimpl.ProvideService, playlistimpl.ProvideService, apikeyimpl.ProvideService, dashverimpl.ProvideService, service3.ProvideService, wire.Bind(new(publicdashboards.Service), new(*service3.PublicDashboardServiceImpl)), database3.ProvideStore, wire.Bind(new(publicdashboards.Store), new(*database3.PublicDashboardStoreImpl)), metric.ProvideService, api2.ProvideApi, api3.ProvideApi, userimpl.ProvideService, orgimpl.ProvideService, orgimpl.ProvideDeletionService, statsimpl.ProvideService, grpccontext.ProvideContextHandler, grpcserver.ProvideHealthService, grpcserver.ProvideReflectionService, resolver.ProvideEntityReferenceResolver, teamimpl.ProvideService, teamapi.ProvideTeamAPI, tempuserimpl.ProvideService, loginattemptimpl.ProvideService, wire.Bind(new(loginattempt.Service), new(*loginattemptimpl.Service)), migrations3.ProvideDataSourceMigrationService, migrations3.ProvideSecretMigrationProvider, wire.Bind(new(migrations3.SecretMigrationProvider), new(*migrations3.SecretMigrationProviderImpl)), promtypemigration.ProvideAzurePromMigrationService, promtypemigration.ProvideAmazonPromMigrationService, promtypemigration.ProvidePromTypeMigrationProvider, wire.Bind(new(promtypemigration.PromTypeMigrationProvider), new(*promtypemigration.PromTypeMigrationProviderImpl)), resourcepermissions.NewActionSetService, wire.Bind(new(accesscontrol.ActionResolver), new(resourcepermissions.ActionSetService)), wire.Bind(new(pluginaccesscontrol.ActionSetRegistry), new(resourcepermissions.ActionSetService)), permreg.ProvidePermissionRegistry, acimpl.ProvideAccessControl, accesscontrol.ProvideFixedRolesLoader, dualwrite2.ProvideZanzanaReconciler, navtreeimpl.ProvideService, wire.Bind(new(accesscontrol.AccessControl), new(*acimpl.AccessControl)), wire.Bind(new(notifications.TempUserStore), new(tempuser.Service)), tagimpl.ProvideService, wire.Bind(new(tag.Service), new(*tagimpl.Service)), authnimpl.ProvideService, authnimpl.ProvideIdentitySynchronizer, authnimpl.ProvideAuthnService, authnimpl.ProvideAuthnServiceAuthenticateOnly, authnimpl.ProvideRegistration, supportbundlesimpl.ProvideService, extsvcaccounts.ProvideExtSvcAccountsService, wire.Bind(new(serviceaccounts.ExtSvcAccountsService), new(*extsvcaccounts.ExtSvcAccountsService)), registry2.ProvideExtSvcRegistry, wire.Bind(new(extsvcauth.ExternalServiceRegistry), new(*registry2.Registry)), anonstore.ProvideAnonDBStore, wire.Bind(new(anonstore.AnonStore), new(*anonstore.AnonDBStore)), loggermw.Provide, slogadapter.Provide, signingkeysimpl.ProvideEmbeddedSigningKeysService, wire.Bind(new(signingkeys.Service), new(*signingkeysimpl.Service)), ssosettingsimpl.ProvideService, wire.Bind(new(ssosettings.Service), new(*ssosettingsimpl.Service)), idimpl.ProvideService, wire.Bind(new(auth.IDService), new(*idimpl.Service)), cloudmigrationimpl.ProvideService, caching.ProvideCachingServiceClient, userimpl.ProvideVerifier, connectors.ProvideOrgRoleMapper, wire.Bind(new(user.Verifier), new(*userimpl.Verifier)), authz.WireSet, metadata.ProvideSecureValueMetadataStorage, metadata.ProvideKeeperMetadataStorage, metadata.ProvideDecryptStorage, decrypt.ProvideDecryptAuthorizer, wire.Value([]decrypt.ExtraOwnerDecrypter(nil)), decrypt.ProvideDecryptService, inline.ProvideInlineSecureValueService, encryption.ProvideDataKeyStorage, encryption.ProvideGlobalDataKeyStorage, encryption.ProvideEncryptedValueStorage, encryption.ProvideGlobalEncryptedValueStorage, encryption.ProvideEncryptedValueMigrationExecutor, service5.ProvideSecureValueService, validator.ProvideKeeperValidator, validator.ProvideSecureValueValidator, mutator.ProvideKeeperMutator, mutator.ProvideSecureValueMutator, migrator.NewWithEngine, database4.ProvideDatabase, clock.ProvideClock, wire.Bind(new(contracts.Database), new(*database4.Database)), wire.Bind(new(contracts.Clock), new(*clock.Clock)), manager2.ProvideEncryptionManager, service4.ProvideAESGCMCipherService, resource.ProvideStorageMetrics, resource.ProvideIndexMetrics, migrations2.ProvideUnifiedStorageMigrationService, apiserver.WireSet, apiregistry.WireSet, appregistry.WireSet, client.ProvideK8sClientWithFallback) +var wireBasicSet = wire.NewSet(annotationsimpl.ProvideService, wire.Bind(new(annotations.Repository), new(*annotationsimpl.RepositoryImpl)), New, api.ProvideHTTPServer, query.ProvideService, wire.Bind(new(query.Service), new(*query.ServiceImpl)), bus.ProvideBus, wire.Bind(new(bus.Bus), new(*bus.InProcBus)), rendering.ProvideService, wire.Bind(new(rendering.Service), new(*rendering.RenderingService)), routing.ProvideRegister, wire.Bind(new(routing.RouteRegister), new(*routing.RouteRegisterImpl)), hooks.ProvideService, kvstore.ProvideService, localcache.ProvideService, bundleregistry.ProvideService, wire.Bind(new(supportbundles.Service), new(*bundleregistry.Service)), updatemanager.ProvideGrafanaService, updatemanager.ProvidePluginsService, service.ProvideService, wire.Bind(new(usagestats.Service), new(*service.UsageStats)), validator3.ProvideService, provisioning.ProvideStubProvisioningService, legacy.ProvideMigratorDashboardAccessor, migrations2.ProvideUnifiedMigrator, pluginsintegration.WireSet, dashboards.ProvideFileStoreManager, wire.Bind(new(dashboards.FileStore), new(*dashboards.FileStoreManager)), cloudwatch.ProvideService, cloudmonitoring.ProvideService, azuremonitor.ProvideService, postgres.ProvideService, mysql.ProvideService, mssql.ProvideService, store.ProvideEntityEventsService, dualwrite.ProvideService, httpclientprovider.New, wire.Bind(new(httpclient.Provider), new(*httpclient2.Provider)), serverlock.ProvideService, wire.Bind(new(installsync.ServerLock), new(*serverlock.ServerLockService)), annotationsimpl.ProvideCleanupService, wire.Bind(new(annotations.Cleaner), new(*annotationsimpl.CleanupServiceImpl)), cleanup.ProvideService, shorturlimpl.ProvideService, wire.Bind(new(shorturls.Service), new(*shorturlimpl.ShortURLService)), queryhistory.ProvideService, wire.Bind(new(queryhistory.Service), new(*queryhistory.QueryHistoryService)), correlations.ProvideService, wire.Bind(new(correlations.Service), new(*correlations.CorrelationsService)), quotaimpl.ProvideService, remotecache.ProvideService, wire.Bind(new(remotecache.CacheStorage), new(*remotecache.RemoteCache)), authinfoimpl.ProvideService, wire.Bind(new(login.AuthInfoService), new(*authinfoimpl.Service)), authinfoimpl.ProvideStore, datasourceproxy.ProvideService, sort.ProvideService, search2.ProvideService, searchV2.ProvideService, searchV2.ProvideSearchHTTPService, store.ProvideService, store.ProvideSystemUsersService, live.ProvideService, live.ProvideDashboardActivityChannel, pushhttp.ProvideService, contexthandler.ProvideService, service12.ProvideService, wire.Bind(new(service12.LDAP), new(*service12.LDAPImpl)), jwt.ProvideService, wire.Bind(new(jwt.JWTService), new(*jwt.AuthService)), store2.ProvideDBStore, image.ProvideDeleteExpiredService, ngalert.ProvideService, librarypanels.ProvideService, wire.Bind(new(librarypanels.Service), new(*librarypanels.LibraryPanelService)), libraryelements.ProvideService, wire.Bind(new(libraryelements.Service), new(*libraryelements.LibraryElementService)), notifications.ProvideService, notifications.ProvideSmtpService, github.ProvideFactory, tracing.ProvideService, tracing.ProvideTracingConfig, wire.Bind(new(tracing.Tracer), new(*tracing.TracingService)), withOTelSet, testdatasource.ProvideService, api4.ProvideService, opentsdb.ProvideService, socialimpl.ProvideService, influxdb.ProvideService, wire.Bind(new(social.Service), new(*socialimpl.SocialService)), tempo.ProvideService, loki.ProvideService, graphite.ProvideService, prometheus.ProvideService, elasticsearch.ProvideService, pyroscope.ProvideService, parca.ProvideService, zipkin.ProvideService, jaeger.ProvideService, service9.ProvideCacheService, wire.Bind(new(datasources.CacheService), new(*service9.CacheServiceImpl)), service2.ProvideEncryptionService, wire.Bind(new(encryption2.Internal), new(*service2.Service)), manager.ProvideSecretsService, wire.Bind(new(secrets.Service), new(*manager.SecretsService)), database.ProvideSecretsStore, wire.Bind(new(secrets.Store), new(*database.SecretsStoreImpl)), garbagecollectionworker.ProvideWorker, grafanads.ProvideService, wire.Bind(new(dashboardsnapshots.Store), new(*database5.DashboardSnapshotStore)), database5.ProvideStore, wire.Bind(new(dashboardsnapshots.Service), new(*service10.ServiceImpl)), service10.ProvideService, service9.ProvideService, wire.Bind(new(datasources.DataSourceService), new(*service9.Service)), service9.ProvideLegacyDataSourceLookup, retriever.ProvideService, wire.Bind(new(serviceaccounts.ServiceAccountRetriever), new(*retriever.Service)), ossaccesscontrol.ProvideServiceAccountPermissions, wire.Bind(new(accesscontrol.ServiceAccountPermissionsService), new(*ossaccesscontrol.ServiceAccountPermissionsService)), manager3.ProvideServiceAccountsService, proxy.ProvideServiceAccountsProxy, wire.Bind(new(serviceaccounts.Service), new(*proxy.ServiceAccountsProxy)), dsquerierclient.NewNullQSDatasourceClientBuilder, expr.ProvideService, featuremgmt.ProvideManagerService, featuremgmt.ProvideToggles, service7.ProvideDashboardServiceImpl, wire.Bind(new(dashboards2.PermissionsRegistrationService), new(*service7.DashboardServiceImpl)), service7.ProvideDashboardService, service7.ProvideDashboardProvisioningService, service7.ProvideDashboardPluginService, service7.ProvideDashboardAccessService, database2.ProvideDashboardStore, folderimpl.ProvideService, wire.Bind(new(folder.Service), new(*folderimpl.Service)), wire.Bind(new(folder.LegacyService), new(*folderimpl.Service)), folderimpl.ProvideStore, wire.Bind(new(folder.Store), new(*folderimpl.FolderStoreImpl)), service11.ProvideService, wire.Bind(new(dashboardimport.Service), new(*service11.ImportDashboardService)), service8.ProvideService, wire.Bind(new(plugindashboards.Service), new(*service8.Service)), service8.ProvideDashboardUpdater, kvstore2.ProvideService, avatar.ProvideAvatarCacheServer, statscollector.ProvideService, csrf.ProvideCSRFFilter, wire.Bind(new(csrf.Service), new(*csrf.CSRF)), ossaccesscontrol.ProvideTeamPermissions, wire.Bind(new(accesscontrol.TeamPermissionsService), new(*ossaccesscontrol.TeamPermissionsService)), ossaccesscontrol.ProvideFolderPermissions, wire.Bind(new(accesscontrol.FolderPermissionsService), new(*ossaccesscontrol.FolderPermissionsService)), ossaccesscontrol.ProvideDashboardPermissions, wire.Bind(new(accesscontrol.DashboardPermissionsService), new(*ossaccesscontrol.DashboardPermissionsService)), ossaccesscontrol.ProvideReceiverPermissionsService, wire.Bind(new(accesscontrol.ReceiverPermissionsService), new(*ossaccesscontrol.ReceiverPermissionsService)), starimpl.ProvideService, playlistimpl.ProvideService, apikeyimpl.ProvideService, dashverimpl.ProvideService, service3.ProvideService, wire.Bind(new(publicdashboards.Service), new(*service3.PublicDashboardServiceImpl)), database3.ProvideStore, wire.Bind(new(publicdashboards.Store), new(*database3.PublicDashboardStoreImpl)), metric.ProvideService, api2.ProvideApi, api3.ProvideApi, userimpl.ProvideService, orgimpl.ProvideService, orgimpl.ProvideDeletionService, statsimpl.ProvideService, grpccontext.ProvideContextHandler, grpcserver.ProvideHealthService, grpcserver.ProvideReflectionService, resolver.ProvideEntityReferenceResolver, teamimpl.ProvideService, teamapi.ProvideTeamAPI, tempuserimpl.ProvideService, loginattemptimpl.ProvideService, wire.Bind(new(loginattempt.Service), new(*loginattemptimpl.Service)), migrations3.ProvideDataSourceMigrationService, migrations3.ProvideSecretMigrationProvider, wire.Bind(new(migrations3.SecretMigrationProvider), new(*migrations3.SecretMigrationProviderImpl)), promtypemigration.ProvideAzurePromMigrationService, promtypemigration.ProvideAmazonPromMigrationService, promtypemigration.ProvidePromTypeMigrationProvider, wire.Bind(new(promtypemigration.PromTypeMigrationProvider), new(*promtypemigration.PromTypeMigrationProviderImpl)), resourcepermissions.NewActionSetService, wire.Bind(new(accesscontrol.ActionResolver), new(resourcepermissions.ActionSetService)), wire.Bind(new(pluginaccesscontrol.ActionSetRegistry), new(resourcepermissions.ActionSetService)), permreg.ProvidePermissionRegistry, acimpl.ProvideAccessControl, accesscontrol.ProvideFixedRolesLoader, dualwrite2.ProvideZanzanaReconciler, navtreeimpl.ProvideService, wire.Bind(new(accesscontrol.AccessControl), new(*acimpl.AccessControl)), wire.Bind(new(notifications.TempUserStore), new(tempuser.Service)), tagimpl.ProvideService, wire.Bind(new(tag.Service), new(*tagimpl.Service)), authnimpl.ProvideService, authnimpl.ProvideIdentitySynchronizer, authnimpl.ProvideAuthnService, authnimpl.ProvideAuthnServiceAuthenticateOnly, authnimpl.ProvideRegistration, supportbundlesimpl.ProvideService, extsvcaccounts.ProvideExtSvcAccountsService, wire.Bind(new(serviceaccounts.ExtSvcAccountsService), new(*extsvcaccounts.ExtSvcAccountsService)), registry2.ProvideExtSvcRegistry, wire.Bind(new(extsvcauth.ExternalServiceRegistry), new(*registry2.Registry)), anonstore.ProvideAnonDBStore, wire.Bind(new(anonstore.AnonStore), new(*anonstore.AnonDBStore)), loggermw.Provide, slogadapter.Provide, signingkeysimpl.ProvideEmbeddedSigningKeysService, wire.Bind(new(signingkeys.Service), new(*signingkeysimpl.Service)), ssosettingsimpl.ProvideService, wire.Bind(new(ssosettings.Service), new(*ssosettingsimpl.Service)), idimpl.ProvideService, wire.Bind(new(auth.IDService), new(*idimpl.Service)), cloudmigrationimpl.ProvideService, caching.ProvideCachingServiceClient, userimpl.ProvideVerifier, connectors.ProvideOrgRoleMapper, wire.Bind(new(user.Verifier), new(*userimpl.Verifier)), authz.WireSet, metadata.ProvideSecureValueMetadataStorage, metadata.ProvideKeeperMetadataStorage, metadata.ProvideDecryptStorage, decrypt.ProvideDecryptAuthorizer, wire.Value([]decrypt.ExtraOwnerDecrypter(nil)), decrypt.ProvideDecryptService, inline.ProvideInlineSecureValueService, encryption.ProvideDataKeyStorage, encryption.ProvideGlobalDataKeyStorage, encryption.ProvideEncryptedValueStorage, encryption.ProvideGlobalEncryptedValueStorage, encryption.ProvideEncryptedValueMigrationExecutor, service5.ProvideSecureValueService, validator.ProvideKeeperValidator, validator.ProvideSecureValueValidator, mutator.ProvideKeeperMutator, mutator.ProvideSecureValueMutator, migrator.NewWithEngine, database4.ProvideDatabase, clock.ProvideClock, wire.Bind(new(contracts.Database), new(*database4.Database)), wire.Bind(new(contracts.Clock), new(*clock.Clock)), manager2.ProvideEncryptionManager, service4.ProvideAESGCMCipherService, resource.ProvideStorageMetrics, resource.ProvideIndexMetrics, migrations2.ProvideUnifiedStorageMigrationService, apiserver.WireSet, apiregistry.WireSet, appregistry.WireSet, client.ProvideK8sClientWithFallback) var wireSet = wire.NewSet( wireBasicSet, metrics.WireSet, sqlstore.ProvideService, metrics2.ProvideService, wire.Bind(new(notifications.Service), new(*notifications.NotificationService)), wire.Bind(new(notifications.WebhookSender), new(*notifications.NotificationService)), wire.Bind(new(notifications.EmailSender), new(*notifications.NotificationService)), wire.Bind(new(db.DB), new(*sqlstore.SQLStore)), prefimpl.ProvideService, oauthtoken.ProvideService, wire.Bind(new(oauthtoken.OAuthTokenService), new(*oauthtoken.Service)), wire.Bind(new(cleanup.AlertRuleService), new(*store2.DBstore)), diff --git a/pkg/services/accesscontrol/models.go b/pkg/services/accesscontrol/models.go index dfda78ac9f0..b18fb4134f3 100644 --- a/pkg/services/accesscontrol/models.go +++ b/pkg/services/accesscontrol/models.go @@ -447,6 +447,7 @@ const ( ActionAlertingNotificationsTemplatesRead = "alert.notifications.templates:read" ActionAlertingNotificationsTemplatesWrite = "alert.notifications.templates:write" ActionAlertingNotificationsTemplatesDelete = "alert.notifications.templates:delete" + ActionAlertingNotificationsTemplatesTest = "alert.notifications.templates.test:write" // Alerting notifications time interval actions ActionAlertingNotificationsTimeIntervalsRead = "alert.notifications.time-intervals:read" @@ -459,6 +460,7 @@ const ( ActionAlertingReceiversReadSecrets = "alert.notifications.receivers.secrets:read" ActionAlertingReceiversCreate = "alert.notifications.receivers:create" ActionAlertingReceiversUpdate = "alert.notifications.receivers:write" + ActionAlertingReceiversUpdateProtected = "alert.notifications.receivers.protected:write" ActionAlertingReceiversDelete = "alert.notifications.receivers:delete" ActionAlertingReceiversTest = "alert.notifications.receivers:test" ActionAlertingReceiversPermissionsRead = "receivers.permissions:read" diff --git a/pkg/services/accesscontrol/ossaccesscontrol/receivers.go b/pkg/services/accesscontrol/ossaccesscontrol/receivers.go index 49ca4a0b3e8..9dd4def1db3 100644 --- a/pkg/services/accesscontrol/ossaccesscontrol/receivers.go +++ b/pkg/services/accesscontrol/ossaccesscontrol/receivers.go @@ -23,7 +23,7 @@ import ( var ReceiversViewActions = []string{accesscontrol.ActionAlertingReceiversRead} var ReceiversEditActions = append(ReceiversViewActions, []string{accesscontrol.ActionAlertingReceiversUpdate, accesscontrol.ActionAlertingReceiversDelete}...) -var ReceiversAdminActions = append(ReceiversEditActions, []string{accesscontrol.ActionAlertingReceiversReadSecrets, accesscontrol.ActionAlertingReceiversPermissionsRead, accesscontrol.ActionAlertingReceiversPermissionsWrite}...) +var ReceiversAdminActions = append(ReceiversEditActions, []string{accesscontrol.ActionAlertingReceiversReadSecrets, accesscontrol.ActionAlertingReceiversPermissionsRead, accesscontrol.ActionAlertingReceiversPermissionsWrite, accesscontrol.ActionAlertingReceiversUpdateProtected}...) // defaultPermissions returns the default permissions for a newly created receiver. func defaultPermissions() []accesscontrol.SetResourcePermissionCommand { diff --git a/pkg/services/accesscontrol/permreg/permreg.go b/pkg/services/accesscontrol/permreg/permreg.go index c9f010c2909..cae7b701cf0 100644 --- a/pkg/services/accesscontrol/permreg/permreg.go +++ b/pkg/services/accesscontrol/permreg/permreg.go @@ -85,7 +85,10 @@ func newPermissionRegistry() *permissionRegistry { "orgs": "orgs:id:", "plugins": "plugins:id:", "plugins.plugins": "plugins.plugins:uid:", - "plugins.pluginsmeta": "plugins.pluginsmeta:uid:", + "plugins.metas": "plugins.metas:uid:", + "advisor.checks": "advisor.checks:uid:", + "advisor.checktypes": "advisor.checktypes:uid:", + "advisor.register": "advisor.register:uid:", "provisioners": "provisioners:", "reports": "reports:id:", "permissions": "permissions:type:", diff --git a/pkg/services/accesscontrol/resourcepermissions/api.go b/pkg/services/accesscontrol/resourcepermissions/api.go index 981a99f5189..3c6d1da2038 100644 --- a/pkg/services/accesscontrol/resourcepermissions/api.go +++ b/pkg/services/accesscontrol/resourcepermissions/api.go @@ -33,6 +33,7 @@ type api struct { permissions []string features featuremgmt.FeatureToggles restConfigProvider apiserver.RestConfigProvider + logger log.Logger } func newApi(cfg *setting.Cfg, ac accesscontrol.AccessControl, router routing.RouteRegister, manager *Service, features featuremgmt.FeatureToggles, restConfigProvider apiserver.RestConfigProvider) *api { @@ -41,7 +42,23 @@ func newApi(cfg *setting.Cfg, ac accesscontrol.AccessControl, router routing.Rou for i := len(manager.permissions) - 1; i >= 0; i-- { permissions = append(permissions, manager.permissions[i]) } - return &api{cfg, ac, router, manager, permissions, features, restConfigProvider} + return &api{ + cfg: cfg, + ac: ac, + router: router, + service: manager, + permissions: permissions, + features: features, + restConfigProvider: restConfigProvider, + logger: log.New("resource-permissions-api"), + } +} + +// shouldUseK8sAPIs returns true if both feature flags for K8s API redirect are enabled +func (a *api) shouldUseK8sAPIs() bool { + //nolint:staticcheck // not yet migrated to OpenFeature + return a.features.IsEnabledGlobally(featuremgmt.FlagKubernetesAuthZHandlerRedirect) && + a.features.IsEnabledGlobally(featuremgmt.FlagKubernetesAuthzResourcePermissionApis) } func (a *api) registerEndpoints() { @@ -189,11 +206,10 @@ func (a *api) getPermissions(c *contextmodel.ReqContext) response.Response { return response.JSON(http.StatusOK, k8sPermissions) } span.RecordError(err) - logger := log.New("resource-permissions-api") if errors.Is(err, ErrRestConfigNotAvailable) { - logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + a.logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) } else { - logger.Warn("Failed to get resource permissions from k8s API, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + a.logger.Warn("Failed to get resource permissions from k8s API, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) } } @@ -304,6 +320,19 @@ func (a *api) setUserPermission(c *contextmodel.ReqContext) response.Response { return response.Error(http.StatusBadRequest, "bad request data", err) } + if a.shouldUseK8sAPIs() { + err := a.setUserPermissionToK8s(c.Req.Context(), c.Namespace, resourceID, userID, cmd.Permission) + if err == nil { + return permissionSetResponse(cmd) + } + span.RecordError(err) + if errors.Is(err, ErrRestConfigNotAvailable) { + a.logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } else { + a.logger.Warn("Failed to set user permission in k8s API, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } + } + _, err = a.service.SetUserPermission(c.Req.Context(), c.GetOrgID(), accesscontrol.User{ID: userID}, resourceID, cmd.Permission) if err != nil { return response.Err(err) @@ -361,6 +390,19 @@ func (a *api) setTeamPermission(c *contextmodel.ReqContext) response.Response { return response.Error(http.StatusBadRequest, "bad request data", err) } + if a.shouldUseK8sAPIs() { + err := a.setTeamPermissionToK8s(c.Req.Context(), c.Namespace, resourceID, teamID, cmd.Permission) + if err == nil { + return permissionSetResponse(cmd) + } + span.RecordError(err) + if errors.Is(err, ErrRestConfigNotAvailable) { + a.logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } else { + a.logger.Warn("Failed to set team permission in k8s API, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } + } + _, err = a.service.SetTeamPermission(c.Req.Context(), c.GetOrgID(), teamID, resourceID, cmd.Permission) if err != nil { return response.Err(err) @@ -415,6 +457,17 @@ func (a *api) setBuiltinRolePermission(c *contextmodel.ReqContext) response.Resp return response.Error(http.StatusBadRequest, "bad request data", err) } + if a.shouldUseK8sAPIs() { + err := a.setBuiltInRolePermissionToK8s(c.Req.Context(), c.Namespace, resourceID, builtInRole, cmd.Permission) + if err == nil { + return permissionSetResponse(cmd) + } + span.RecordError(err) + if errors.Is(err, ErrRestConfigNotAvailable) { + a.logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } + } + _, err := a.service.SetBuiltInRolePermission(c.Req.Context(), c.GetOrgID(), builtInRole, resourceID, cmd.Permission) if err != nil { return response.Err(err) @@ -463,6 +516,17 @@ func (a *api) setPermissions(c *contextmodel.ReqContext) response.Response { return response.Error(http.StatusBadRequest, "Bad request data: "+err.Error(), err) } + if a.shouldUseK8sAPIs() { + err := a.setResourcePermissionsToK8s(c.Req.Context(), c.Namespace, resourceID, cmd.Permissions) + if err == nil { + return response.Success("Permissions updated") + } + span.RecordError(err) + if errors.Is(err, ErrRestConfigNotAvailable) { + a.logger.Debug("k8s API not available for resource permissions, falling back to legacy", "error", err, "resourceID", resourceID, "resource", a.service.options.Resource) + } + } + _, err := a.service.SetPermissions(ctx, c.GetOrgID(), resourceID, cmd.Permissions...) if err != nil { return response.Err(err) diff --git a/pkg/services/accesscontrol/resourcepermissions/api_adapter.go b/pkg/services/accesscontrol/resourcepermissions/api_adapter.go index 868ae1a32b5..578111368e5 100644 --- a/pkg/services/accesscontrol/resourcepermissions/api_adapter.go +++ b/pkg/services/accesscontrol/resourcepermissions/api_adapter.go @@ -13,9 +13,12 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/dynamic" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/infra/log" + "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/team" "github.com/grafana/grafana/pkg/services/user" ) @@ -162,3 +165,231 @@ func getMapKeys(m map[string][]string) []string { func (a *api) buildResourcePermissionName(resourceID string) string { return fmt.Sprintf("%s-%s-%s", a.getAPIGroup(), a.service.options.Resource, resourceID) } + +// Write operations + +func (a *api) setResourcePermissionsToK8s(ctx context.Context, namespace string, resourceID string, permissions []accesscontrol.SetResourcePermissionCommand) error { + dynamicClient, err := a.getDynamicClient(ctx) + if err != nil { + return err + } + + resourcePermName := a.buildResourcePermissionName(resourceID) + resourcePermResource := dynamicClient.Resource(iamv0.ResourcePermissionInfo.GroupVersionResource()).Namespace(namespace) + + _, existingResourceVersion, err := a.getExistingResourcePermission(ctx, resourcePermResource, resourcePermName) + if err != nil { + return err + } + + k8sPermissions := make([]iamv0.ResourcePermissionspecPermission, 0, len(permissions)) + for _, perm := range permissions { + if perm.Permission == "" { + continue + } + + kind := a.getPermissionKind(perm) + name, err := a.getPermissionName(ctx, perm) + if err != nil { + return fmt.Errorf("failed to get permission name: %w", err) + } + + k8sPermissions = append(k8sPermissions, iamv0.ResourcePermissionspecPermission{ + Kind: iamv0.ResourcePermissionSpecPermissionKind(kind), + Name: name, + Verb: cases.Lower(language.Und).String(perm.Permission), + }) + } + + if len(k8sPermissions) == 0 { + if existingResourceVersion != "" { + err = resourcePermResource.Delete(ctx, resourcePermName, metav1.DeleteOptions{}) + if err != nil && !k8serrors.IsNotFound(err) { + return fmt.Errorf("failed to delete resource permission in k8s: %w", err) + } + } + return nil + } + + resourcePerm := &iamv0.ResourcePermission{ + TypeMeta: metav1.TypeMeta{ + APIVersion: iamv0.ResourcePermissionInfo.GroupVersion().String(), + Kind: iamv0.ResourcePermissionInfo.TypeMeta().Kind, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: resourcePermName, + Namespace: namespace, + ResourceVersion: existingResourceVersion, + }, + Spec: iamv0.ResourcePermissionSpec{ + Resource: iamv0.ResourcePermissionspecResource{ + ApiGroup: a.getAPIGroup(), + Resource: a.service.options.Resource, + Name: resourceID, + }, + Permissions: k8sPermissions, + }, + } + + return a.createOrUpdateResourcePermission(ctx, resourcePermResource, resourcePerm, existingResourceVersion != "") +} + +func (a *api) setUserPermissionToK8s(ctx context.Context, namespace string, resourceID string, userID int64, permission string) error { + userDetails, err := a.service.userService.GetByID(ctx, &user.GetUserByIDQuery{ID: userID}) + if err != nil { + return fmt.Errorf("failed to get user details: %w", err) + } + + return a.setSinglePermissionToK8s(ctx, namespace, resourceID, string(iamv0.ResourcePermissionSpecPermissionKindUser), userDetails.UID, permission) +} + +func (a *api) setTeamPermissionToK8s(ctx context.Context, namespace string, resourceID string, teamID int64, permission string) error { + teamDetails, err := a.service.teamService.GetTeamByID(ctx, &team.GetTeamByIDQuery{ID: teamID}) + if err != nil { + return fmt.Errorf("failed to get team details: %w", err) + } + + return a.setSinglePermissionToK8s(ctx, namespace, resourceID, string(iamv0.ResourcePermissionSpecPermissionKindTeam), teamDetails.UID, permission) +} + +func (a *api) setBuiltInRolePermissionToK8s(ctx context.Context, namespace string, resourceID string, builtInRole string, permission string) error { + return a.setSinglePermissionToK8s(ctx, namespace, resourceID, string(iamv0.ResourcePermissionSpecPermissionKindBasicRole), builtInRole, permission) +} + +func (a *api) setSinglePermissionToK8s(ctx context.Context, namespace string, resourceID string, kind string, name string, permission string) error { + dynamicClient, err := a.getDynamicClient(ctx) + if err != nil { + return err + } + + resourcePermName := a.buildResourcePermissionName(resourceID) + resourcePermResource := dynamicClient.Resource(iamv0.ResourcePermissionInfo.GroupVersionResource()).Namespace(namespace) + + existingResourcePerm, existingResourceVersion, err := a.getExistingResourcePermission(ctx, resourcePermResource, resourcePermName) + if err != nil { + return err + } + + newPermissions := make([]iamv0.ResourcePermissionspecPermission, 0) + for _, perm := range existingResourcePerm.Spec.Permissions { + if string(perm.Kind) == kind && perm.Name == name { + continue + } + newPermissions = append(newPermissions, perm) + } + + if permission != "" { + newPermissions = append(newPermissions, iamv0.ResourcePermissionspecPermission{ + Kind: iamv0.ResourcePermissionSpecPermissionKind(kind), + Name: name, + Verb: cases.Lower(language.Und).String(permission), + }) + } + + if len(newPermissions) == 0 { + if existingResourceVersion != "" { + err = resourcePermResource.Delete(ctx, resourcePermName, metav1.DeleteOptions{}) + if err != nil && !k8serrors.IsNotFound(err) { + return fmt.Errorf("failed to delete resource permission in k8s: %w", err) + } + } + return nil + } + + resourcePerm := &iamv0.ResourcePermission{ + TypeMeta: metav1.TypeMeta{ + APIVersion: iamv0.ResourcePermissionInfo.GroupVersion().String(), + Kind: iamv0.ResourcePermissionInfo.TypeMeta().Kind, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: resourcePermName, + Namespace: namespace, + ResourceVersion: existingResourceVersion, + }, + Spec: iamv0.ResourcePermissionSpec{ + Resource: iamv0.ResourcePermissionspecResource{ + ApiGroup: a.getAPIGroup(), + Resource: a.service.options.Resource, + Name: resourceID, + }, + Permissions: newPermissions, + }, + } + + return a.createOrUpdateResourcePermission(ctx, resourcePermResource, resourcePerm, existingResourceVersion != "") +} + +func (a *api) getPermissionKind(perm accesscontrol.SetResourcePermissionCommand) string { + if perm.UserID != 0 { + return string(iamv0.ResourcePermissionSpecPermissionKindUser) + } + if perm.TeamID != 0 { + return string(iamv0.ResourcePermissionSpecPermissionKindTeam) + } + if perm.BuiltinRole != "" { + return string(iamv0.ResourcePermissionSpecPermissionKindBasicRole) + } + return "" +} + +func (a *api) getExistingResourcePermission(ctx context.Context, resourcePermResource dynamic.ResourceInterface, resourcePermName string) (*iamv0.ResourcePermission, string, error) { + unstructuredObj, err := resourcePermResource.Get(ctx, resourcePermName, metav1.GetOptions{}) + if err != nil { + if k8serrors.IsNotFound(err) { + return &iamv0.ResourcePermission{}, "", nil + } + return nil, "", fmt.Errorf("failed to get existing resource permission: %w", err) + } + + var resourcePerm iamv0.ResourcePermission + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredObj.Object, &resourcePerm); err != nil { + return nil, "", fmt.Errorf("failed to convert existing resource permission: %w", err) + } + + return &resourcePerm, unstructuredObj.GetResourceVersion(), nil +} + +func (a *api) createOrUpdateResourcePermission(ctx context.Context, resourcePermResource dynamic.ResourceInterface, resourcePerm *iamv0.ResourcePermission, isUpdate bool) error { + unstructuredObj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(resourcePerm) + if err != nil { + return fmt.Errorf("failed to convert resource permission to unstructured: %w", err) + } + unstructuredPerm := &unstructured.Unstructured{Object: unstructuredObj} + + if isUpdate { + _, err = resourcePermResource.Update(ctx, unstructuredPerm, metav1.UpdateOptions{}) + if err != nil { + return fmt.Errorf("failed to update resource permission in k8s: %w", err) + } + } else { + _, err = resourcePermResource.Create(ctx, unstructuredPerm, metav1.CreateOptions{}) + if err != nil { + return fmt.Errorf("failed to create resource permission in k8s: %w", err) + } + } + + return nil +} + +func (a *api) getPermissionName(ctx context.Context, perm accesscontrol.SetResourcePermissionCommand) (string, error) { + if perm.UserID != 0 { + userDetails, err := a.service.userService.GetByID(ctx, &user.GetUserByIDQuery{ID: perm.UserID}) + if err != nil { + return "", fmt.Errorf("failed to get user details for user ID %d: %w", perm.UserID, err) + } + return userDetails.UID, nil + } + if perm.TeamID != 0 { + teamDetails, err := a.service.teamService.GetTeamByID(ctx, &team.GetTeamByIDQuery{ + ID: perm.TeamID, + }) + if err != nil { + return "", fmt.Errorf("failed to get team details for team ID %d: %w", perm.TeamID, err) + } + return teamDetails.UID, nil + } + if perm.BuiltinRole != "" { + return perm.BuiltinRole, nil + } + return "", fmt.Errorf("no valid permission subject found") +} diff --git a/pkg/services/accesscontrol/resourcepermissions/api_adapter_test.go b/pkg/services/accesscontrol/resourcepermissions/api_adapter_test.go new file mode 100644 index 00000000000..ca0ca214c9a --- /dev/null +++ b/pkg/services/accesscontrol/resourcepermissions/api_adapter_test.go @@ -0,0 +1,200 @@ +package resourcepermissions + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/services/accesscontrol" +) + +// TestGetPermissionKind tests the permission kind mapping logic +func TestGetPermissionKind(t *testing.T) { + api := &api{ + service: &Service{ + options: Options{ + Resource: "dashboards", + ResourceAttribute: "uid", + }, + }, + } + + tests := []struct { + name string + perm accesscontrol.SetResourcePermissionCommand + expected string + }{ + { + name: "user permission", + perm: accesscontrol.SetResourcePermissionCommand{UserID: 123}, + expected: string(iamv0.ResourcePermissionSpecPermissionKindUser), + }, + { + name: "team permission", + perm: accesscontrol.SetResourcePermissionCommand{TeamID: 456}, + expected: string(iamv0.ResourcePermissionSpecPermissionKindTeam), + }, + { + name: "builtin role permission", + perm: accesscontrol.SetResourcePermissionCommand{BuiltinRole: "Editor"}, + expected: string(iamv0.ResourcePermissionSpecPermissionKindBasicRole), + }, + { + name: "empty permission returns empty kind", + perm: accesscontrol.SetResourcePermissionCommand{}, + expected: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kind := api.getPermissionKind(tt.perm) + assert.Equal(t, tt.expected, kind) + }) + } +} + +// TestGetDynamicClient_RestConfigNotAvailable tests error handling when rest config is not available +func TestGetDynamicClient_RestConfigNotAvailable(t *testing.T) { + ctx := context.Background() + + api := &api{ + service: &Service{ + options: Options{ + Resource: "dashboards", + }, + }, + restConfigProvider: nil, + } + + client, err := api.getDynamicClient(ctx) + + assert.Error(t, err) + assert.Nil(t, client) + assert.Equal(t, ErrRestConfigNotAvailable, err) +} + +// TestBuildResourcePermissionName tests resource permission name building +func TestBuildResourcePermissionName(t *testing.T) { + tests := []struct { + name string + apiGroup string + resource string + resourceID string + expectedName string + }{ + { + name: "with custom API group", + apiGroup: "dashboard.grafana.app", + resource: "dashboards", + resourceID: "dashboard-uid-123", + expectedName: "dashboard.grafana.app-dashboards-dashboard-uid-123", + }, + { + name: "with default API group", + apiGroup: "", + resource: "folders", + resourceID: "folder-uid-456", + expectedName: "folders.grafana.app-folders-folder-uid-456", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + api := &api{ + service: &Service{ + options: Options{ + Resource: tt.resource, + APIGroup: tt.apiGroup, + }, + }, + } + + name := api.buildResourcePermissionName(tt.resourceID) + assert.Equal(t, tt.expectedName, name) + }) + } +} + +// TestGetAPIGroup tests API group resolution +func TestGetAPIGroup(t *testing.T) { + t.Run("returns custom API group when set", func(t *testing.T) { + api := &api{ + service: &Service{ + options: Options{ + Resource: "dashboards", + APIGroup: "custom.grafana.app", + }, + }, + } + + group := api.getAPIGroup() + assert.Equal(t, "custom.grafana.app", group) + }) + + t.Run("returns default API group when not set", func(t *testing.T) { + api := &api{ + service: &Service{ + options: Options{ + Resource: "dashboards", + APIGroup: "", + }, + }, + } + + group := api.getAPIGroup() + assert.Equal(t, "dashboards.grafana.app", group) + }) + + t.Run("default group for folders", func(t *testing.T) { + api := &api{ + service: &Service{ + options: Options{ + Resource: "folders", + APIGroup: "", + }, + }, + } + + group := api.getAPIGroup() + assert.Equal(t, "folders.grafana.app", group) + }) +} + +// TestResourcePermissionKindConstants verifies the kind constants match expected values +func TestResourcePermissionKindConstants(t *testing.T) { + tests := []struct { + name string + kind iamv0.ResourcePermissionSpecPermissionKind + expected string + }{ + { + name: "User kind", + kind: iamv0.ResourcePermissionSpecPermissionKindUser, + expected: "User", + }, + { + name: "Team kind", + kind: iamv0.ResourcePermissionSpecPermissionKindTeam, + expected: "Team", + }, + { + name: "ServiceAccount kind", + kind: iamv0.ResourcePermissionSpecPermissionKindServiceAccount, + expected: "ServiceAccount", + }, + { + name: "BasicRole kind", + kind: iamv0.ResourcePermissionSpecPermissionKindBasicRole, + expected: "BasicRole", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, string(tt.kind)) + }) + } +} diff --git a/pkg/services/apiserver/appinstaller/installer.go b/pkg/services/apiserver/appinstaller/installer.go index b6e9145ff15..d282b42f547 100644 --- a/pkg/services/apiserver/appinstaller/installer.go +++ b/pkg/services/apiserver/appinstaller/installer.go @@ -108,9 +108,14 @@ func RegisterAuthorizers( if authorizerProvider, ok := installer.(AuthorizerProvider); ok { authorizer := authorizerProvider.GetAuthorizer() for _, gv := range installer.GroupVersions() { + if authorizer == nil { + panic("authorizer cannot be nil for api group: " + gv.String()) + } registrar.Register(gv, authorizer) logger.Debug("Registered authorizer", "group", gv.Group, "version", gv.Version, "app") } + } else { + panic("authorizer cannot be nil for api group: " + installer.GroupVersions()[0].Group) } } } diff --git a/pkg/services/apiserver/appinstaller/installer_test.go b/pkg/services/apiserver/appinstaller/installer_test.go index 89c4bfa0164..53c2d2dbedf 100644 --- a/pkg/services/apiserver/appinstaller/installer_test.go +++ b/pkg/services/apiserver/appinstaller/installer_test.go @@ -15,6 +15,7 @@ func TestRegisterAuthorizers(t *testing.T) { name string appInstallers []appsdkapiserver.AppInstaller expectedRegisters int + expectedPanic bool }{ { name: "empty installers list", @@ -30,7 +31,7 @@ func TestRegisterAuthorizers(t *testing.T) { }, }, }, - expectedRegisters: 0, + expectedPanic: true, }, { name: "single installer with authorizer provider", @@ -46,6 +47,20 @@ func TestRegisterAuthorizers(t *testing.T) { }, expectedRegisters: 1, }, + { + name: "single installer with invalid authorizer provider", + appInstallers: []appsdkapiserver.AppInstaller{ + &mockAppInstallerWithAuth{ + mockAppInstaller: &mockAppInstaller{ + groupVersions: []schema.GroupVersion{ + {Group: "test.example.com", Version: "v1"}, + }, + }, + mockAuthorizer: nil, + }, + }, + expectedPanic: true, + }, { name: "installer with multiple group versions", appInstallers: []appsdkapiserver.AppInstaller{ @@ -63,7 +78,7 @@ func TestRegisterAuthorizers(t *testing.T) { expectedRegisters: 3, }, { - name: "multiple installers with mixed authorizer support", + name: "multiple installers with authorizer support", appInstallers: []appsdkapiserver.AppInstaller{ &mockAppInstallerWithAuth{ mockAppInstaller: &mockAppInstaller{ @@ -73,11 +88,6 @@ func TestRegisterAuthorizers(t *testing.T) { }, mockAuthorizer: &mockAuthorizer{}, }, - &mockAppInstaller{ - groupVersions: []schema.GroupVersion{ - {Group: "other.example.com", Version: "v1"}, - }, - }, &mockAppInstallerWithAuth{ mockAppInstaller: &mockAppInstaller{ groupVersions: []schema.GroupVersion{ @@ -88,7 +98,7 @@ func TestRegisterAuthorizers(t *testing.T) { mockAuthorizer: &mockAuthorizer{}, }, }, - expectedRegisters: 3, // 1 from first installer + 2 from third installer + expectedRegisters: 3, // 1 from first installer + 2 from second installer }, } @@ -96,6 +106,13 @@ func TestRegisterAuthorizers(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() registrar := &mockAuthorizerRegistrar{} + if tt.expectedPanic { + defer func() { + if r := recover(); r == nil { + t.Errorf("%s case did not panic as expected", t.Name()) + } + }() + } RegisterAuthorizers(ctx, tt.appInstallers, registrar) require.Equal(t, tt.expectedRegisters, len(registrar.registrations)) }) diff --git a/pkg/services/apiserver/auth/authorizer/authorizer.go b/pkg/services/apiserver/auth/authorizer/authorizer.go index 54ea8c081d7..dab8167deb0 100644 --- a/pkg/services/apiserver/auth/authorizer/authorizer.go +++ b/pkg/services/apiserver/auth/authorizer/authorizer.go @@ -38,11 +38,13 @@ func NewGrafanaBuiltInSTAuthorizer(cfg *setting.Cfg) *GrafanaAuthorizer { // Individual services may have explicit implementations apis := make(map[string]authorizer.Authorizer) + // The apiVersion flavors will run first and can return early when FGAC has appropriate rules authorizers = append(authorizers, &authorizerForAPI{apis}) - // org role is last -- and will return allow for verbs that match expectations - // The apiVersion flavors will run first and can return early when FGAC has appropriate rules - authorizers = append(authorizers, newRoleAuthorizer()) + // org role authorizer is last -- and will return allow for verbs that match expectations + // it is only helpful here for remote APIs in some cloud use-cases. + //nolint:staticcheck // remove once build handler chains are untangled between local and remote APIs handling + authorizers = append(authorizers, NewRoleAuthorizer()) return &GrafanaAuthorizer{ apis: apis, auth: union.New(authorizers...), diff --git a/pkg/services/apiserver/auth/authorizer/resource.go b/pkg/services/apiserver/auth/authorizer/resource.go index b86f6b40f09..f2f959f9381 100644 --- a/pkg/services/apiserver/auth/authorizer/resource.go +++ b/pkg/services/apiserver/auth/authorizer/resource.go @@ -9,13 +9,13 @@ import ( claims "github.com/grafana/authlib/types" ) -func NewResourceAuthorizer(c claims.AccessClient) authorizer.Authorizer { +func NewResourceAuthorizer(c claims.AccessChecker) authorizer.Authorizer { return ResourceAuthorizer{c} } // ResourceAuthorizer is used to translate authorizer.Authorizer calls to claims.AccessClient calls type ResourceAuthorizer struct { - c claims.AccessClient + c claims.AccessChecker } func (r ResourceAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (authorizer.Decision, string, error) { diff --git a/pkg/services/apiserver/auth/authorizer/role.go b/pkg/services/apiserver/auth/authorizer/role.go index 39b3b440665..e8e70dd01c8 100644 --- a/pkg/services/apiserver/auth/authorizer/role.go +++ b/pkg/services/apiserver/auth/authorizer/role.go @@ -19,7 +19,8 @@ var orgRoleNoneAsViewerAPIGroups = []string{ type roleAuthorizer struct{} -func newRoleAuthorizer() *roleAuthorizer { +// Deprecated: NewRoleAuthorizer exists for apps that were launched with simplistic authorization requirements. Consider using NewResourceAuthorizer instead. +func NewRoleAuthorizer() *roleAuthorizer { return &roleAuthorizer{} } diff --git a/pkg/services/apiserver/builder/common.go b/pkg/services/apiserver/builder/common.go index bebbad8e8a6..e5e46a3340d 100644 --- a/pkg/services/apiserver/builder/common.go +++ b/pkg/services/apiserver/builder/common.go @@ -9,6 +9,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apiserver/pkg/admission" + "k8s.io/apiserver/pkg/audit" "k8s.io/apiserver/pkg/authorization/authorizer" "k8s.io/apiserver/pkg/registry/generic" genericapiserver "k8s.io/apiserver/pkg/server" @@ -59,6 +60,13 @@ type APIGroupAuthorizer interface { GetAuthorizer() authorizer.Authorizer } +// APIGroupAuditor allows different API groups to opt-in and provide their own auditing policy evaluator function. +// Auditing is only enabled if this is implemented. If no customization is needed, you can use the default evaluator, +// `pkg/apiserver/auditing.NewDefaultGrafanaPolicyRuleEvaluator()`. +type APIGroupAuditor interface { + GetPolicyRuleEvaluator() audit.PolicyRuleEvaluator +} + type APIGroupMutation interface { // Mutate allows the builder to make changes to the object before it is persisted. // Context is used only for timeout/deadline/cancellation and tracing information. diff --git a/pkg/services/apiserver/builder/helper.go b/pkg/services/apiserver/builder/helper.go index a76a01dffba..c535443a91e 100644 --- a/pkg/services/apiserver/builder/helper.go +++ b/pkg/services/apiserver/builder/helper.go @@ -29,6 +29,7 @@ import ( "k8s.io/klog/v2" "k8s.io/kube-openapi/pkg/common" + "github.com/grafana/grafana/pkg/apiserver/auditing" "github.com/grafana/grafana/pkg/apiserver/endpoints/filters" grafanarest "github.com/grafana/grafana/pkg/apiserver/rest" "github.com/grafana/grafana/pkg/services/apiserver/endpoints/request" @@ -497,6 +498,32 @@ func AddPostStartHooks( return nil } +func EvaluatorPolicyRuleFromBuilders(builders []APIGroupBuilder) auditing.PolicyRuleEvaluators { + policyRuleEvaluators := make(auditing.PolicyRuleEvaluators, 0) + + for _, b := range builders { + auditor, ok := b.(APIGroupAuditor) + if !ok { + continue + } + + policyRuleEvaluator := auditor.GetPolicyRuleEvaluator() + if policyRuleEvaluator == nil { + continue + } + + for _, gv := range GetGroupVersions(b) { + if gv.Empty() { + continue + } + + policyRuleEvaluators[gv] = policyRuleEvaluator + } + } + + return policyRuleEvaluators +} + func allowRegisteringResourceByInfo(allowedResources []string, name string) bool { // trim any subresources from the name name = strings.Split(name, "/")[0] diff --git a/pkg/services/apiserver/service.go b/pkg/services/apiserver/service.go index 605016c112d..6c92350ec2a 100644 --- a/pkg/services/apiserver/service.go +++ b/pkg/services/apiserver/service.go @@ -12,6 +12,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/apiserver/pkg/audit" genericapifilters "k8s.io/apiserver/pkg/endpoints/filters" "k8s.io/apiserver/pkg/endpoints/responsewriter" genericapiserver "k8s.io/apiserver/pkg/server" @@ -27,6 +28,7 @@ import ( dataplaneaggregator "github.com/grafana/grafana/pkg/aggregator/apiserver" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/apiserver/auditing" grafanaresponsewriter "github.com/grafana/grafana/pkg/apiserver/endpoints/responsewriter" grafanarest "github.com/grafana/grafana/pkg/apiserver/rest" "github.com/grafana/grafana/pkg/infra/db" @@ -113,6 +115,9 @@ type service struct { appInstallers []appsdkapiserver.AppInstaller builderMetrics *builder.BuilderMetrics dualWriterMetrics *grafanarest.DualWriterMetrics + + auditBackend audit.Backend + auditPolicyRuleProvider auditing.PolicyRuleProvider } func ProvideService( @@ -137,6 +142,8 @@ func ProvideService( aggregatorRunner aggregatorrunner.AggregatorRunner, appInstallers []appsdkapiserver.AppInstaller, builderMetrics *builder.BuilderMetrics, + auditBackend audit.Backend, + auditPolicyRuleProvider auditing.PolicyRuleProvider, ) (*service, error) { scheme := builder.ProvideScheme() codecs := builder.ProvideCodecFactory(scheme) @@ -167,6 +174,8 @@ func ProvideService( appInstallers: appInstallers, builderMetrics: builderMetrics, dualWriterMetrics: grafanarest.NewDualWriterMetrics(reg), + auditBackend: auditBackend, + auditPolicyRuleProvider: auditPolicyRuleProvider, } // This will be used when running as a dskit service s.NamedService = services.NewBasicService(s.start, s.running, nil).WithName(modules.GrafanaAPIServer) @@ -275,6 +284,8 @@ func (s *service) start(ctx context.Context) error { auth := a.GetAuthorizer() if auth != nil { s.authorizer.Register(gv, auth) + } else { + panic("authorizer can not be nil for api group=" + gv.String()) } } } @@ -353,6 +364,10 @@ func (s *service) start(ctx context.Context) error { appinstaller.BuildOpenAPIDefGetter(s.appInstallers), } + // Auditing Options + serverConfig.AuditBackend = s.auditBackend + serverConfig.AuditPolicyRuleEvaluator = s.auditPolicyRuleProvider.PolicyRuleProvider(builder.EvaluatorPolicyRuleFromBuilders(s.builders)) + // Add OpenAPI specs for each group+version (existing builders) err = builder.SetupConfig( s.scheme, diff --git a/pkg/services/authn/authnimpl/sync/user_sync.go b/pkg/services/authn/authnimpl/sync/user_sync.go index cb8099ba1d1..ada03081add 100644 --- a/pkg/services/authn/authnimpl/sync/user_sync.go +++ b/pkg/services/authn/authnimpl/sync/user_sync.go @@ -77,6 +77,10 @@ var ( "user.sync.user-externalUID-mismatch", errutil.WithPublicMessage("User externalUID mismatch"), ) + errSCIMAuthModuleMismatch = errutil.Unauthorized( + "user.sync.scim-auth-module-mismatch", + errutil.WithPublicMessage("User was provisioned via SCIM and must login via SAML"), + ) ) var ( @@ -308,6 +312,21 @@ func (s *UserSync) SyncUserHook(ctx context.Context, id *authn.Identity, _ *auth // just try to fetch the user one more to make the other request work. if errors.Is(err, user.ErrUserAlreadyExists) { usr, _, err = s.getUser(ctx, id) + + // Check if this is a SCIM-provisioned user trying to login via an auth module that is not SAML or GCOM + if err == nil && usr != nil && usr.IsProvisioned && id.AuthenticatedBy != login.GrafanaComAuthModule { + _, authErr := s.authInfoService.GetAuthInfo(ctx, &login.GetAuthInfoQuery{ + UserId: usr.ID, + AuthModule: id.AuthenticatedBy, + }) + if errors.Is(authErr, user.ErrUserNotFound) { + s.log.FromContext(ctx).Error("SCIM-provisioned user attempted login via non-SAML auth module", + "user_id", usr.ID, + "attempted_module", id.AuthenticatedBy, + ) + return errSCIMAuthModuleMismatch.Errorf("user was provisioned via SCIM but attempted login via %s", id.AuthenticatedBy) + } + } } if err != nil { diff --git a/pkg/services/authn/authnimpl/sync/user_sync_test.go b/pkg/services/authn/authnimpl/sync/user_sync_test.go index dd19836b0a5..ad863164aee 100644 --- a/pkg/services/authn/authnimpl/sync/user_sync_test.go +++ b/pkg/services/authn/authnimpl/sync/user_sync_test.go @@ -1926,3 +1926,100 @@ func TestUserSync_SCIMLoginUsageStatSet(t *testing.T) { finalCount := finalStats["stats.features.scim.has_successful_login.count"].(int) require.Equal(t, int(1), finalCount) } + +func TestUserSync_SyncUserHook_SCIMAuthModuleMismatch(t *testing.T) { + userSrv := usertest.NewMockService(t) + authInfoSrv := authinfotest.NewMockAuthInfoService(t) + + userSrv.On("GetByEmail", mock.Anything, mock.Anything).Return(nil, user.ErrUserNotFound).Once() + + userSrv.On("Create", mock.Anything, mock.Anything).Return(nil, user.ErrUserAlreadyExists).Once() + + userSrv.On("GetByEmail", mock.Anything, mock.Anything).Return(&user.User{ + ID: 1, + Email: "test@test.com", + IsProvisioned: true, + }, nil).Once() + + authInfoSrv.On("GetAuthInfo", mock.Anything, mock.MatchedBy(func(q *login.GetAuthInfoQuery) bool { + return q.AuthModule == "oauth_azuread" + })).Return(nil, user.ErrUserNotFound).Once() + + s := ProvideUserSync( + userSrv, + authinfoimpl.ProvideOSSUserProtectionService(), + authInfoSrv, + "atest.FakeQuotaService{}, + tracing.NewNoopTracerService(), + featuremgmt.WithFeatures(), + setting.NewCfg(), + nil, + ) + + email := "test@test.com" + + err := s.SyncUserHook(context.Background(), &authn.Identity{ + AuthenticatedBy: "oauth_azuread", + ClientParams: authn.ClientParams{ + SyncUser: true, + AllowSignUp: true, + LookUpParams: login.UserLookupParams{ + Email: &email, + }, + }, + }, nil) + + require.Error(t, err) + assert.ErrorIs(t, err, errSCIMAuthModuleMismatch) + assert.Contains(t, err.Error(), "SCIM") + assert.Contains(t, err.Error(), "oauth_azuread") +} + +func TestUserSync_SyncUserHook_SCIMUserAllowsGCOMLogin(t *testing.T) { + userSrv := usertest.NewMockService(t) + authInfoSrv := authinfotest.NewMockAuthInfoService(t) + + authInfoSrv.On("GetAuthInfo", mock.Anything, mock.MatchedBy(func(q *login.GetAuthInfoQuery) bool { + return q.AuthModule == login.GrafanaComAuthModule && q.AuthId == "gcom-user-123" + })).Return(nil, user.ErrUserNotFound).Once() + + userSrv.On("GetByEmail", mock.Anything, mock.Anything).Return(nil, user.ErrUserNotFound).Once() + userSrv.On("Create", mock.Anything, mock.Anything).Return(nil, user.ErrUserAlreadyExists).Once() + + authInfoSrv.On("GetAuthInfo", mock.Anything, mock.MatchedBy(func(q *login.GetAuthInfoQuery) bool { + return q.AuthModule == login.GrafanaComAuthModule && q.AuthId == "gcom-user-123" + })).Return(nil, user.ErrUserNotFound).Once() + + userSrv.On("GetByEmail", mock.Anything, mock.Anything).Return(&user.User{ + ID: 1, + Email: "test@test.com", + IsProvisioned: true, + }, nil).Once() + + s := ProvideUserSync( + userSrv, + authinfoimpl.ProvideOSSUserProtectionService(), + authInfoSrv, + "atest.FakeQuotaService{}, + tracing.NewNoopTracerService(), + featuremgmt.WithFeatures(), + setting.NewCfg(), + nil, + ) + + email := "test@test.com" + + err := s.SyncUserHook(context.Background(), &authn.Identity{ + AuthenticatedBy: login.GrafanaComAuthModule, + AuthID: "gcom-user-123", + ClientParams: authn.ClientParams{ + SyncUser: true, + AllowSignUp: true, + LookUpParams: login.UserLookupParams{ + Email: &email, + }, + }, + }, nil) + + require.NoError(t, err) +} diff --git a/pkg/services/authz/rbac.go b/pkg/services/authz/rbac.go index 23de10511a2..c6c078a9b4a 100644 --- a/pkg/services/authz/rbac.go +++ b/pkg/services/authz/rbac.go @@ -152,7 +152,7 @@ func ProvideStandaloneAuthZClient( //nolint:staticcheck // not yet migrated to OpenFeature zanzanaEnabled := features.IsEnabledGlobally(featuremgmt.FlagZanzana) - zanzanaClient, err := ProvideStandaloneZanzanaClient(cfg, features) + zanzanaClient, err := ProvideStandaloneZanzanaClient(cfg, features, reg) if err != nil { return nil, err } diff --git a/pkg/services/authz/rbac/mapper.go b/pkg/services/authz/rbac/mapper.go index e34965df999..9444d35d0ae 100644 --- a/pkg/services/authz/rbac/mapper.go +++ b/pkg/services/authz/rbac/mapper.go @@ -298,8 +298,13 @@ func NewMapperRegistry() MapperRegistry { }, }, "plugins.grafana.app": { - "plugins": newResourceTranslation("plugins.plugins", "uid", false, nil), - "pluginsmeta": newResourceTranslation("plugins.pluginsmeta", "uid", false, nil), + "plugins": newResourceTranslation("plugins.plugins", "uid", false, nil), + "metas": newResourceTranslation("plugins.metas", "uid", false, nil), + }, + "advisor.grafana.app": { + "checks": newResourceTranslation("advisor.checks", "uid", false, nil), + "checktypes": newResourceTranslation("advisor.checktypes", "uid", false, nil), + "register": newResourceTranslation("advisor.register", "uid", false, nil), }, }) diff --git a/pkg/services/authz/zanzana.go b/pkg/services/authz/zanzana.go index da77010d0eb..f6751258f2d 100644 --- a/pkg/services/authz/zanzana.go +++ b/pkg/services/authz/zanzana.go @@ -4,16 +4,19 @@ import ( "context" "errors" "fmt" + "time" "github.com/fullstorydev/grpchan/inprocgrpc" authnlib "github.com/grafana/authlib/authn" authzv1 "github.com/grafana/authlib/authz/proto/v1" "github.com/grafana/authlib/grpcutils" "github.com/grafana/authlib/types" + "github.com/grafana/dskit/middleware" "github.com/grafana/dskit/services" grpcAuth "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth" openfgav1 "github.com/openfga/api/proto/openfga/v1" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" @@ -43,14 +46,14 @@ func ProvideZanzanaClient(cfg *setting.Cfg, db db.DB, tracer tracing.Tracer, fea switch cfg.ZanzanaClient.Mode { case setting.ZanzanaModeClient: - return NewRemoteZanzanaClient( - fmt.Sprintf("stacks-%s", cfg.StackID), - ZanzanaClientConfig{ - URL: cfg.ZanzanaClient.Addr, - Token: cfg.ZanzanaClient.Token, - TokenExchangeURL: cfg.ZanzanaClient.TokenExchangeURL, - ServerCertFile: cfg.ZanzanaClient.ServerCertFile, - }) + zanzanaConfig := ZanzanaClientConfig{ + Addr: cfg.ZanzanaClient.Addr, + Token: cfg.ZanzanaClient.Token, + TokenExchangeURL: cfg.ZanzanaClient.TokenExchangeURL, + TokenNamespace: cfg.ZanzanaClient.TokenNamespace, + ServerCertFile: cfg.ZanzanaClient.ServerCertFile, + } + return NewRemoteZanzanaClient(zanzanaConfig, reg) case setting.ZanzanaModeEmbedded: logger := log.New("zanzana.server") @@ -97,32 +100,33 @@ func ProvideZanzanaClient(cfg *setting.Cfg, db db.DB, tracer tracing.Tracer, fea // ProvideStandaloneZanzanaClient provides a standalone Zanzana client, without registering the Zanzana service. // Client connects to a remote Zanzana server specified in the configuration. -func ProvideStandaloneZanzanaClient(cfg *setting.Cfg, features featuremgmt.FeatureToggles) (zanzana.Client, error) { +func ProvideStandaloneZanzanaClient(cfg *setting.Cfg, features featuremgmt.FeatureToggles, reg prometheus.Registerer) (zanzana.Client, error) { //nolint:staticcheck // not yet migrated to OpenFeature if !features.IsEnabledGlobally(featuremgmt.FlagZanzana) { return zClient.NewNoopClient(), nil } zanzanaConfig := ZanzanaClientConfig{ - URL: cfg.ZanzanaClient.Addr, + Addr: cfg.ZanzanaClient.Addr, Token: cfg.ZanzanaClient.Token, TokenExchangeURL: cfg.ZanzanaClient.TokenExchangeURL, + TokenNamespace: cfg.ZanzanaClient.TokenNamespace, ServerCertFile: cfg.ZanzanaClient.ServerCertFile, } - return NewRemoteZanzanaClient(cfg.ZanzanaClient.TokenNamespace, zanzanaConfig) + return NewRemoteZanzanaClient(zanzanaConfig, reg) } type ZanzanaClientConfig struct { - URL string + Addr string Token string TokenExchangeURL string - ServerCertFile string TokenNamespace string + ServerCertFile string } // NewRemoteZanzanaClient creates a new Zanzana client that connects to remote Zanzana server. -func NewRemoteZanzanaClient(namespace string, cfg ZanzanaClientConfig) (zanzana.Client, error) { +func NewRemoteZanzanaClient(cfg ZanzanaClientConfig, reg prometheus.Registerer) (zanzana.Client, error) { tokenClient, err := authnlib.NewTokenExchangeClient(authnlib.TokenExchangeConfig{ Token: cfg.Token, TokenExchangeURL: cfg.TokenExchangeURL, @@ -139,18 +143,25 @@ func NewRemoteZanzanaClient(namespace string, cfg ZanzanaClientConfig) (zanzana. } } + authzRequestDuration := promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{ + Name: "authz_zanzana_client_request_duration_seconds", + Help: "Time spent executing requests to zanzana server.", + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 160, + NativeHistogramMinResetDuration: time.Hour, + }, []string{"operation", "status_code"}) + unaryInterceptors, streamInterceptors := instrument(authzRequestDuration, middleware.ReportGRPCStatusOption) + dialOptions := []grpc.DialOption{ grpc.WithTransportCredentials(transportCredentials), grpc.WithPerRPCCredentials( - NewGRPCTokenAuth( - AuthzServiceAudience, - namespace, - tokenClient, - ), + NewGRPCTokenAuth(AuthzServiceAudience, cfg.TokenNamespace, tokenClient), ), + grpc.WithChainUnaryInterceptor(unaryInterceptors...), + grpc.WithChainStreamInterceptor(streamInterceptors...), } - conn, err := grpc.NewClient(cfg.URL, dialOptions...) + conn, err := grpc.NewClient(cfg.Addr, dialOptions...) if err != nil { return nil, fmt.Errorf("failed to create zanzana client to remote server: %w", err) } diff --git a/pkg/services/authz/zanzana/common/info.go b/pkg/services/authz/zanzana/common/info.go index c17970ca1b3..4e4bbedc0b7 100644 --- a/pkg/services/authz/zanzana/common/info.go +++ b/pkg/services/authz/zanzana/common/info.go @@ -4,8 +4,12 @@ import ( "google.golang.org/protobuf/types/known/structpb" authzv1 "github.com/grafana/authlib/authz/proto/v1" + + dashboardV1 "github.com/grafana/grafana/apps/dashboard/pkg/apis/dashboard/v1beta1" folders "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" iamv0alpha1 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/services/accesscontrol" authzextv1 "github.com/grafana/grafana/pkg/services/authz/proto/v1" ) @@ -44,7 +48,8 @@ func getTypeInfo(group, resource string) (typeInfo, bool) { func NewResourceInfoFromCheck(r *authzv1.CheckRequest) ResourceInfo { typ, relations := getTypeAndRelations(r.GetGroup(), r.GetResource()) - return newResource( + + resource := newResource( typ, r.GetGroup(), r.GetResource(), @@ -53,6 +58,19 @@ func NewResourceInfoFromCheck(r *authzv1.CheckRequest) ResourceInfo { r.GetSubresource(), relations, ) + + // Special case for creating folders and resources in the root folder + if r.GetVerb() == utils.VerbCreate { + if resource.IsFolderResource() && resource.name == "" { + resource.name = accesscontrol.GeneralFolderUID + } else if resource.HasFolderSupport() && resource.folder == "" { + resource.folder = accesscontrol.GeneralFolderUID + } + + return resource + } + + return resource } func NewResourceInfoFromBatchItem(i *authzextv1.BatchCheckItem) ResourceInfo { @@ -164,3 +182,15 @@ func (r ResourceInfo) IsValidRelation(relation string) bool { func (r ResourceInfo) HasSubresource() bool { return r.subresource != "" } + +var resourcesWithFolderSupport = map[string]bool{ + dashboardV1.DashboardResourceInfo.GroupResource().Group: true, +} + +func (r ResourceInfo) HasFolderSupport() bool { + return resourcesWithFolderSupport[r.group] +} + +func (r ResourceInfo) IsFolderResource() bool { + return r.group == folders.FolderResourceInfo.GroupResource().Group +} diff --git a/pkg/services/authz/zanzana/common/tuple.go b/pkg/services/authz/zanzana/common/tuple.go index b1b6499dcd2..38f38fb90a7 100644 --- a/pkg/services/authz/zanzana/common/tuple.go +++ b/pkg/services/authz/zanzana/common/tuple.go @@ -58,6 +58,13 @@ const ( RelationGetPermissions string = "get_permissions" RelationSetPermissions string = "set_permissions" + RelationCanGet string = "can_get" + RelationCanCreate string = "can_create" + RelationCanUpdate string = "can_update" + RelationCanDelete string = "can_delete" + RelationCanGetPermissions string = "can_get_permissions" + RelationCanSetPermissions string = "can_set_permissions" + RelationSubresourceSetView string = "resource_" + RelationSetView RelationSubresourceSetEdit string = "resource_" + RelationSetEdit RelationSubresourceSetAdmin string = "resource_" + RelationSetAdmin @@ -134,6 +141,26 @@ var RelationToVerbMapping = map[string]string{ RelationSetPermissions: utils.VerbSetPermissions, } +// FolderPermissionRelation returns the optimized folder relation for permission management. +func FolderPermissionRelation(relation string) string { + switch relation { + case RelationGet: + return RelationCanGet + case RelationCreate: + return RelationCanCreate + case RelationUpdate: + return RelationCanUpdate + case RelationDelete: + return RelationCanDelete + case RelationGetPermissions: + return RelationCanGetPermissions + case RelationSetPermissions: + return RelationCanSetPermissions + default: + return relation + } +} + func IsGroupResourceRelation(relation string) bool { return isValidRelation(relation, RelationsGroupResource) } @@ -228,6 +255,9 @@ func TranslateToResourceTuple(subject string, action, kind, name string) (*openf } if name == "*" { + if m.group != "" && m.resource != "" { + return NewGroupResourceTuple(subject, m.relation, m.group, m.resource, m.subresource), true + } return NewGroupResourceTuple(subject, m.relation, translation.group, translation.resource, m.subresource), true } diff --git a/pkg/services/authz/zanzana/common/tuple_test.go b/pkg/services/authz/zanzana/common/tuple_test.go new file mode 100644 index 00000000000..ecb4d6e9dd1 --- /dev/null +++ b/pkg/services/authz/zanzana/common/tuple_test.go @@ -0,0 +1,89 @@ +package common + +import ( + "testing" + + openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/structpb" +) + +type translationTestCase struct { + testName string + subject string + action string + kind string + name string + expected *openfgav1.TupleKey +} + +func TestTranslateToResourceTuple(t *testing.T) { + tests := []translationTestCase{ + { + testName: "dashboards:read in folders", + subject: "user:1", + action: "dashboards:read", + kind: "folders", + name: "*", + expected: &openfgav1.TupleKey{ + User: "user:1", + Relation: "get", + Object: "group_resource:dashboard.grafana.app/dashboards", + }, + }, + { + testName: "dashboards:read for all dashboards", + subject: "user:1", + action: "dashboards:read", + kind: "dashboards", + name: "*", + expected: &openfgav1.TupleKey{ + User: "user:1", + Relation: "get", + Object: "group_resource:dashboard.grafana.app/dashboards", + }, + }, + { + testName: "dashboards:read for general folder", + subject: "user:1", + action: "dashboards:read", + kind: "folders", + name: "general", + expected: &openfgav1.TupleKey{ + User: "user:1", + Relation: "resource_get", + Object: "folder:general", + Condition: &openfgav1.RelationshipCondition{ + Name: "subresource_filter", + Context: &structpb.Struct{ + Fields: map[string]*structpb.Value{ + "subresources": structpb.NewListValue(&structpb.ListValue{ + Values: []*structpb.Value{structpb.NewStringValue("dashboard.grafana.app/dashboards")}, + }), + }, + }, + }, + }, + }, + { + testName: "folders:read", + subject: "user:1", + action: "folders:read", + kind: "folders", + name: "*", + expected: &openfgav1.TupleKey{ + User: "user:1", + Relation: "get", + Object: "group_resource:folder.grafana.app/folders", + }, + }, + } + + for _, test := range tests { + t.Run(test.testName, func(t *testing.T) { + tuple, ok := TranslateToResourceTuple(test.subject, test.action, test.kind, test.name) + require.True(t, ok) + require.EqualExportedValues(t, test.expected, tuple) + }) + } +} diff --git a/pkg/services/authz/zanzana/schema/schema_folder.fga b/pkg/services/authz/zanzana/schema/schema_folder.fga index b9b0a842de9..c55d1312f53 100644 --- a/pkg/services/authz/zanzana/schema/schema_folder.fga +++ b/pkg/services/authz/zanzana/schema/schema_folder.fga @@ -4,15 +4,21 @@ type folder relations define parent: [folder] - # Action sets - define view: [user, service-account, team#member, role#assignee] or edit or view from parent - define edit: [user, service-account, team#member, role#assignee] or admin or edit from parent + # Permission levels define admin: [user, service-account, team#member, role#assignee] or admin from parent + define edit: [user, service-account, team#member, role#assignee] or edit from parent + define view: [user, service-account, team#member, role#assignee] or view from parent + define get: [user, service-account, team#member, role#assignee] or get from parent + define create: [user, service-account, team#member, role#assignee] or create from parent + define update: [user, service-account, team#member, role#assignee] or update from parent + define delete: [user, service-account, team#member, role#assignee] or delete from parent + define get_permissions: [user, service-account, team#member, role#assignee] or get_permissions from parent + define set_permissions: [user, service-account, team#member, role#assignee] or set_permissions from parent - define get: [user, service-account, team#member, role#assignee] or view or get from parent - define create: [user, service-account, team#member, role#assignee] or edit or create from parent - define update: [user, service-account, team#member, role#assignee] or edit or update from parent - define delete: [user, service-account, team#member, role#assignee] or edit or delete from parent - - define get_permissions: [user, service-account, team#member, role#assignee] or admin or get_permissions from parent - define set_permissions: [user, service-account, team#member, role#assignee] or admin or set_permissions from parent + # Computed actions + define can_get: admin or edit or view or get + define can_create: admin or edit or create + define can_update: admin or edit or update + define can_delete: admin or edit or delete + define can_get_permissions: admin or get_permissions + define can_set_permissions: admin or set_permissions diff --git a/pkg/services/authz/zanzana/server/server_bench_test.go b/pkg/services/authz/zanzana/server/server_bench_test.go new file mode 100644 index 00000000000..98ec58560b0 --- /dev/null +++ b/pkg/services/authz/zanzana/server/server_bench_test.go @@ -0,0 +1,947 @@ +package server + +import ( + "context" + "fmt" + "math/rand" + "testing" + "time" + + authzv1 "github.com/grafana/authlib/authz/proto/v1" + openfgav1 "github.com/openfga/api/proto/openfga/v1" + "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/require" + + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/infra/log" + "github.com/grafana/grafana/pkg/infra/tracing" + authzextv1 "github.com/grafana/grafana/pkg/services/authz/proto/v1" + "github.com/grafana/grafana/pkg/services/authz/zanzana/common" + "github.com/grafana/grafana/pkg/services/authz/zanzana/store" + "github.com/grafana/grafana/pkg/services/sqlstore" + "github.com/grafana/grafana/pkg/setting" +) + +const ( + benchNamespace = "default" + + // Folder tree parameters + foldersPerLevel = 3 + folderDepth = 7 + + // Other data generation parameters + numResources = 50000 + numUsers = 1000 + numTeams = 100 + + // Timeout for List operations + listTimeout = 30 * time.Second + + // Resource type constants for benchmarks + benchDashboardGroup = "dashboard.grafana.app" + benchDashboardResource = "dashboards" + benchFolderGroup = "folder.grafana.app" + benchFolderResource = "folders" + + // BenchmarkBatchCheck measures the performance of BatchCheck requests with 50 items per batch. + batchCheckSize = 50 +) + +// benchmarkData holds all the generated test data for benchmarks +type benchmarkData struct { + folders []string // folder UIDs + folderDepths map[string]int // folder UID -> depth level + folderParents map[string]string // folder UID -> parent UID + folderDescendants map[string]int // folder UID -> number of descendants (including self) + foldersByDepth [][]string // folders grouped by depth level + resources []string // resource names + resourceFolders map[string]string // resource name -> folder UID + users []string // user identifiers (e.g., "user:1") + teams []string // team identifiers (e.g., "team:1") + + // Pre-computed test scenarios + deepestFolder string // folder at max depth for worst-case tests + midDepthFolder string // folder at depth/2 + shallowFolder string // folder at depth 1 + rootFolder string // root level folder (depth 0) + largestRootFolder string // root folder with most descendants + largestRootDescCount int // number of descendants in largestRootFolder + maxDepth int // maximum depth in the tree +} + +// generateFolderHierarchy creates a balanced tree of folders. +// Each folder has `childrenPerFolder` children, up to `depth` levels deep. +func generateFolderHierarchy(childrenPerFolder, depth int) ([]*openfgav1.TupleKey, *benchmarkData) { + // Calculate total folders: childrenPerFolder + childrenPerFolder^2 + ... + childrenPerFolder^(depth+1) + totalFolders := 0 + levelSize := childrenPerFolder + for d := 0; d <= depth; d++ { + totalFolders += levelSize + levelSize *= childrenPerFolder + } + + data := &benchmarkData{ + folders: make([]string, 0, totalFolders), + folderDepths: make(map[string]int), + folderParents: make(map[string]string), + folderDescendants: make(map[string]int), + } + tuples := make([]*openfgav1.TupleKey, 0, totalFolders) + + folderIdx := 0 + + // Track folders at each level for parent assignment + levelFolders := make([][]string, depth+1) + for i := range levelFolders { + levelFolders[i] = make([]string, 0) + } + + // Create root level folders (depth 0) + for i := 0; i < childrenPerFolder; i++ { + folderUID := fmt.Sprintf("folder-%d", folderIdx) + data.folders = append(data.folders, folderUID) + data.folderDepths[folderUID] = 0 + levelFolders[0] = append(levelFolders[0], folderUID) + folderIdx++ + } + + // Create folders at each subsequent depth level + for d := 1; d <= depth; d++ { + parentFolders := levelFolders[d-1] + + // Each parent gets exactly childrenPerFolder children + for _, parentUID := range parentFolders { + for j := 0; j < childrenPerFolder; j++ { + folderUID := fmt.Sprintf("folder-%d", folderIdx) + + data.folders = append(data.folders, folderUID) + data.folderDepths[folderUID] = d + data.folderParents[folderUID] = parentUID + levelFolders[d] = append(levelFolders[d], folderUID) + + // Create parent relationship tuple + tuples = append(tuples, common.NewFolderParentTuple(folderUID, parentUID)) + folderIdx++ + } + } + } + + // Set reference folders for different depth scenarios + data.rootFolder = levelFolders[0][0] + data.shallowFolder = levelFolders[0][0] + if len(levelFolders[1]) > 0 { + data.shallowFolder = levelFolders[1][0] + } + midDepth := depth / 2 + if len(levelFolders[midDepth]) > 0 { + data.midDepthFolder = levelFolders[midDepth][0] + } + // Deepest folder + if len(levelFolders[depth]) > 0 { + data.deepestFolder = levelFolders[depth][0] + } + + // Calculate descendant counts for each folder (bottom-up) + // Initialize all folders with count of 1 (self) + for _, folder := range data.folders { + data.folderDescendants[folder] = 1 + } + // Process folders from deepest to shallowest, accumulating descendant counts + for d := depth; d >= 0; d-- { + for _, folder := range levelFolders[d] { + if parent, hasParent := data.folderParents[folder]; hasParent { + data.folderDescendants[parent] += data.folderDescendants[folder] + } + } + } + + // Find root folder with most descendants + for _, rootFolder := range levelFolders[0] { + count := data.folderDescendants[rootFolder] + if count > data.largestRootDescCount { + data.largestRootDescCount = count + data.largestRootFolder = rootFolder + } + } + + // Store folders by depth for depth-based testing + data.foldersByDepth = levelFolders + data.maxDepth = depth + + return tuples, data +} + +// generateResources creates resources distributed across folders +func generateResources(data *benchmarkData, numResources int) []*openfgav1.TupleKey { + data.resources = make([]string, numResources) + data.resourceFolders = make(map[string]string, numResources) + + // Distribute resources across folders + for i := 0; i < numResources; i++ { + resourceName := fmt.Sprintf("resource-%d", i) + folderIdx := i % len(data.folders) + folderUID := data.folders[folderIdx] + + data.resources[i] = resourceName + data.resourceFolders[resourceName] = folderUID + } + + // Note: We don't create tuples for resources themselves, + // permissions are assigned to users/teams on folders or directly on resources + return nil +} + +// generateUsers creates user identifiers +func generateUsers(data *benchmarkData, numUsers int) { + data.users = make([]string, numUsers) + for i := 0; i < numUsers; i++ { + data.users[i] = fmt.Sprintf("user:%d", i) + } +} + +// generateTeams creates team identifiers +func generateTeams(data *benchmarkData, numTeams int) { + data.teams = make([]string, numTeams) + for i := 0; i < numTeams; i++ { + data.teams[i] = fmt.Sprintf("team:%d", i) + } +} + +// generatePermissionTuples creates various permission assignments for benchmarking. +// Users are distributed across 7 patterns: global, root folder, mid-depth folder, +// folder-scoped resource, direct resource, team-based, and no permissions. +const numPermissionPatterns = 7 + +func generatePermissionTuples(data *benchmarkData) []*openfgav1.TupleKey { + tuples := make([]*openfgav1.TupleKey, 0) + + // Distribute users across different permission patterns + usersPerPattern := len(data.users) / numPermissionPatterns + + // Pattern 1: Users with GroupResource permission (all access) + // Users 0 to usersPerPattern-1 + for i := 0; i < usersPerPattern; i++ { + tuples = append(tuples, common.NewGroupResourceTuple( + data.users[i], + common.RelationGet, + benchDashboardGroup, + benchDashboardResource, + "", + )) + } + + // Pattern 2: Users with folder-level permission on root folders + // Users usersPerPattern to 2*usersPerPattern-1 + for i := usersPerPattern; i < 2*usersPerPattern; i++ { + folderIdx := (i - usersPerPattern) % len(data.folders) + // Only assign to root-level folders for this pattern + for j := folderIdx; j < len(data.folders); j++ { + if data.folderDepths[data.folders[j]] == 0 { + tuples = append(tuples, common.NewFolderTuple( + data.users[i], + common.RelationSetView, + data.folders[j], + )) + break + } + } + } + + // Pattern 3: Users with folder-level permission on mid-depth folders + // Use relative depth range: 1/3 to 2/3 of max depth + // Use "view" relation which grants get through the optimized schema + minMidDepth := data.maxDepth / 3 + maxMidDepth := 2 * data.maxDepth / 3 + if maxMidDepth < minMidDepth { + maxMidDepth = minMidDepth + } + // Collect folders in the mid-depth range + var midDepthFolders []string + for d := minMidDepth; d <= maxMidDepth; d++ { + if d < len(data.foldersByDepth) { + midDepthFolders = append(midDepthFolders, data.foldersByDepth[d]...) + } + } + // Fall back to root folders if no mid-depth folders exist + if len(midDepthFolders) == 0 { + midDepthFolders = data.foldersByDepth[0] + } + for i := 2 * usersPerPattern; i < 3*usersPerPattern; i++ { + folderIdx := (i - 2*usersPerPattern) % len(midDepthFolders) + tuples = append(tuples, common.NewFolderTuple( + data.users[i], + common.RelationSetView, + midDepthFolders[folderIdx], + )) + } + + // Pattern 4: Users with folder-scoped resource permission + for i := 3 * usersPerPattern; i < 4*usersPerPattern; i++ { + folderIdx := (i - 3*usersPerPattern) % len(data.folders) + tuples = append(tuples, common.NewFolderResourceTuple( + data.users[i], + common.RelationGet, + benchDashboardGroup, + benchDashboardResource, + "", + data.folders[folderIdx], + )) + } + + // Pattern 5: Users with direct resource permission + for i := 4 * usersPerPattern; i < 5*usersPerPattern; i++ { + resourceIdx := (i - 4*usersPerPattern) % len(data.resources) + tuples = append(tuples, common.NewResourceTuple( + data.users[i], + common.RelationGet, + benchDashboardGroup, + benchDashboardResource, + "", + data.resources[resourceIdx], + )) + } + + // Pattern 6: Team memberships and team permissions + // First, add users to teams + for i := 5 * usersPerPattern; i < 6*usersPerPattern && i < len(data.users); i++ { + teamIdx := (i - 5*usersPerPattern) % len(data.teams) + tuples = append(tuples, common.NewTypedTuple( + common.TypeTeam, + data.users[i], + common.RelationTeamMember, + fmt.Sprintf("%d", teamIdx), + )) + } + // Then, give teams folder permissions + // Use "view" relation which grants get through the optimized schema + for i := 0; i < len(data.teams); i++ { + folderIdx := i % len(data.folders) + teamMember := fmt.Sprintf("team:%d#member", i) + tuples = append(tuples, common.NewFolderTuple( + teamMember, + common.RelationSetView, + data.folders[folderIdx], + )) + } + + // Pattern 7: Users with no permissions (remaining users) + // These users don't get any tuples - they're for testing denial cases + + return tuples +} + +// setupBenchmarkServer creates a server with the benchmark data loaded +func setupBenchmarkServer(b *testing.B) (*Server, *benchmarkData) { + b.Helper() + if testing.Short() { + b.Skip("skipping benchmark in short mode") + } + + cfg := setting.NewCfg() + testStore := sqlstore.NewTestStore(b, sqlstore.WithCfg(cfg)) + + openFGAStore, err := store.NewEmbeddedStore(cfg, testStore, log.NewNopLogger()) + require.NoError(b, err) + + openfga, err := NewOpenFGAServer(cfg.ZanzanaServer, openFGAStore) + require.NoError(b, err) + + srv, err := NewServer(cfg.ZanzanaServer, openfga, log.NewNopLogger(), tracing.NewNoopTracerService(), prometheus.NewRegistry()) + require.NoError(b, err) + + // Generate test data + b.Log("Generating folder hierarchy...") + folderTuples, data := generateFolderHierarchy(foldersPerLevel, folderDepth) + + b.Log("Generating resources...") + generateResources(data, numResources) + + b.Log("Generating users...") + generateUsers(data, numUsers) + + b.Log("Generating teams...") + generateTeams(data, numTeams) + + b.Log("Generating permission tuples...") + permTuples := generatePermissionTuples(data) + + // Add special user with permission on largest root folder (for >1000 folder test) + // Use "view" relation which grants get through the optimized schema + largeRootUserTuple := common.NewFolderTuple( + "user:large-root-access", + common.RelationSetView, + data.largestRootFolder, + ) + permTuples = append(permTuples, largeRootUserTuple) + + // Add users with permissions at each depth level for depth-based testing + // Use "view" relation which grants get through the optimized schema + for depth := 0; depth <= data.maxDepth; depth++ { + if len(data.foldersByDepth[depth]) == 0 { + continue + } + folder := data.foldersByDepth[depth][0] + user := fmt.Sprintf("user:depth-%d-access", depth) + permTuples = append(permTuples, common.NewFolderTuple(user, common.RelationSetView, folder)) + } + + // Combine all tuples + allTuples := append(folderTuples, permTuples...) + + b.Logf("Total tuples to write: %d", len(allTuples)) + + // Get store info + ctx := newContextWithNamespace() + storeInf, err := srv.getStoreInfo(ctx, benchNamespace) + require.NoError(b, err) + + // Write tuples in batches (OpenFGA limits to 100 per write) + batchSize := 100 + for i := 0; i < len(allTuples); i += batchSize { + end := i + batchSize + if end > len(allTuples) { + end = len(allTuples) + } + batch := allTuples[i:end] + + _, err = srv.openfga.Write(ctx, &openfgav1.WriteRequest{ + StoreId: storeInf.ID, + AuthorizationModelId: storeInf.ModelID, + Writes: &openfgav1.WriteRequestWrites{ + TupleKeys: batch, + OnDuplicate: "ignore", + }, + }) + require.NoError(b, err) + + if (i/batchSize)%100 == 0 { + b.Logf("Written %d/%d tuples", end, len(allTuples)) + } + } + + b.Logf("Benchmark data setup complete: %d folders, %d resources, %d users, %d teams", + len(data.folders), len(data.resources), len(data.users), len(data.teams)) + b.Logf("Largest root folder: %s with %d descendants", data.largestRootFolder, data.largestRootDescCount) + + return srv, data +} + +// BenchmarkCheck measures the performance of Check requests +func BenchmarkCheck(b *testing.B) { + srv, data := setupBenchmarkServer(b) + ctx := newContextWithNamespace() + + // Helper to create check requests + newCheckReq := func(subject, verb, group, resource, folder, name string) *authzv1.CheckRequest { + return &authzv1.CheckRequest{ + Namespace: benchNamespace, + Subject: subject, + Verb: verb, + Group: group, + Resource: resource, + Folder: folder, + Name: name, + } + } + + usersPerPattern := len(data.users) / 7 + + b.Run("GroupResourceDirect", func(b *testing.B) { + // User with group_resource permission - should have access to everything + user := data.users[0] // First user has GroupResource permission + resource := data.resources[rand.Intn(len(data.resources))] + folder := data.resourceFolders[resource] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + if !res.GetAllowed() { + b.Fatal("expected access to be allowed") + } + } + }) + + // Test folder inheritance at each depth level (0 to maxDepth) + // User has permission on ROOT folder (depth 0), we check access at each deeper level + rootUser := "user:depth-0-access" // has view permission on root folder + for depth := 0; depth <= data.maxDepth; depth++ { + depth := depth // capture for closure + if len(data.foldersByDepth[depth]) == 0 { + continue + } + b.Run(fmt.Sprintf("FolderInheritance/Depth%d", depth), func(b *testing.B) { + resource := data.resources[0] + folder := data.foldersByDepth[depth][0] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(rootUser, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + _ = res.GetAllowed() + } + }) + } + + b.Run("FolderResourceScoped", func(b *testing.B) { + // User with folder-scoped resource permission + user := data.users[3*usersPerPattern] + folderIdx := 0 + folder := data.folders[folderIdx] + resource := data.resources[folderIdx] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + _ = res.GetAllowed() + } + }) + + b.Run("DirectResource", func(b *testing.B) { + // User with direct resource permission + user := data.users[4*usersPerPattern] + resourceIdx := 0 + resource := data.resources[resourceIdx] + folder := data.resourceFolders[resource] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + _ = res.GetAllowed() + } + }) + + b.Run("TeamMembership", func(b *testing.B) { + // User who is a team member, team has folder permission + user := data.users[5*usersPerPattern] + teamIdx := 0 + folderIdx := teamIdx % len(data.folders) + folder := data.folders[folderIdx] + resource := data.resources[folderIdx%len(data.resources)] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + _ = res.GetAllowed() + } + }) + + b.Run("NoAccess", func(b *testing.B) { + // User with no permissions - tests denial path + user := data.users[len(data.users)-1] // Last user has no permissions + resource := data.resources[0] + folder := data.resourceFolders[resource] + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource, folder, resource)) + if err != nil { + b.Fatal(err) + } + if res.GetAllowed() { + b.Fatal("expected access to be denied") + } + } + }) + + b.Run("FolderCheck", func(b *testing.B) { + // Direct folder access check + user := data.users[usersPerPattern] + folder := data.rootFolder + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.Check(ctx, newCheckReq(user, utils.VerbGet, benchFolderGroup, benchFolderResource, "", folder)) + if err != nil { + b.Fatal(err) + } + _ = res.GetAllowed() + } + }) +} + +func BenchmarkBatchCheck(b *testing.B) { + srv, data := setupBenchmarkServer(b) + ctx := newContextWithNamespace() + + // Helper to create batch check requests + newBatchCheckReq := func(subject string, items []*authzextv1.BatchCheckItem) *authzextv1.BatchCheckRequest { + return &authzextv1.BatchCheckRequest{ + Namespace: benchNamespace, + Subject: subject, + Items: items, + } + } + + // Helper to create batch items for resources in folders + createBatchItems := func(resources []string, resourceFolders map[string]string) []*authzextv1.BatchCheckItem { + items := make([]*authzextv1.BatchCheckItem, 0, batchCheckSize) + for i := 0; i < batchCheckSize && i < len(resources); i++ { + resource := resources[i] + items = append(items, &authzextv1.BatchCheckItem{ + Verb: utils.VerbGet, + Group: benchDashboardGroup, + Resource: benchDashboardResource, + Name: resource, + Folder: resourceFolders[resource], + }) + } + return items + } + + // Helper to create batch items for folders at a specific depth + createFolderBatchItems := func(folders []string, depth int, folderDepths map[string]int) []*authzextv1.BatchCheckItem { + items := make([]*authzextv1.BatchCheckItem, 0, batchCheckSize) + for _, folder := range folders { + if folderDepths[folder] == depth && len(items) < batchCheckSize { + items = append(items, &authzextv1.BatchCheckItem{ + Verb: utils.VerbGet, + Group: benchDashboardGroup, + Resource: benchDashboardResource, + Name: fmt.Sprintf("resource-in-%s", folder), + Folder: folder, + }) + } + } + // Fill remaining slots if needed + for len(items) < batchCheckSize && len(folders) > 0 { + folder := folders[len(items)%len(folders)] + items = append(items, &authzextv1.BatchCheckItem{ + Verb: utils.VerbGet, + Group: benchDashboardGroup, + Resource: benchDashboardResource, + Name: fmt.Sprintf("resource-%d", len(items)), + Folder: folder, + }) + } + return items + } + + usersPerPattern := len(data.users) / numPermissionPatterns + + b.Run("GroupResourceDirect", func(b *testing.B) { + // User with group_resource permission - should have access to everything + user := data.users[0] + items := createBatchItems(data.resources, data.resourceFolders) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("FolderInheritance/Depth1", func(b *testing.B) { + // User with folder permission on shallow folder + user := data.users[usersPerPattern] + items := createFolderBatchItems(data.folders, 1, data.folderDepths) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("FolderInheritance/Depth4", func(b *testing.B) { + // User with folder permission on mid-depth folder + user := data.users[2*usersPerPattern] + items := createFolderBatchItems(data.folders, 4, data.folderDepths) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("FolderInheritance/Depth7", func(b *testing.B) { + // Check access on deepest folders (worst case for inheritance traversal) + user := data.users[usersPerPattern] + items := createFolderBatchItems(data.folders, data.maxDepth, data.folderDepths) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("DirectResource", func(b *testing.B) { + // User with direct resource permission + user := data.users[4*usersPerPattern] + items := createBatchItems(data.resources, data.resourceFolders) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("TeamMembership", func(b *testing.B) { + // User who is a team member, team has folder permission + user := data.users[5*usersPerPattern] + items := createBatchItems(data.resources, data.resourceFolders) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("NoAccess", func(b *testing.B) { + // User with no permissions - tests denial path + user := data.users[len(data.users)-1] + items := createBatchItems(data.resources, data.resourceFolders) + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) + + b.Run("MixedFolders", func(b *testing.B) { + // Batch of items across different folder depths + user := data.users[usersPerPattern] + items := make([]*authzextv1.BatchCheckItem, 0, batchCheckSize) + for i := 0; i < batchCheckSize; i++ { + folder := data.folders[i%len(data.folders)] + items = append(items, &authzextv1.BatchCheckItem{ + Verb: utils.VerbGet, + Group: benchDashboardGroup, + Resource: benchDashboardResource, + Name: fmt.Sprintf("resource-%d", i), + Folder: folder, + }) + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + res, err := srv.BatchCheck(ctx, newBatchCheckReq(user, items)) + if err != nil { + b.Fatal(err) + } + _ = res.Groups + } + }) +} + +// BenchmarkList measures the performance of List requests (Compile equivalent) +func BenchmarkList(b *testing.B) { + srv, data := setupBenchmarkServer(b) + baseCtx := newContextWithNamespace() + + // Helper to create list requests + newListReq := func(subject, verb, group, resource string) *authzv1.ListRequest { + return &authzv1.ListRequest{ + Namespace: benchNamespace, + Subject: subject, + Verb: verb, + Group: group, + Resource: resource, + } + } + + // Helper to create context with timeout + ctxWithTimeout := func() (context.Context, context.CancelFunc) { + return context.WithTimeout(baseCtx, listTimeout) + } + + usersPerPattern := len(data.users) / 7 + + b.Run("AllAccess", func(b *testing.B) { + // User with group_resource permission - should return All=true quickly + user := data.users[0] + b.Logf("Test: User with group_resource permission (access to ALL dashboards)") + b.Logf("Expected: All=true returned immediately without ListObjects call") + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource)) + cancel() + if err != nil { + b.Fatalf("Error: %v", err) + } + if !res.GetAll() { + b.Fatal("expected All=true for user with group_resource permission") + } + } + }) + + b.Run("FolderScoped", func(b *testing.B) { + // User with folder permissions - should return folder list + user := data.users[usersPerPattern] + b.Logf("Test: User with direct folder permission on a single folder") + b.Logf("Expected: Returns list of folders user has access to") + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource)) + cancel() + if err != nil { + b.Fatalf("Error: %v", err) + } + if i == 0 { + b.Logf("Result: %d folders, %d items, All=%v", len(res.GetFolders()), len(res.GetItems()), res.GetAll()) + } + } + }) + + b.Run("DirectResources", func(b *testing.B) { + // User with direct resource permissions - should return items list + user := data.users[4*usersPerPattern] + b.Logf("Test: User with direct permission on specific resources") + b.Logf("Expected: Returns list of specific resources user has access to") + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource)) + cancel() + if err != nil { + b.Fatalf("Error: %v", err) + } + if i == 0 { + b.Logf("Result: %d folders, %d items, All=%v", len(res.GetFolders()), len(res.GetItems()), res.GetAll()) + } + } + }) + + b.Run("NoAccess", func(b *testing.B) { + // User with no permissions - should return empty results + user := data.users[len(data.users)-1] + b.Logf("Test: User with NO permissions (denial case)") + b.Logf("Expected: Empty results") + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchDashboardGroup, benchDashboardResource)) + cancel() + if err != nil { + b.Fatalf("Error: %v", err) + } + if i == 0 { + b.Logf("Result: %d folders, %d items, All=%v", len(res.GetFolders()), len(res.GetItems()), res.GetAll()) + } + } + }) + + b.Run("LargeRootFolder", func(b *testing.B) { + // User with access to root folder that has many descendants + user := "user:large-root-access" + b.Logf("Test: User with permission on ROOT folder (folder-0)") + b.Logf("Root folder %s has %d total descendants", data.largestRootFolder, data.largestRootDescCount) + b.Logf("Expected: ListObjects should return folders through inheritance") + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + start := time.Now() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchFolderGroup, benchFolderResource)) + elapsed := time.Since(start) + cancel() + if err != nil { + b.Fatalf("Error after %v: %v", elapsed, err) + } + if i == 0 { + b.Logf("Result: %d folders returned in %v (descendants: %d)", + len(res.GetItems()), elapsed, data.largestRootDescCount) + } + } + }) + + // Test List at various folder depths to find breaking point + b.Run("ByDepth", func(b *testing.B) { + b.Logf("Testing List performance at various folder depths (timeout: %v)", listTimeout) + b.Logf("Tree structure: %d folders per level, %d max depth", foldersPerLevel, data.maxDepth) + + for depth := 0; depth <= data.maxDepth; depth++ { + if len(data.foldersByDepth[depth]) == 0 { + continue + } + + folder := data.foldersByDepth[depth][0] + descendants := data.folderDescendants[folder] + user := fmt.Sprintf("user:depth-%d-access", depth) + + b.Run(fmt.Sprintf("Depth%d_%dDescendants", depth, descendants), func(b *testing.B) { + b.Logf("Test: User with permission on folder at depth %d", depth) + b.Logf("Folder: %s, Descendants: %d", folder, descendants) + + // First, do a single timed run to report + ctx, cancel := ctxWithTimeout() + start := time.Now() + res, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchFolderGroup, benchFolderResource)) + elapsed := time.Since(start) + cancel() + + if err != nil { + b.Logf("FAILED after %v: %v", elapsed, err) + if elapsed >= listTimeout { + b.Logf("TIMEOUT: List took longer than %v", listTimeout) + } + b.Skip("Skipping benchmark iterations due to error") + return + } + + b.Logf("Result: %d folders in %v", len(res.GetItems()), elapsed) + + if elapsed > 5*time.Second { + b.Logf("WARNING: Single List took %v, skipping benchmark iterations", elapsed) + b.Skip("Too slow for benchmark iterations") + return + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + ctx, cancel := ctxWithTimeout() + _, err := srv.List(ctx, newListReq(user, utils.VerbGet, benchFolderGroup, benchFolderResource)) + cancel() + if err != nil { + b.Fatalf("Error: %v", err) + } + } + }) + } + }) +} diff --git a/pkg/services/authz/zanzana/server/server_check.go b/pkg/services/authz/zanzana/server/server_check.go index 916c84e5c0a..2f49641f17f 100644 --- a/pkg/services/authz/zanzana/server/server_check.go +++ b/pkg/services/authz/zanzana/server/server_check.go @@ -126,8 +126,14 @@ func (s *Server) checkTyped(ctx context.Context, subject, relation string, resou return &authzv1.CheckResponse{Allowed: false}, nil } + // Use optimized folder permission relations for permission management + checkRelation := relation + if resource.Type() == common.TypeFolder { + checkRelation = common.FolderPermissionRelation(relation) + } + // Check if subject has direct access to resource - res, err := s.openfgaCheck(ctx, store, subject, relation, resourceIdent, contextuals, nil) + res, err := s.openfgaCheck(ctx, store, subject, checkRelation, resourceIdent, contextuals, nil) if err != nil { return nil, err } @@ -143,14 +149,15 @@ func (s *Server) checkGeneric(ctx context.Context, subject, relation string, res defer span.End() var ( - folderIdent = resource.FolderIdent() - resourceCtx = resource.Context() - folderRelation = common.SubresourceRelation(relation) + folderIdent = resource.FolderIdent() + resourceCtx = resource.Context() + folderRelation = common.SubresourceRelation(relation) + folderCheckRelation = common.FolderPermissionRelation(relation) ) if folderIdent != "" && isFolderPermissionBasedResource(resource.GroupResource()) { // Check if resource inherits permissions from the folder (like dashboards in a folder) - res, err := s.openfgaCheck(ctx, store, subject, relation, folderIdent, contextuals, resourceCtx) + res, err := s.openfgaCheck(ctx, store, subject, folderCheckRelation, folderIdent, contextuals, resourceCtx) if err != nil { return nil, err } diff --git a/pkg/services/authz/zanzana/server/server_check_test.go b/pkg/services/authz/zanzana/server/server_check_test.go index 59a192fe6a0..d8e8fa01526 100644 --- a/pkg/services/authz/zanzana/server/server_check_test.go +++ b/pkg/services/authz/zanzana/server/server_check_test.go @@ -212,4 +212,16 @@ func testCheck(t *testing.T, server *Server) { require.NoError(t, err) assert.True(t, res.GetAllowed(), "user should be able to view dashboards in folder 6") }) + + t.Run("user:18 should be able to create folder in root folder", func(t *testing.T) { + res, err := server.Check(newContextWithNamespace(), newReq("user:18", utils.VerbCreate, folderGroup, folderResource, "", "", "")) + require.NoError(t, err) + assert.Equal(t, true, res.GetAllowed()) + }) + + t.Run("user:18 should be able to create dashboard in root folder", func(t *testing.T) { + res, err := server.Check(newContextWithNamespace(), newReq("user:18", utils.VerbCreate, dashboardGroup, dashboardResource, "", "", "")) + require.NoError(t, err) + assert.Equal(t, true, res.GetAllowed()) + }) } diff --git a/pkg/services/authz/zanzana/server/server_list.go b/pkg/services/authz/zanzana/server/server_list.go index 216e8df933e..9734f186d2a 100644 --- a/pkg/services/authz/zanzana/server/server_list.go +++ b/pkg/services/authz/zanzana/server/server_list.go @@ -85,6 +85,12 @@ func (s *Server) listTyped(ctx context.Context, subject, relation string, resour resourceCtx = resource.Context() ) + // Use optimized folder permission relations for permission management + listRelation := relation + if resource.Type() == common.TypeFolder { + listRelation = common.FolderPermissionRelation(relation) + } + var items []string if resource.HasSubresource() && common.IsSubresourceRelation(subresourceRelation) { // List requested subresources @@ -110,7 +116,7 @@ func (s *Server) listTyped(ctx context.Context, subject, relation string, resour StoreId: store.ID, AuthorizationModelId: store.ModelID, Type: resource.Type(), - Relation: relation, + Relation: listRelation, User: subject, ContextualTuples: contextuals, }) @@ -129,8 +135,9 @@ func (s *Server) listGeneric(ctx context.Context, subject, relation string, reso defer span.End() var ( - folderRelation = common.SubresourceRelation(relation) - resourceCtx = resource.Context() + folderRelation = common.SubresourceRelation(relation) + folderListRelation = common.FolderPermissionRelation(relation) // Optimized for permission management + resourceCtx = resource.Context() ) // 1. List all folders subject has access to resource type in @@ -159,7 +166,7 @@ func (s *Server) listGeneric(ctx context.Context, subject, relation string, reso StoreId: store.ID, AuthorizationModelId: store.ModelID, Type: common.TypeFolder, - Relation: relation, + Relation: folderListRelation, User: subject, Context: resourceCtx, ContextualTuples: contextuals, diff --git a/pkg/services/authz/zanzana/server/server_test.go b/pkg/services/authz/zanzana/server/server_test.go index 63cf8ee2a50..3f3a7e2cad6 100644 --- a/pkg/services/authz/zanzana/server/server_test.go +++ b/pkg/services/authz/zanzana/server/server_test.go @@ -71,6 +71,8 @@ func setup(t *testing.T, srv *Server) *Server { common.NewTypedResourceTuple("user:15", common.RelationGet, common.TypeUser, userGroup, userResource, statusSubresource, "1"), common.NewTypedResourceTuple("user:16", common.RelationGet, common.TypeServiceAccount, serviceAccountGroup, serviceAccountResource, statusSubresource, "1"), common.NewFolderTuple("user:17", common.RelationSetView, "4"), + common.NewFolderTuple("user:18", common.RelationCreate, "general"), + common.NewFolderResourceTuple("user:18", common.RelationCreate, dashboardGroup, dashboardResource, "", "general"), } return setupOpenFGADatabase(t, srv, tuples) diff --git a/pkg/services/dashboards/dashboard.go b/pkg/services/dashboards/dashboard.go index 0334cfc8990..fd30728aa35 100644 --- a/pkg/services/dashboards/dashboard.go +++ b/pkg/services/dashboards/dashboard.go @@ -44,6 +44,11 @@ type DashboardService interface { GetDashboardsByLibraryPanelUID(ctx context.Context, libraryPanelUID string, orgID int64) ([]*DashboardRef, error) } +type DashboardAccessService interface { + // The user as access to {VERB} the requested dashboard + HasDashboardAccess(ctx context.Context, user identity.Requester, verb string, namespace string, name string) (bool, error) +} + type PermissionsRegistrationService interface { RegisterDashboardPermissions(service accesscontrol.DashboardPermissionsService) diff --git a/pkg/services/dashboards/dashboard_service_mock.go b/pkg/services/dashboards/dashboard_service_mock.go index d20a9525622..f5ba0e096dc 100644 --- a/pkg/services/dashboards/dashboard_service_mock.go +++ b/pkg/services/dashboards/dashboard_service_mock.go @@ -5,9 +5,10 @@ package dashboards import ( context "context" - identity "github.com/grafana/grafana/pkg/apimachinery/identity" mock "github.com/stretchr/testify/mock" + identity "github.com/grafana/grafana/pkg/apimachinery/identity" + model "github.com/grafana/grafana/pkg/services/search/model" unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -529,6 +530,11 @@ func (_m *FakeDashboardService) ValidateDashboardRefreshInterval(minRefreshInter return r0 } +// CanViewDashboard uses the access control service to check if the requested user can see a dashboard +func (_m *FakeDashboardService) HasDashboardAccess(ctx context.Context, user identity.Requester, verb string, namespace string, name string) (bool, error) { + return true, nil +} + // NewFakeDashboardService creates a new instance of FakeDashboardService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewFakeDashboardService(t interface { diff --git a/pkg/services/dashboards/models.go b/pkg/services/dashboards/models.go index 3c661ee6b9c..c68263db693 100644 --- a/pkg/services/dashboards/models.go +++ b/pkg/services/dashboards/models.go @@ -304,8 +304,15 @@ type DeleteDashboardCommand struct { RemovePermissions bool } +type ProvisioningConfig struct { + Name string + OrgID int64 + Folder string + AllowUIUpdates bool +} + type DeleteOrphanedProvisionedDashboardsCommand struct { - ReaderNames []string + Config []ProvisioningConfig } type DashboardProvisioningSearchResults struct { @@ -405,6 +412,8 @@ type DashboardSearchProjection struct { FolderTitle string SortMeta int64 Tags []string + ManagedBy utils.ManagerKind + ManagerId string Deleted *time.Time } diff --git a/pkg/services/dashboards/service/dashboard_service.go b/pkg/services/dashboards/service/dashboard_service.go index b63b4a40f96..e105aaa3325 100644 --- a/pkg/services/dashboards/service/dashboard_service.go +++ b/pkg/services/dashboards/service/dashboard_service.go @@ -67,6 +67,7 @@ var ( _ dashboards.DashboardService = (*DashboardServiceImpl)(nil) _ dashboards.DashboardProvisioningService = (*DashboardServiceImpl)(nil) _ dashboards.PluginService = (*DashboardServiceImpl)(nil) + _ dashboards.DashboardAccessService = (*DashboardServiceImpl)(nil) daysInTrash = 24 * 30 * time.Hour tracer = otel.Tracer("github.com/grafana/grafana/pkg/services/dashboards/service") @@ -100,6 +101,38 @@ type DashboardServiceImpl struct { dashboardPermissionsReady chan struct{} } +// CanViewDashboard uses the access control service to check if the requested user can see a dashboard +func (dr *DashboardServiceImpl) HasDashboardAccess(ctx context.Context, user identity.Requester, verb string, namespace string, name string) (bool, error) { + ns, err := claims.ParseNamespace(namespace) + if err != nil { + return false, err + } + dash, err := dr.GetDashboard(ctx, &dashboards.GetDashboardQuery{ + UID: name, + OrgID: ns.OrgID, + }) + if err != nil || dash == nil { + return false, nil + } + var action string + switch verb { + case utils.VerbGet: + action = dashboards.ActionDashboardsRead + case utils.VerbUpdate: + action = dashboards.ActionDashboardsWrite + default: + return false, fmt.Errorf("unsupported verb") + } + + evaluator := accesscontrol.EvalPermission(action, + dashboards.ScopeDashboardsProvider.GetResourceScopeUID(name)) + canView, err := dr.ac.Evaluate(ctx, user, evaluator) + if err != nil || !canView { + return false, nil + } + return true, nil +} + func (dr *DashboardServiceImpl) startK8sDeletedDashboardsCleanupJob(ctx context.Context) chan struct{} { done := make(chan struct{}) go func() { @@ -877,24 +910,32 @@ func (dr *DashboardServiceImpl) waitForSearchQuery(ctx context.Context, query *d } func (dr *DashboardServiceImpl) DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *dashboards.DeleteOrphanedProvisionedDashboardsCommand) error { - // cleanup duplicate provisioned dashboards first (this will have the same name and external_id) - // note: only works in modes 1-3 - if err := dr.DeleteDuplicateProvisionedDashboards(ctx); err != nil { - dr.log.Error("Failed to delete duplicate provisioned dashboards", "error", err) - } - // check each org for orphaned provisioned dashboards orgs, err := dr.orgService.Search(ctx, &org.SearchOrgsQuery{}) if err != nil { return err } + orgIDs := make([]int64, 0, len(orgs)) + for _, org := range orgs { + orgIDs = append(orgIDs, org.ID) + } + + if err := dr.DeleteDuplicateProvisionedDashboards(ctx, orgIDs, cmd.Config); err != nil { + dr.log.Error("Failed to delete duplicate provisioned dashboards", "error", err) + } + + currentNames := make([]string, 0, len(cmd.Config)) + for _, cfg := range cmd.Config { + currentNames = append(currentNames, cfg.Name) + } + for _, org := range orgs { ctx, _ := identity.WithServiceIdentity(ctx, org.ID) // find all dashboards in the org that have a file repo set that is not in the given readers list foundDashs, err := dr.searchProvisionedDashboardsThroughK8s(ctx, &dashboards.FindPersistedDashboardsQuery{ ManagedBy: utils.ManagerKindClassicFP, //nolint:staticcheck - ManagerIdentityNotIn: cmd.ReaderNames, + ManagerIdentityNotIn: currentNames, OrgId: org.ID, }) if err != nil { @@ -921,7 +962,129 @@ func (dr *DashboardServiceImpl) DeleteOrphanedProvisionedDashboards(ctx context. return nil } -func (dr *DashboardServiceImpl) DeleteDuplicateProvisionedDashboards(ctx context.Context) error { +// searchExistingProvisionedData fetches provisioned data for the purposes of +// duplication cleanup. Returns the set of folder UIDs for folders with the +// given title, and the set of resources contained in those folders. +func (dr *DashboardServiceImpl) searchExistingProvisionedData( + ctx context.Context, orgID int64, folderTitle string, +) ([]string, []dashboards.DashboardSearchProjection, error) { + ctx, user := identity.WithServiceIdentity(ctx, orgID) + cmd := folder.SearchFoldersQuery{ + OrgID: orgID, + SignedInUser: user, + Title: folderTitle, + TitleExactMatch: true, + } + + searchResults, err := dr.folderService.SearchFolders(ctx, cmd) + if err != nil { + return nil, nil, fmt.Errorf("checking if provisioning reset is required: %w", err) + } + + var matchingFolders []string //nolint:prealloc + for _, result := range searchResults { + f, err := dr.folderService.Get(ctx, &folder.GetFolderQuery{ + OrgID: orgID, + UID: &result.UID, + SignedInUser: user, + }) + if err != nil { + return nil, nil, err + } + + // We are only interested in folders at the top-level of the folder hierarchy. + // Cleanup is not performed for provisioned folders that were moved to + // a different location. + if f.ParentUID != "" { + continue + } + + matchingFolders = append(matchingFolders, f.UID) + } + + if len(matchingFolders) == 0 { + // If there are no folders with the same title as the provisioned folder we + // are looking for, there is nothing to be cleaned up. + return nil, nil, nil + } + + resources, err := dr.FindDashboards(ctx, &dashboards.FindPersistedDashboardsQuery{ + OrgId: orgID, + SignedInUser: user, + FolderUIDs: matchingFolders, + }) + if err != nil { + return nil, nil, err + } + + return matchingFolders, resources, nil +} + +// maybeResetProvisioning will check for duplicated provisioned dashboards in the database. These duplications +// happen when multiple provisioned dashboards of the same title are found, or multiple provisioned +// folders are found. In this case, provisioned resources are deleted, allowing the provisioning +// process to start from scratch after this function returns. +func (dr *DashboardServiceImpl) maybeResetProvisioning(ctx context.Context, orgs []int64, configs []dashboards.ProvisioningConfig) { + if skipReason := canBeAutomaticallyCleanedUp(configs); skipReason != "" { + dr.log.Info("not eligible for automated cleanup", "reason", skipReason) + return + } + + folderTitle := configs[0].Folder + provisionedNames := map[string]bool{} + for _, c := range configs { + provisionedNames[c.Name] = true + } + + for _, orgID := range orgs { + ctx, user := identity.WithServiceIdentity(ctx, orgID) + provFolders, resources, err := dr.searchExistingProvisionedData(ctx, orgID, folderTitle) + if err != nil { + dr.log.Error("failed to search for provisioned data for cleanup", "org", orgID, "error", err) + continue + } + + steps, err := cleanupSteps(provFolders, resources, provisionedNames) + if err != nil { + dr.log.Warn("not possible to perform automated duplicate cleanup", "org", orgID, "error", err) + continue + } + + for _, step := range steps { + var err error + + switch step.Type { + case searchstore.TypeDashboard: + err = dr.deleteDashboard(ctx, 0, step.UID, orgID, false) + case searchstore.TypeFolder: + err = dr.folderService.Delete(ctx, &folder.DeleteFolderCommand{ + OrgID: orgID, + SignedInUser: user, + UID: step.UID, + }) + } + + if err == nil { + dr.log.Info("deleted duplicated provisioned resource", + "type", step.Type, "uid", step.UID, + ) + } else { + dr.log.Error("failed to delete duplicated provisioned resource", + "type", step.Type, "uid", step.UID, "error", err, + ) + } + } + } +} + +func (dr *DashboardServiceImpl) DeleteDuplicateProvisionedDashboards(ctx context.Context, orgs []int64, configs []dashboards.ProvisioningConfig) error { + // Start from scratch if duplications that cannot be fixed by the logic + // below are found in the database. + dr.maybeResetProvisioning(ctx, orgs, configs) + + // cleanup duplicate provisioned dashboards (i.e., with the same name and external_id). + // Note: only works in modes 1-3. This logic can be removed once mode5 is + // enabled everywhere. duplicates, err := dr.dashboardStore.GetDuplicateProvisionedDashboards(ctx) if err != nil { return err @@ -1305,6 +1468,11 @@ func (dr *DashboardServiceImpl) GetDashboardUIDByID(ctx context.Context, query * if err != nil { return nil, err } + + if query.ID <= 0 { + return nil, dashboards.ErrDashboardNotFound + } + result, err := dr.searchDashboardsThroughK8s(ctx, &dashboards.FindPersistedDashboardsQuery{ OrgId: requester.GetOrgID(), DashboardIds: []int64{query.ID}, @@ -1316,7 +1484,7 @@ func (dr *DashboardServiceImpl) GetDashboardUIDByID(ctx context.Context, query * if len(result) == 0 { return nil, dashboards.ErrDashboardNotFound } else if len(result) > 1 { - return nil, fmt.Errorf("unexpected number of dashboards found: %d. desired: 1", len(result)) + return nil, fmt.Errorf("unexpected number of dashboards for id %d. found: %d. desired: 1", query.ID, len(result)) } return &dashboards.DashboardRef{UID: result[0].UID, Slug: result[0].Slug, FolderUID: result[0].FolderUID}, nil @@ -1506,6 +1674,8 @@ func (dr *DashboardServiceImpl) FindDashboards(ctx context.Context, query *dashb FolderTitle: folderTitle, FolderID: folderID, FolderSlug: slugify.Slugify(folderTitle), + ManagedBy: hit.ManagedBy.Kind, + ManagerId: hit.ManagedBy.ID, Tags: hit.Tags, } diff --git a/pkg/services/dashboards/service/dashboard_service_test.go b/pkg/services/dashboards/service/dashboard_service_test.go index 35ac47afd9a..a3745f864c2 100644 --- a/pkg/services/dashboards/service/dashboard_service_test.go +++ b/pkg/services/dashboards/service/dashboard_service_test.go @@ -779,7 +779,7 @@ func TestDeleteOrphanedProvisionedDashboards(t *testing.T) { }, nil).Twice() err := service.DeleteOrphanedProvisionedDashboards(context.Background(), &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ - ReaderNames: []string{"test"}, + Config: []dashboards.ProvisioningConfig{{Name: "test"}}, }) require.NoError(t, err) k8sCliMock.AssertExpectations(t) @@ -874,7 +874,7 @@ func TestDeleteOrphanedProvisionedDashboards(t *testing.T) { }, nil).Once() err := singleOrgService.DeleteOrphanedProvisionedDashboards(ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ - ReaderNames: []string{"test"}, + Config: []dashboards.ProvisioningConfig{{Name: "test"}}, }) require.NoError(t, err) k8sCliMock.AssertExpectations(t) @@ -906,7 +906,7 @@ func TestDeleteOrphanedProvisionedDashboards(t *testing.T) { }, nil) err := singleOrgService.DeleteOrphanedProvisionedDashboards(ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ - ReaderNames: []string{"test"}, + Config: []dashboards.ProvisioningConfig{{Name: "test"}}, }) require.NoError(t, err) k8sCliMock.AssertExpectations(t) @@ -1663,6 +1663,13 @@ func TestGetDashboardUIDByID(t *testing.T) { require.NoError(t, err) require.Equal(t, expectedResult, result) k8sCliMock.AssertExpectations(t) + + // 0 should return error + _, err = service.GetDashboardUIDByID(ctx, &dashboards.GetDashboardRefByIDQuery{ + ID: 0, + }) + require.Error(t, err) + require.Equal(t, dashboards.ErrDashboardNotFound, err) } func TestUnstructuredToLegacyDashboard(t *testing.T) { diff --git a/pkg/services/dashboards/service/provisioning_cleanup.go b/pkg/services/dashboards/service/provisioning_cleanup.go new file mode 100644 index 00000000000..ca5fe75921a --- /dev/null +++ b/pkg/services/dashboards/service/provisioning_cleanup.go @@ -0,0 +1,107 @@ +package service + +import ( + "errors" + "fmt" + + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/services/dashboards" + "github.com/grafana/grafana/pkg/services/sqlstore/searchstore" +) + +// canBeAutomaticallyCleanedUp determines whether this instance can be automatically cleaned up +// if duplicated provisioned resources are found. To ensure the process does not delete +// resources it shouldn't, automatic cleanups only happen if all provisioned dashboards +// are stored in the same folder (by title), and no dashboards allow UI updates. +func canBeAutomaticallyCleanedUp(configs []dashboards.ProvisioningConfig) string { + if len(configs) == 0 { + return "no provisioned dashboards" + } + + folderTitle := configs[0].Folder + if len(folderTitle) == 0 { + return fmt.Sprintf("dashboard has no folder: %s", configs[0].Name) + } + + for _, cfg := range configs { + if cfg.AllowUIUpdates { + return "contains dashboards with allowUiUpdates" + } + + if cfg.Folder != folderTitle { + return "dashboards provisioned across multiple folders" + } + } + + return "" +} + +type deleteProvisionedResource struct { + Type string + UID string +} + +// cleanupSteps computes the sequence of steps to be performed in order to cleanup the +// provisioning resources and allow the process to start from scratch when duplication +// is detected. The sequence of steps will dictate the order in which dashboards and folders +// are to be deleted. +func cleanupSteps(provFolders []string, resources []dashboards.DashboardSearchProjection, configDashboards map[string]bool) ([]deleteProvisionedResource, error) { + var hasDuplicatedProvisionedDashboard bool + var hasUserCreatedResource bool + var uniqueNames = map[string]struct{}{} + var deleteProvisionedDashboards []deleteProvisionedResource //nolint:prealloc + + for _, r := range resources { + // nolint:staticcheck + if r.IsFolder || r.ManagedBy != utils.ManagerKindClassicFP { + hasUserCreatedResource = true + continue + } + + // Only delete dashboards if they are included in the provisioning configuration + // for this instance. + if !configDashboards[r.ManagerId] { + continue + } + + if _, exists := uniqueNames[r.ManagerId]; exists { + hasDuplicatedProvisionedDashboard = true + } + + uniqueNames[r.ManagerId] = struct{}{} + deleteProvisionedDashboards = append(deleteProvisionedDashboards, deleteProvisionedResource{ + Type: searchstore.TypeDashboard, + UID: r.UID, + }) + } + + if len(provFolders) == 0 { + // When there are no provisioned folders, there is nothing to do. + return nil, nil + } else if len(provFolders) == 1 { + // If only one folder was found, keep it and delete the provisioned dashboards if + // duplication was found. + if hasDuplicatedProvisionedDashboard { + return deleteProvisionedDashboards, nil + } + } else { + // If multiple folders were found *and* a user-created resource exists in + // one of them, bail, as we wouldn't be able to delete one of the duplicated folders. + if hasUserCreatedResource { + return nil, errors.New("multiple provisioning folders exist with at least one user-created resource") + } + + // Delete provisioned dashboards first, and then the folders. + steps := deleteProvisionedDashboards + for _, uid := range provFolders { + steps = append(steps, deleteProvisionedResource{ + Type: searchstore.TypeFolder, + UID: uid, + }) + } + + return steps, nil + } + + return nil, nil +} diff --git a/pkg/services/dashboards/service/provisioning_cleanup_test.go b/pkg/services/dashboards/service/provisioning_cleanup_test.go new file mode 100644 index 00000000000..049dc420f2d --- /dev/null +++ b/pkg/services/dashboards/service/provisioning_cleanup_test.go @@ -0,0 +1,279 @@ +package service + +import ( + "testing" + + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/services/dashboards" + "github.com/grafana/grafana/pkg/services/sqlstore/searchstore" + "github.com/stretchr/testify/require" +) + +func Test_canBeAutomaticallyCleanedUp(t *testing.T) { + testCases := []struct { + name string + configs []dashboards.ProvisioningConfig + expectedSkip string + }{ + { + name: "no dashboards defined in the configuration", + configs: []dashboards.ProvisioningConfig{}, + expectedSkip: "no provisioned dashboards", + }, + { + name: "first defined dashboard has no folder defined", + configs: []dashboards.ProvisioningConfig{ + {Name: "1", Folder: ""}, + {Folder: "f1"}, + }, + expectedSkip: "dashboard has no folder: 1", + }, + { + name: "one of the provisioned dashboards has no folder defined", + configs: []dashboards.ProvisioningConfig{ + {Name: "1", Folder: "f1"}, + {Name: "2", Folder: "f1"}, + {Name: "3", Folder: ""}, + {Name: "4", Folder: "f1"}, + }, + expectedSkip: "dashboards provisioned across multiple folders", + }, + { + name: "one of the provisioned dashboards allows UI updates", + configs: []dashboards.ProvisioningConfig{ + {Name: "1", Folder: "f1"}, + {Name: "2", Folder: "f1", AllowUIUpdates: true}, + {Name: "3", Folder: "f1"}, + {Name: "4", Folder: "f1"}, + }, + expectedSkip: "contains dashboards with allowUiUpdates", + }, + { + name: "one of the provisioned dashboards is in a different folder", + configs: []dashboards.ProvisioningConfig{ + {Name: "1", Folder: "f1"}, + {Name: "2", Folder: "f1"}, + {Name: "3", Folder: "f1"}, + {Name: "4", Folder: "different"}, + }, + expectedSkip: "dashboards provisioned across multiple folders", + }, + { + name: "can be skipped when all conditions are met", + configs: []dashboards.ProvisioningConfig{ + {Name: "1", Folder: "f1"}, + {Name: "2", Folder: "f1"}, + {Name: "3", Folder: "f1"}, + {Name: "4", Folder: "f1"}, + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.expectedSkip, canBeAutomaticallyCleanedUp(tc.configs)) + }) + } +} + +func Test_cleanupSteps(t *testing.T) { + isDashboard, isFolder := false, true + + fromUser := func(uid, name string, isFolder bool) dashboards.DashboardSearchProjection { + return dashboards.DashboardSearchProjection{ + UID: uid, + ManagerId: name, + IsFolder: isFolder, + } + } + + provisioned := func(uid, name string, isFolder bool) dashboards.DashboardSearchProjection { + dashboard := fromUser(uid, name, isFolder) + dashboard.ManagedBy = utils.ManagerKindClassicFP //nolint:staticcheck + return dashboard + } + + testCases := []struct { + name string + provisionedFolders []string + provisionedResources []dashboards.DashboardSearchProjection + configDashboards []string + expectedSteps []deleteProvisionedResource + expectedErr string + }{ + { + name: "no provisioned folders, nothing to do", + provisionedFolders: []string{}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + }, + }, + { + name: "multiple folders, a user-created dashboard in one of them", + provisionedFolders: []string{"folder1", "folder2"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + fromUser("d3", "User1", isDashboard), + provisioned("d4", "Provisioned3", isDashboard), + }, + expectedErr: "multiple provisioning folders exist with at least one user-created resource", + }, + { + name: "multiple folders, a user-created folder in one of them", + provisionedFolders: []string{"folder1", "folder2"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned3", isDashboard), + fromUser("f1", "UserFolder1", isFolder), + }, + expectedErr: "multiple provisioning folders exist with at least one user-created resource", + }, + { + name: "single folder, some dashboards duplicated", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + // Provisioned1 is duplicated. + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned1", isDashboard), + provisioned("d4", "Provisioned3", isDashboard), + }, + expectedSteps: []deleteProvisionedResource{ + {Type: searchstore.TypeDashboard, UID: "d1"}, + {Type: searchstore.TypeDashboard, UID: "d2"}, + {Type: searchstore.TypeDashboard, UID: "d3"}, + {Type: searchstore.TypeDashboard, UID: "d4"}, + }, + }, + { + name: "single folder, duplicated dashboards, user-created dashboards are ignored", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + // Provisioned1 is duplicated. + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + fromUser("d3", "User1", isDashboard), + provisioned("d4", "Provisioned3", isDashboard), + provisioned("d5", "Provisioned1", isDashboard), + }, + // User dashboard (d3) is not deleted. + expectedSteps: []deleteProvisionedResource{ + {Type: searchstore.TypeDashboard, UID: "d1"}, + {Type: searchstore.TypeDashboard, UID: "d2"}, + {Type: searchstore.TypeDashboard, UID: "d4"}, + {Type: searchstore.TypeDashboard, UID: "d5"}, + }, + }, + { + name: "single folder, duplicated dashboards, user-created folders are ignored", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + // Provisioned1 is duplicated. + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned3", isDashboard), + provisioned("d4", "Provisioned1", isDashboard), + fromUser("f1", "UserFolder1", isFolder), + }, + // User folder (f1) is not deleted. + expectedSteps: []deleteProvisionedResource{ + {Type: searchstore.TypeDashboard, UID: "d1"}, + {Type: searchstore.TypeDashboard, UID: "d2"}, + {Type: searchstore.TypeDashboard, UID: "d3"}, + {Type: searchstore.TypeDashboard, UID: "d4"}, + }, + }, + { + name: "multiple folders, only provisioned dashboards", + provisionedFolders: []string{"folder1", "folder2"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned3", isDashboard), + provisioned("d4", "Provisioned4", isDashboard), + }, + // Delete all dashboards, then all folders. + expectedSteps: []deleteProvisionedResource{ + {Type: searchstore.TypeDashboard, UID: "d1"}, + {Type: searchstore.TypeDashboard, UID: "d2"}, + {Type: searchstore.TypeDashboard, UID: "d3"}, + {Type: searchstore.TypeDashboard, UID: "d4"}, + {Type: searchstore.TypeFolder, UID: "folder1"}, + {Type: searchstore.TypeFolder, UID: "folder2"}, + }, + }, + { + name: "single folder, only deletes dashboards defined in the config file", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned1", isDashboard), + provisioned("d4", "Provisioned4", isDashboard), + provisioned("d5", "Provisioned4", isDashboard), + }, + // Delete duplicated dashboards, but keep Provisioned4, since it's not in the config file. + expectedSteps: []deleteProvisionedResource{ + {Type: searchstore.TypeDashboard, UID: "d1"}, + {Type: searchstore.TypeDashboard, UID: "d2"}, + {Type: searchstore.TypeDashboard, UID: "d3"}, + }, + }, + { + name: "single folder, no duplicated dashboards", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + provisioned("d3", "Provisioned3", isDashboard), + provisioned("d4", "Provisioned4", isDashboard), + }, + expectedSteps: nil, // no duplicates, nothing to do + }, + { + name: "single folder, no duplicated dashboards, multiple user-created resources", + provisionedFolders: []string{"folder1"}, + configDashboards: []string{"Provisioned1", "Provisioned2", "Provisioned3", "Provisioned4"}, + provisionedResources: []dashboards.DashboardSearchProjection{ + provisioned("d1", "Provisioned1", isDashboard), + provisioned("d2", "Provisioned2", isDashboard), + fromUser("f1", "UserFolder1", isFolder), + provisioned("d3", "Provisioned3", isDashboard), + fromUser("d4", "User1", isDashboard), + provisioned("d5", "Provisioned4", isDashboard), + fromUser("d6", "User2", isDashboard), + fromUser("f2", "UserFolder2", isFolder), + }, + expectedSteps: nil, // no duplicates in the provisioned set, nothing to do + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + provisionedSet := make(map[string]bool) + for _, name := range tc.configDashboards { + provisionedSet[name] = true + } + + steps, err := cleanupSteps(tc.provisionedFolders, tc.provisionedResources, provisionedSet) + if tc.expectedErr == "" { + require.NoError(t, err) + require.Equal(t, tc.expectedSteps, steps) + } else { + require.Error(t, err) + require.Equal(t, tc.expectedErr, err.Error()) + } + }) + } +} diff --git a/pkg/services/dashboards/service/service.go b/pkg/services/dashboards/service/service.go index f526404dc0e..f56d070b695 100644 --- a/pkg/services/dashboards/service/service.go +++ b/pkg/services/dashboards/service/service.go @@ -23,3 +23,9 @@ func ProvideDashboardPluginService( ) dashboards.PluginService { return orig } + +func ProvideDashboardAccessService( + features featuremgmt.FeatureToggles, orig *DashboardServiceImpl, +) dashboards.DashboardAccessService { + return orig +} diff --git a/pkg/services/dashboardversion/dashverimpl/dashver.go b/pkg/services/dashboardversion/dashverimpl/dashver.go index 2a4d31f2b4d..8f9e01bbeea 100644 --- a/pkg/services/dashboardversion/dashverimpl/dashver.go +++ b/pkg/services/dashboardversion/dashverimpl/dashver.go @@ -274,6 +274,11 @@ func (s *Service) listDashboardVersionsThroughK8s( continueToken = tempOut.GetContinue() } + // Update the continue token on the response to reflect the actual position after all fetched items. + // Without this, the response would return the token from the first fetch, causing duplicate items + // on subsequent pages when multiple fetches were needed to fill the requested limit. + out.SetContinue(continueToken) + return out, nil } diff --git a/pkg/services/dashboardversion/dashverimpl/dashver_test.go b/pkg/services/dashboardversion/dashverimpl/dashver_test.go index 909e98ee33c..18e3c295ab5 100644 --- a/pkg/services/dashboardversion/dashverimpl/dashver_test.go +++ b/pkg/services/dashboardversion/dashverimpl/dashver_test.go @@ -268,6 +268,58 @@ func TestListDashboardVersions(t *testing.T) { }}}, res) }) + t.Run("List returns continue token when first fetch satisfies limit with more pages", func(t *testing.T) { + dashboardService := dashboards.NewFakeDashboardService(t) + dashboardVersionService := Service{dashSvc: dashboardService, features: featuremgmt.WithFeatures()} + mockCli := new(client.MockK8sHandler) + dashboardVersionService.k8sclient = mockCli + dashboardVersionService.features = featuremgmt.WithFeatures() + + dashboardService.On("GetDashboardUIDByID", mock.Anything, + mock.AnythingOfType("*dashboards.GetDashboardRefByIDQuery")). + Return(&dashboards.DashboardRef{UID: "uid"}, nil) + query := dashver.ListDashboardVersionsQuery{DashboardID: 42, Limit: 2} + mockCli.On("GetUsersFromMeta", mock.Anything, mock.Anything).Return(map[string]*user.User{}, nil) + + firstPage := &unstructured.UnstructuredList{ + Items: []unstructured.Unstructured{ + {Object: map[string]any{ + "metadata": map[string]any{ + "name": "uid", + "resourceVersion": "11", + "generation": int64(4), + "labels": map[string]any{ + utils.LabelKeyDeprecatedInternalID: "42", // nolint:staticcheck + }, + }, + "spec": map[string]any{}, + }}, + {Object: map[string]any{ + "metadata": map[string]any{ + "name": "uid", + "resourceVersion": "12", + "generation": int64(5), + "labels": map[string]any{ + utils.LabelKeyDeprecatedInternalID: "42", // nolint:staticcheck + }, + }, + "spec": map[string]any{}, + }}, + }, + } + firstMeta, err := meta.ListAccessor(firstPage) + require.NoError(t, err) + firstMeta.SetContinue("t1") // More pages exist + + mockCli.On("List", mock.Anything, mock.Anything, mock.Anything).Return(firstPage, nil).Once() + + res, err := dashboardVersionService.List(context.Background(), &query) + require.Nil(t, err) + require.Equal(t, 2, len(res.Versions)) + require.Equal(t, "t1", res.ContinueToken) // Token from first fetch when limit is satisfied + mockCli.AssertNumberOfCalls(t, "List", 1) // Only one fetch needed + }) + t.Run("List returns correct continue token across multiple pages", func(t *testing.T) { dashboardService := dashboards.NewFakeDashboardService(t) dashboardVersionService := Service{dashSvc: dashboardService, features: featuremgmt.WithFeatures()} @@ -333,7 +385,79 @@ func TestListDashboardVersions(t *testing.T) { res, err := dashboardVersionService.List(context.Background(), &query) require.Nil(t, err) require.Equal(t, 3, len(res.Versions)) - require.Equal(t, "t1", res.ContinueToken) // Implementation returns continue token from first page + require.Equal(t, "", res.ContinueToken) // Should return token from last fetch (empty = no more pages) + mockCli.AssertNumberOfCalls(t, "List", 2) + }) + + t.Run("List returns continue token from last fetch when more pages exist", func(t *testing.T) { + dashboardService := dashboards.NewFakeDashboardService(t) + dashboardVersionService := Service{dashSvc: dashboardService, features: featuremgmt.WithFeatures()} + mockCli := new(client.MockK8sHandler) + dashboardVersionService.k8sclient = mockCli + dashboardVersionService.features = featuremgmt.WithFeatures() + + dashboardService.On("GetDashboardUIDByID", mock.Anything, + mock.AnythingOfType("*dashboards.GetDashboardRefByIDQuery")). + Return(&dashboards.DashboardRef{UID: "uid"}, nil) + query := dashver.ListDashboardVersionsQuery{DashboardID: 42, Limit: 3} + mockCli.On("GetUsersFromMeta", mock.Anything, mock.Anything).Return(map[string]*user.User{}, nil) + + firstPage := &unstructured.UnstructuredList{ + Items: []unstructured.Unstructured{ + {Object: map[string]any{ + "metadata": map[string]any{ + "name": "uid", + "resourceVersion": "11", + "generation": int64(4), + "labels": map[string]any{ + utils.LabelKeyDeprecatedInternalID: "42", // nolint:staticcheck + }, + }, + "spec": map[string]any{}, + }}, + {Object: map[string]any{ + "metadata": map[string]any{ + "name": "uid", + "resourceVersion": "12", + "generation": int64(5), + "labels": map[string]any{ + utils.LabelKeyDeprecatedInternalID: "42", // nolint:staticcheck + }, + }, + "spec": map[string]any{}, + }}, + }, + } + firstMeta, err := meta.ListAccessor(firstPage) + require.NoError(t, err) + firstMeta.SetContinue("t1") + + secondPage := &unstructured.UnstructuredList{ + Items: []unstructured.Unstructured{ + {Object: map[string]any{ + "metadata": map[string]any{ + "name": "uid", + "resourceVersion": "13", + "generation": int64(6), + "labels": map[string]any{ + utils.LabelKeyDeprecatedInternalID: "42", // nolint:staticcheck + }, + }, + "spec": map[string]any{}, + }}, + }, + } + secondMeta, err := meta.ListAccessor(secondPage) + require.NoError(t, err) + secondMeta.SetContinue("t2") // More pages exist + + mockCli.On("List", mock.Anything, mock.Anything, mock.Anything).Return(firstPage, nil).Once() + mockCli.On("List", mock.Anything, mock.Anything, mock.Anything).Return(secondPage, nil).Once() + + res, err := dashboardVersionService.List(context.Background(), &query) + require.Nil(t, err) + require.Equal(t, 3, len(res.Versions)) + require.Equal(t, "t2", res.ContinueToken) // Must return token from LAST fetch, not first mockCli.AssertNumberOfCalls(t, "List", 2) }) diff --git a/pkg/services/featuremgmt/registry.go b/pkg/services/featuremgmt/registry.go index feb38de0b4e..2044c9c40f2 100644 --- a/pkg/services/featuremgmt/registry.go +++ b/pkg/services/featuremgmt/registry.go @@ -494,13 +494,6 @@ var ( Owner: grafanaDatasourcesCoreServicesSquad, FrontendOnly: true, // and can change at startup }, - { - Name: "queryServiceFromExplore", - Description: "Routes explore requests to the new query service", - Stage: FeatureStageExperimental, - Owner: grafanaDatasourcesCoreServicesSquad, - FrontendOnly: true, - }, { Name: "cloudWatchBatchQueries", Description: "Runs CloudWatch metrics queries as separate batches", @@ -1631,6 +1624,14 @@ var ( Owner: grafanaFrontendSearchNavOrganise, Expression: "false", }, + { + Name: "recentlyViewedDashboards", + Description: "Enables recently viewed dashboards section in the browsing dashboard page", + Stage: FeatureStageExperimental, + Owner: grafanaFrontendSearchNavOrganise, + FrontendOnly: true, + Expression: "false", + }, { Name: "alertEnrichment", Description: "Enable configuration of alert enrichments in Grafana Cloud.", @@ -1945,6 +1946,14 @@ var ( Owner: identityAccessTeam, Expression: "true", }, + { + Name: "pluginInsights", + Description: "Show insights for plugins in the plugin details page", + Stage: FeatureStageExperimental, + FrontendOnly: true, + Owner: grafanaPluginsPlatformSquad, + Expression: "false", + }, { Name: "panelTimeSettings", Description: "Enables a new panel time settings drawer", @@ -1954,6 +1963,13 @@ var ( RequiresRestart: false, HideFromDocs: false, }, + { + Name: "elasticsearchRawDSLQuery", + Description: "Enables the raw DSL query editor in the Elasticsearch data source", + Stage: FeatureStageExperimental, + Owner: grafanaPartnerPluginsSquad, + Expression: "false", + }, { Name: "kubernetesAnnotations", Description: "Enables app platform API for annotations", diff --git a/pkg/services/featuremgmt/toggles_gen.csv b/pkg/services/featuremgmt/toggles_gen.csv index 3e8324db87a..0f681344984 100644 --- a/pkg/services/featuremgmt/toggles_gen.csv +++ b/pkg/services/featuremgmt/toggles_gen.csv @@ -68,7 +68,6 @@ queryService,experimental,@grafana/grafana-datasources-core-services,false,true, queryServiceWithConnections,experimental,@grafana/grafana-datasources-core-services,false,true,false queryServiceRewrite,experimental,@grafana/grafana-datasources-core-services,false,true,false queryServiceFromUI,experimental,@grafana/grafana-datasources-core-services,false,false,true -queryServiceFromExplore,experimental,@grafana/grafana-datasources-core-services,false,false,true cloudWatchBatchQueries,preview,@grafana/aws-datasources,false,false,false cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false alertmanagerRemoteSecondary,experimental,@grafana/alerting-squad,false,false,false @@ -224,6 +223,7 @@ kubernetesAuthzZanzanaSync,experimental,@grafana/identity-access-team,false,fals kubernetesAuthnMutation,experimental,@grafana/identity-access-team,false,false,false kubernetesExternalGroupMapping,experimental,@grafana/identity-access-team,false,false,false restoreDashboards,experimental,@grafana/grafana-search-navigate-organise,false,false,false +recentlyViewedDashboards,experimental,@grafana/grafana-search-navigate-organise,false,false,true alertEnrichment,experimental,@grafana/alerting-squad,false,false,false alertEnrichmentMultiStep,experimental,@grafana/alerting-squad,false,false,false alertEnrichmentConditional,experimental,@grafana/alerting-squad,false,false,false @@ -264,7 +264,9 @@ jaegerEnableGrpcEndpoint,experimental,@grafana/oss-big-tent,false,false,false pluginStoreServiceLoading,experimental,@grafana/plugins-platform-backend,false,false,false newPanelPadding,preview,@grafana/dashboards-squad,false,false,true onlyStoreActionSets,GA,@grafana/identity-access-team,false,false,false +pluginInsights,experimental,@grafana/plugins-platform-backend,false,false,true panelTimeSettings,experimental,@grafana/dashboards-squad,false,false,false +elasticsearchRawDSLQuery,experimental,@grafana/partner-datasources,false,false,false kubernetesAnnotations,experimental,@grafana/grafana-backend-services-squad,false,false,false awsDatasourcesHttpProxy,experimental,@grafana/aws-datasources,false,false,false transformationsEmptyPlaceholder,preview,@grafana/datapro,false,false,true diff --git a/pkg/services/featuremgmt/toggles_gen.go b/pkg/services/featuremgmt/toggles_gen.go index 6e106fd9950..fc7b8043dec 100644 --- a/pkg/services/featuremgmt/toggles_gen.go +++ b/pkg/services/featuremgmt/toggles_gen.go @@ -758,6 +758,10 @@ const ( // Enables a new panel time settings drawer FlagPanelTimeSettings = "panelTimeSettings" + // FlagElasticsearchRawDSLQuery + // Enables the raw DSL query editor in the Elasticsearch data source + FlagElasticsearchRawDSLQuery = "elasticsearchRawDSLQuery" + // FlagKubernetesAnnotations // Enables app platform API for annotations FlagKubernetesAnnotations = "kubernetesAnnotations" diff --git a/pkg/services/featuremgmt/toggles_gen.json b/pkg/services/featuremgmt/toggles_gen.json index 4dcaf34f924..31b501a8feb 100644 --- a/pkg/services/featuremgmt/toggles_gen.json +++ b/pkg/services/featuremgmt/toggles_gen.json @@ -1206,6 +1206,19 @@ "codeowner": "@grafana/partner-datasources" } }, + { + "metadata": { + "name": "elasticsearchRawDSLQuery", + "resourceVersion": "1763508396079", + "creationTimestamp": "2025-11-18T23:26:36Z" + }, + "spec": { + "description": "Enables the raw DSL query editor in the Elasticsearch data source", + "stage": "experimental", + "codeowner": "@grafana/partner-datasources", + "expression": "false" + } + }, { "metadata": { "name": "enableAppChromeExtensions", @@ -2654,6 +2667,20 @@ "expression": "false" } }, + { + "metadata": { + "name": "pluginInsights", + "resourceVersion": "1761300628147", + "creationTimestamp": "2025-10-24T10:10:28Z" + }, + "spec": { + "description": "Show insights for plugins in the plugin details page", + "stage": "experimental", + "codeowner": "@grafana/plugins-platform-backend", + "frontend": true, + "expression": "false" + } + }, { "metadata": { "name": "pluginInstallAPISync", @@ -2884,7 +2911,8 @@ "metadata": { "name": "queryServiceFromExplore", "resourceVersion": "1764664939750", - "creationTimestamp": "2025-04-02T10:00:33Z" + "creationTimestamp": "2025-04-02T10:00:33Z", + "deletionTimestamp": "2025-12-10T20:33:21Z" }, "spec": { "description": "Routes explore requests to the new query service", @@ -2933,6 +2961,23 @@ "requiresRestart": true } }, + { + "metadata": { + "name": "recentlyViewedDashboards", + "resourceVersion": "1765227168175", + "creationTimestamp": "2025-12-08T20:44:44Z", + "annotations": { + "grafana.app/updatedTimestamp": "2025-12-08 20:52:48.175129 +0000 UTC" + } + }, + "spec": { + "description": "Enables recently viewed dashboards section in the browsing dashboard page", + "stage": "experimental", + "codeowner": "@grafana/grafana-search-navigate-organise", + "frontend": true, + "expression": "false" + } + }, { "metadata": { "name": "refactorVariablesTimeRange", diff --git a/pkg/services/folder/folderimpl/folder_unifiedstorage.go b/pkg/services/folder/folderimpl/folder_unifiedstorage.go index 1551d858efe..9b238b769fe 100644 --- a/pkg/services/folder/folderimpl/folder_unifiedstorage.go +++ b/pkg/services/folder/folderimpl/folder_unifiedstorage.go @@ -202,6 +202,11 @@ func (s *Service) searchFoldersFromApiServer(ctx context.Context, query folder.S if query.Title != "" { // allow wildcard search request.Query = "*" + strings.ToLower(query.Title) + "*" + // or perform exact match if requested + if query.TitleExactMatch { + request.Query = query.Title + } + // if using query, you need to specify the fields you want request.Fields = dashboardsearch.IncludeFields } diff --git a/pkg/services/folder/model.go b/pkg/services/folder/model.go index 3e59f5c1b6f..e0061ca8dd7 100644 --- a/pkg/services/folder/model.go +++ b/pkg/services/folder/model.go @@ -224,12 +224,13 @@ type GetFoldersQuery struct { } type SearchFoldersQuery struct { - OrgID int64 - UIDs []string - IDs []int64 - Title string - Limit int64 - SignedInUser identity.Requester `json:"-"` + OrgID int64 + UIDs []string + IDs []int64 + Title string + TitleExactMatch bool + Limit int64 + SignedInUser identity.Requester `json:"-"` } // GetParentsQuery captures the information required by the folder service to diff --git a/pkg/services/frontend/frontend_service.go b/pkg/services/frontend/frontend_service.go index f730bfba376..74776a1169e 100644 --- a/pkg/services/frontend/frontend_service.go +++ b/pkg/services/frontend/frontend_service.go @@ -22,6 +22,7 @@ import ( fswebassets "github.com/grafana/grafana/pkg/services/frontend/webassets" "github.com/grafana/grafana/pkg/services/hooks" "github.com/grafana/grafana/pkg/services/licensing" + publicdashboardsapi "github.com/grafana/grafana/pkg/services/publicdashboards/api" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/web" ) @@ -133,7 +134,7 @@ func (s *frontendService) addMiddlewares(m *web.Mux) { loggermiddleware := loggermw.Provide(s.cfg, s.features) m.Use(requestmeta.SetupRequestMetadata()) - m.Use(middleware.RequestTracing(s.tracer, middleware.TraceAllPaths)) + m.Use(middleware.RequestTracing(s.tracer, middleware.ShouldTraceAllPaths)) m.Use(middleware.RequestMetrics(s.features, s.cfg, s.promRegister)) m.UseMiddleware(s.contextMiddleware()) @@ -164,6 +165,11 @@ func (s *frontendService) registerRoutes(m *web.Mux) { // uses cache busting to ensure requests aren't cached. s.routeGet(m, "/-/fe-boot-error", s.handleBootError) + s.routeGet(m, "/public-dashboards/:accessToken", + publicdashboardsapi.SetPublicDashboardAccessToken, + s.index.HandleRequest, + ) + // All other requests return index.html s.routeGet(m, "/*", s.index.HandleRequest) } diff --git a/pkg/services/frontend/index.go b/pkg/services/frontend/index.go index 22d04234a36..e87ca894d20 100644 --- a/pkg/services/frontend/index.go +++ b/pkg/services/frontend/index.go @@ -45,6 +45,8 @@ type IndexViewData struct { // Nonce is a cryptographic identifier for use with Content Security Policy. Nonce string + + PublicDashboardAccessToken string } // Templates setup. @@ -138,9 +140,12 @@ func (p *IndexProvider) HandleRequest(writer http.ResponseWriter, request *http. return } + reqCtx := contexthandler.FromContext(ctx) + // TODO -- restructure so the static stuff is under one variable and the rest is dynamic data := p.data // copy everything data.Nonce = nonce + data.PublicDashboardAccessToken = reqCtx.PublicDashboardAccessToken if data.CSPEnabled { data.CSPContent = middleware.ReplacePolicyVariables(p.data.CSPContent, p.data.AppSubUrl, data.Nonce) @@ -150,7 +155,6 @@ func (p *IndexProvider) HandleRequest(writer http.ResponseWriter, request *http. writer.Header().Set("Content-Security-Policy-Report-Only", policy) } - reqCtx := contexthandler.FromContext(ctx) p.runIndexDataHooks(reqCtx, &data) writer.Header().Set("Content-Type", "text/html; charset=UTF-8") diff --git a/pkg/services/frontend/index.html b/pkg/services/frontend/index.html index b0364fcbac9..198b8216189 100644 --- a/pkg/services/frontend/index.html +++ b/pkg/services/frontend/index.html @@ -188,6 +188,7 @@ // Wrap in an IIFE to avoid polluting the global scope. Intentionally global-scope properties // are explicitly assigned to the `window` object. (() => { + const publicDashboardAccessToken = [[.PublicDashboardAccessToken]] // Grafana can only fail to load once // However, it can fail to load in multiple different places // To avoid double reporting the error, we use this boolean to check if we've already failed @@ -271,9 +272,15 @@ async function fetchBootData() { const queryParams = new URLSearchParams(window.location.search); + let path = '/bootdata'; + // call a special bootdata url with the public access token + // this is needed to set the access token and correct org for public dashboards on the ST backend + if (publicDashboardAccessToken) { + path += `/${publicDashboardAccessToken}`; + } // pass the search params through to the bootdata request // this allows for overriding the theme/language etc - const bootDataUrl = new URL('/bootdata', window.location.origin); + const bootDataUrl = new URL(path, window.location.origin); for (const [key, value] of queryParams.entries()) { bootDataUrl.searchParams.append(key, value); } diff --git a/pkg/services/libraryelements/api.go b/pkg/services/libraryelements/api.go index 4895e7e6505..df51717756e 100644 --- a/pkg/services/libraryelements/api.go +++ b/pkg/services/libraryelements/api.go @@ -424,6 +424,9 @@ func (l *LibraryElementService) toLibraryElementError(err error, message string) if errors.Is(err, model.ErrLibraryElementUIDTooLong) { return response.Error(http.StatusBadRequest, model.ErrLibraryElementUIDTooLong.Error(), err) } + if errors.Is(err, model.ErrLibraryElementProvisionedFolder) { + return response.Error(http.StatusConflict, model.ErrLibraryElementProvisionedFolder.Error(), err) + } if err != nil && strings.Contains(err.Error(), "insufficient permissions") { return response.Error(http.StatusForbidden, err.Error(), err) } diff --git a/pkg/services/libraryelements/database.go b/pkg/services/libraryelements/database.go index a5b43fd54cb..2baa27ac1f8 100644 --- a/pkg/services/libraryelements/database.go +++ b/pkg/services/libraryelements/database.go @@ -10,6 +10,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/metrics" ac "github.com/grafana/grafana/pkg/services/accesscontrol" @@ -125,6 +126,20 @@ func (l *LibraryElementService) CreateElement(c context.Context, signedInUser id } } + if cmd.FolderUID != nil { + f, err := l.folderService.Get(c, &folder.GetFolderQuery{ + OrgID: signedInUser.GetOrgID(), + UID: cmd.FolderUID, + SignedInUser: signedInUser, + }) + if err != nil { + return model.LibraryElementDTO{}, err + } + if f.ManagedBy == utils.ManagerKindRepo { + return model.LibraryElementDTO{}, model.ErrLibraryElementProvisionedFolder + } + } + updatedModel := cmd.Model var err error if cmd.Kind == int64(model.PanelElement) { @@ -601,6 +616,21 @@ func (l *LibraryElementService) PatchLibraryElement(c context.Context, signedInU if err := l.requireSupportedElementKind(cmd.Kind); err != nil { return model.LibraryElementDTO{}, err } + + if cmd.FolderUID != nil { + f, err := l.folderService.Get(c, &folder.GetFolderQuery{ + OrgID: signedInUser.GetOrgID(), + UID: cmd.FolderUID, + SignedInUser: signedInUser, + }) + if err != nil { + return model.LibraryElementDTO{}, err + } + if f.ManagedBy == utils.ManagerKindRepo { + return model.LibraryElementDTO{}, model.ErrLibraryElementProvisionedFolder + } + } + err := l.SQLStore.WithTransactionalDbSession(c, func(session *db.Session) error { elementInDB, err := l.GetLibraryElement(c, signedInUser, session, uid) if err != nil { diff --git a/pkg/services/libraryelements/model/model.go b/pkg/services/libraryelements/model/model.go index 6e2bdfdcc41..4868bf50cbf 100644 --- a/pkg/services/libraryelements/model/model.go +++ b/pkg/services/libraryelements/model/model.go @@ -161,6 +161,8 @@ var ( ErrLibraryElementInvalidUID = errors.New("uid contains illegal characters") // errLibraryElementUIDTooLong is an error for when the uid of a library element is invalid ErrLibraryElementUIDTooLong = errors.New("uid too long, max 40 characters") + // ErrLibraryElementProvisionedFolder indicates that a library element cannot be created on a provisioned folder. + ErrLibraryElementProvisionedFolder = errors.New("resource type not supported in repository-managed folders") ) // Commands diff --git a/pkg/services/live/database/storage.go b/pkg/services/live/database/storage.go deleted file mode 100644 index 3736c27d265..00000000000 --- a/pkg/services/live/database/storage.go +++ /dev/null @@ -1,48 +0,0 @@ -package database - -import ( - "fmt" - "time" - - "github.com/grafana/grafana/pkg/infra/db" - "github.com/grafana/grafana/pkg/infra/localcache" - "github.com/grafana/grafana/pkg/services/live/model" -) - -type Storage struct { - store db.DB - cache *localcache.CacheService -} - -func NewStorage(store db.DB, cache *localcache.CacheService) *Storage { - return &Storage{store: store, cache: cache} -} - -func getLiveMessageCacheKey(orgID int64, channel string) string { - return fmt.Sprintf("live_message_%d_%s", orgID, channel) -} - -func (s *Storage) SaveLiveMessage(query *model.SaveLiveMessageQuery) error { - // Come back to saving into database after evaluating database structure. - s.cache.Set(getLiveMessageCacheKey(query.OrgID, query.Channel), model.LiveMessage{ - ID: 0, // Not used actually. - OrgID: query.OrgID, - Channel: query.Channel, - Data: query.Data, - Published: time.Now(), - }, 0) - return nil -} - -func (s *Storage) GetLiveMessage(query *model.GetLiveMessageQuery) (model.LiveMessage, bool, error) { - // Come back to saving into database after evaluating database structure. - m, ok := s.cache.Get(getLiveMessageCacheKey(query.OrgID, query.Channel)) - if !ok { - return model.LiveMessage{}, false, nil - } - msg, ok := m.(model.LiveMessage) - if !ok { - return model.LiveMessage{}, false, fmt.Errorf("unexpected live message type in cache: %T", m) - } - return msg, true, nil -} diff --git a/pkg/services/live/database/tests/setup.go b/pkg/services/live/database/tests/setup.go deleted file mode 100644 index 9ebf8f84a26..00000000000 --- a/pkg/services/live/database/tests/setup.go +++ /dev/null @@ -1,18 +0,0 @@ -package tests - -import ( - "testing" - "time" - - "github.com/grafana/grafana/pkg/infra/db" - "github.com/grafana/grafana/pkg/infra/localcache" - "github.com/grafana/grafana/pkg/services/live/database" -) - -// SetupTestStorage initializes a storage to used by the integration tests. -// This is required to properly register and execute migrations. -func SetupTestStorage(t *testing.T) *database.Storage { - sqlStore := db.InitTestDB(t) - localCache := localcache.New(time.Hour, time.Hour) - return database.NewStorage(sqlStore, localCache) -} diff --git a/pkg/services/live/database/tests/storage_test.go b/pkg/services/live/database/tests/storage_test.go deleted file mode 100644 index 0c57ec08e50..00000000000 --- a/pkg/services/live/database/tests/storage_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package tests - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/grafana/grafana/pkg/services/live/model" - "github.com/grafana/grafana/pkg/tests/testsuite" - "github.com/grafana/grafana/pkg/util/testutil" -) - -func TestMain(m *testing.M) { - testsuite.Run(m) -} - -func TestIntegrationLiveMessage(t *testing.T) { - testutil.SkipIntegrationTestInShortMode(t) - - storage := SetupTestStorage(t) - - getQuery := &model.GetLiveMessageQuery{ - OrgID: 1, - Channel: "test_channel", - } - _, ok, err := storage.GetLiveMessage(getQuery) - require.NoError(t, err) - require.False(t, ok) - - saveQuery := &model.SaveLiveMessageQuery{ - OrgID: 1, - Channel: "test_channel", - Data: []byte(`{}`), - } - err = storage.SaveLiveMessage(saveQuery) - require.NoError(t, err) - - msg, ok, err := storage.GetLiveMessage(getQuery) - require.NoError(t, err) - require.True(t, ok) - require.Equal(t, int64(1), msg.OrgID) - require.Equal(t, "test_channel", msg.Channel) - require.Equal(t, json.RawMessage(`{}`), msg.Data) - require.NotZero(t, msg.Published) - - // try saving again, should be replaced. - saveQuery2 := &model.SaveLiveMessageQuery{ - OrgID: 1, - Channel: "test_channel", - Data: []byte(`{"input": "hello"}`), - } - err = storage.SaveLiveMessage(saveQuery2) - require.NoError(t, err) - - getQuery2 := &model.GetLiveMessageQuery{ - OrgID: 1, - Channel: "test_channel", - } - msg2, ok, err := storage.GetLiveMessage(getQuery2) - require.NoError(t, err) - require.True(t, ok) - require.Equal(t, int64(1), msg2.OrgID) - require.Equal(t, "test_channel", msg2.Channel) - require.Equal(t, json.RawMessage(`{"input": "hello"}`), msg2.Data) - require.NotZero(t, msg2.Published) -} diff --git a/pkg/services/live/features/broadcast.go b/pkg/services/live/features/broadcast.go deleted file mode 100644 index fc9bbc56f2b..00000000000 --- a/pkg/services/live/features/broadcast.go +++ /dev/null @@ -1,70 +0,0 @@ -package features - -import ( - "context" - - "github.com/grafana/grafana-plugin-sdk-go/backend" - - "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/infra/log" - "github.com/grafana/grafana/pkg/services/live/model" -) - -var ( - logger = log.New("live.features") // scoped to all features? -) - -//go:generate mockgen -destination=broadcast_mock.go -package=features github.com/grafana/grafana/pkg/services/live/features LiveMessageStore - -type LiveMessageStore interface { - SaveLiveMessage(query *model.SaveLiveMessageQuery) error - GetLiveMessage(query *model.GetLiveMessageQuery) (model.LiveMessage, bool, error) -} - -// BroadcastRunner will simply broadcast all events to `grafana/broadcast/*` channels -// This assumes that data is a JSON object -type BroadcastRunner struct { - liveMessageStore LiveMessageStore -} - -func NewBroadcastRunner(liveMessageStore LiveMessageStore) *BroadcastRunner { - return &BroadcastRunner{liveMessageStore: liveMessageStore} -} - -// GetHandlerForPath called on init -func (b *BroadcastRunner) GetHandlerForPath(_ string) (model.ChannelHandler, error) { - return b, nil // all dashboards share the same handler -} - -// OnSubscribe will let anyone connect to the path -func (b *BroadcastRunner) OnSubscribe(_ context.Context, u identity.Requester, e model.SubscribeEvent) (model.SubscribeReply, backend.SubscribeStreamStatus, error) { - reply := model.SubscribeReply{ - Presence: true, - JoinLeave: true, - } - query := &model.GetLiveMessageQuery{ - OrgID: u.GetOrgID(), - Channel: e.Channel, - } - msg, ok, err := b.liveMessageStore.GetLiveMessage(query) - if err != nil { - return model.SubscribeReply{}, 0, err - } - if ok { - reply.Data = msg.Data - } - return reply, backend.SubscribeStreamStatusOK, nil -} - -// OnPublish is called when a client wants to broadcast on the websocket -func (b *BroadcastRunner) OnPublish(_ context.Context, u identity.Requester, e model.PublishEvent) (model.PublishReply, backend.PublishStreamStatus, error) { - query := &model.SaveLiveMessageQuery{ - OrgID: u.GetOrgID(), - Channel: e.Channel, - Data: e.Data, - } - if err := b.liveMessageStore.SaveLiveMessage(query); err != nil { - return model.PublishReply{}, 0, err - } - return model.PublishReply{Data: e.Data}, backend.PublishStreamStatusOK, nil -} diff --git a/pkg/services/live/features/broadcast_mock.go b/pkg/services/live/features/broadcast_mock.go deleted file mode 100644 index 54df3472a98..00000000000 --- a/pkg/services/live/features/broadcast_mock.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/grafana/grafana/pkg/services/live/features (interfaces: LiveMessageStore) - -// Package features is a generated GoMock package. -package features - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - - model "github.com/grafana/grafana/pkg/services/live/model" -) - -// MockLiveMessageStore is a mock of LiveMessageStore interface. -type MockLiveMessageStore struct { - ctrl *gomock.Controller - recorder *MockLiveMessageStoreMockRecorder -} - -// MockLiveMessageStoreMockRecorder is the mock recorder for MockLiveMessageStore. -type MockLiveMessageStoreMockRecorder struct { - mock *MockLiveMessageStore -} - -// NewMockLiveMessageStore creates a new mock instance. -func NewMockLiveMessageStore(ctrl *gomock.Controller) *MockLiveMessageStore { - mock := &MockLiveMessageStore{ctrl: ctrl} - mock.recorder = &MockLiveMessageStoreMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockLiveMessageStore) EXPECT() *MockLiveMessageStoreMockRecorder { - return m.recorder -} - -// GetLiveMessage mocks base method. -func (m *MockLiveMessageStore) GetLiveMessage(arg0 *model.GetLiveMessageQuery) (model.LiveMessage, bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLiveMessage", arg0) - ret0, _ := ret[0].(model.LiveMessage) - ret1, _ := ret[1].(bool) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetLiveMessage indicates an expected call of GetLiveMessage. -func (mr *MockLiveMessageStoreMockRecorder) GetLiveMessage(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLiveMessage", reflect.TypeOf((*MockLiveMessageStore)(nil).GetLiveMessage), arg0) -} - -// SaveLiveMessage mocks base method. -func (m *MockLiveMessageStore) SaveLiveMessage(arg0 *model.SaveLiveMessageQuery) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SaveLiveMessage", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SaveLiveMessage indicates an expected call of SaveLiveMessage. -func (mr *MockLiveMessageStoreMockRecorder) SaveLiveMessage(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveLiveMessage", reflect.TypeOf((*MockLiveMessageStore)(nil).SaveLiveMessage), arg0) -} diff --git a/pkg/services/live/features/broadcast_test.go b/pkg/services/live/features/broadcast_test.go deleted file mode 100644 index 25065087420..00000000000 --- a/pkg/services/live/features/broadcast_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package features - -import ( - "context" - "encoding/json" - "testing" - - "github.com/golang/mock/gomock" - "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/stretchr/testify/require" - - "github.com/grafana/grafana/pkg/services/live/model" - "github.com/grafana/grafana/pkg/services/user" -) - -func TestNewBroadcastRunner(t *testing.T) { - mockCtrl := gomock.NewController(t) - defer mockCtrl.Finish() - d := NewMockLiveMessageStore(mockCtrl) - br := NewBroadcastRunner(d) - require.NotNil(t, br) -} - -func TestBroadcastRunner_OnSubscribe(t *testing.T) { - mockCtrl := gomock.NewController(t) - defer mockCtrl.Finish() - mockDispatcher := NewMockLiveMessageStore(mockCtrl) - - channel := "stream/channel/test" - data := json.RawMessage(`{}`) - - mockDispatcher.EXPECT().GetLiveMessage(&model.GetLiveMessageQuery{ - OrgID: 1, - Channel: channel, - }).DoAndReturn(func(query *model.GetLiveMessageQuery) (model.LiveMessage, bool, error) { - return model.LiveMessage{ - Data: data, - }, true, nil - }).Times(1) - - br := NewBroadcastRunner(mockDispatcher) - require.NotNil(t, br) - handler, err := br.GetHandlerForPath("test") - require.NoError(t, err) - reply, status, err := handler.OnSubscribe( - context.Background(), - &user.SignedInUser{OrgID: 1, UserID: 2}, - model.SubscribeEvent{Channel: channel, Path: "test"}, - ) - require.NoError(t, err) - require.Equal(t, backend.SubscribeStreamStatusOK, status) - require.Equal(t, data, reply.Data) - require.True(t, reply.Presence) - require.True(t, reply.JoinLeave) - require.False(t, reply.Recover) -} - -func TestBroadcastRunner_OnPublish(t *testing.T) { - mockCtrl := gomock.NewController(t) - defer mockCtrl.Finish() - mockDispatcher := NewMockLiveMessageStore(mockCtrl) - - channel := "stream/channel/test" - data := json.RawMessage(`{}`) - var orgID int64 = 1 - - mockDispatcher.EXPECT().SaveLiveMessage(&model.SaveLiveMessageQuery{ - OrgID: orgID, - Channel: channel, - Data: data, - }).DoAndReturn(func(query *model.SaveLiveMessageQuery) error { - return nil - }).Times(1) - - br := NewBroadcastRunner(mockDispatcher) - require.NotNil(t, br) - handler, err := br.GetHandlerForPath("test") - require.NoError(t, err) - reply, status, err := handler.OnPublish( - context.Background(), - &user.SignedInUser{OrgID: 1, UserID: 2}, - model.PublishEvent{Channel: channel, Path: "test", Data: data}, - ) - require.NoError(t, err) - require.Equal(t, backend.PublishStreamStatusOK, status) - require.Equal(t, data, reply.Data) -} diff --git a/pkg/services/live/features/dashboard.go b/pkg/services/live/features/dashboard.go index 286dad7c49c..537042d2da0 100644 --- a/pkg/services/live/features/dashboard.go +++ b/pkg/services/live/features/dashboard.go @@ -6,11 +6,11 @@ import ( "fmt" "strings" + "github.com/grafana/authlib/types" "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/infra/db" - "github.com/grafana/grafana/pkg/services/accesscontrol" + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/live/model" ) @@ -22,48 +22,20 @@ const ( ActionDeleted actionType = "deleted" EditingStarted actionType = "editing-started" //EditingFinished actionType = "editing-finished" - - GitopsChannel = "grafana/dashboard/gitops" ) -type userDisplayDTO struct { - ID int64 `json:"id,omitempty"` - UID string `json:"uid,omitempty"` - Name string `json:"name,omitempty"` - Login string `json:"login,omitempty"` - AvatarURL string `json:"avatarUrl"` -} - -// Static function to parse a requester into a userDisplayDTO -func newUserDisplayDTOFromRequester(requester identity.Requester) *userDisplayDTO { - // nolint:staticcheck - userID, _ := requester.GetInternalID() - return &userDisplayDTO{ - ID: userID, - UID: requester.GetRawIdentifier(), - Login: requester.GetLogin(), - Name: requester.GetName(), - } -} - // DashboardEvent events related to dashboards type dashboardEvent struct { - UID string `json:"uid"` - Action actionType `json:"action"` // saved, editing, deleted - User *userDisplayDTO `json:"user,omitempty"` - SessionID string `json:"sessionId,omitempty"` - Message string `json:"message,omitempty"` - Dashboard *dashboards.Dashboard `json:"dashboard,omitempty"` - Error string `json:"error,omitempty"` + UID string `json:"uid"` + Action actionType `json:"action"` // saved, editing, deleted + SessionID string `json:"sessionId,omitempty"` } // DashboardHandler manages all the `grafana/dashboard/*` channels type DashboardHandler struct { - Publisher model.ChannelPublisher - ClientCount model.ChannelClientCount - Store db.DB - DashboardService dashboards.DashboardService - AccessControl accesscontrol.AccessControl + Publisher model.ChannelPublisher + ClientCount model.ChannelClientCount + AccessControl dashboards.DashboardAccessService } // GetHandlerForPath called on init @@ -77,23 +49,15 @@ func (h *DashboardHandler) OnSubscribe(ctx context.Context, user identity.Reques // make sure can view this dashboard if len(parts) == 2 && parts[0] == "uid" { - query := dashboards.GetDashboardQuery{UID: parts[1], OrgID: user.GetOrgID()} - _, err := h.DashboardService.GetDashboard(ctx, &query) - if err != nil { - logger.Error("Error getting dashboard", "query", query, "error", err) - return model.SubscribeReply{}, backend.SubscribeStreamStatusNotFound, nil + ns := types.OrgNamespaceFormatter(user.GetOrgID()) + ok, err := h.AccessControl.HasDashboardAccess(ctx, user, utils.VerbGet, ns, parts[1]) + if ok && err == nil { + return model.SubscribeReply{ + Presence: true, + JoinLeave: true, + }, backend.SubscribeStreamStatusOK, nil } - - evaluator := accesscontrol.EvalPermission(dashboards.ActionDashboardsRead, dashboards.ScopeDashboardsProvider.GetResourceScopeUID(parts[1])) - canView, err := h.AccessControl.Evaluate(ctx, user, evaluator) - if err != nil || !canView { - return model.SubscribeReply{}, backend.SubscribeStreamStatusPermissionDenied, err - } - - return model.SubscribeReply{ - Presence: true, - JoinLeave: true, - }, backend.SubscribeStreamStatusOK, nil + return model.SubscribeReply{}, backend.SubscribeStreamStatusPermissionDenied, err } // Unknown path @@ -116,32 +80,16 @@ func (h *DashboardHandler) OnPublish(ctx context.Context, requester identity.Req // just ignore the event return model.PublishReply{}, backend.PublishStreamStatusNotFound, fmt.Errorf("ignore???") } - query := dashboards.GetDashboardQuery{UID: parts[1], OrgID: requester.GetOrgID()} - _, err = h.DashboardService.GetDashboard(ctx, &query) - if err != nil { - logger.Error("Unknown dashboard", "query", query) - return model.PublishReply{}, backend.PublishStreamStatusNotFound, nil - } - evaluator := accesscontrol.EvalPermission(dashboards.ActionDashboardsWrite, dashboards.ScopeDashboardsProvider.GetResourceScopeUID(parts[1])) - canEdit, err := h.AccessControl.Evaluate(ctx, requester, evaluator) - if err != nil { - return model.PublishReply{}, backend.PublishStreamStatusNotFound, fmt.Errorf("internal error") + ns := types.OrgNamespaceFormatter(requester.GetOrgID()) + ok, err := h.AccessControl.HasDashboardAccess(ctx, requester, utils.VerbUpdate, ns, parts[1]) + if ok && err == nil { + msg, err := json.Marshal(event) + if err != nil { + return model.PublishReply{}, backend.PublishStreamStatusNotFound, fmt.Errorf("internal error") + } + return model.PublishReply{Data: msg}, backend.PublishStreamStatusOK, nil } - - // Ignore edit events if the user can not edit - if !canEdit { - return model.PublishReply{}, backend.PublishStreamStatusNotFound, nil // NOOP - } - - // Tell everyone who is editing - event.User = newUserDisplayDTOFromRequester(requester) - - msg, err := json.Marshal(event) - if err != nil { - return model.PublishReply{}, backend.PublishStreamStatusNotFound, fmt.Errorf("internal error") - } - return model.PublishReply{Data: msg}, backend.PublishStreamStatusOK, nil } return model.PublishReply{}, backend.PublishStreamStatusNotFound, nil @@ -153,55 +101,21 @@ func (h *DashboardHandler) publish(orgID int64, event dashboardEvent) error { if err != nil { return err } - - // Only broadcast non-error events - if event.Error == "" { - err = h.Publisher(orgID, "grafana/dashboard/uid/"+event.UID, msg) - if err != nil { - return err - } - } - - // Send everything to the gitops channel - return h.Publisher(orgID, GitopsChannel, msg) + return h.Publisher(orgID, "grafana/dashboard/uid/"+event.UID, msg) } // DashboardSaved will broadcast to all connected dashboards -func (h *DashboardHandler) DashboardSaved(orgID int64, requester identity.Requester, message string, dashboard *dashboards.Dashboard, err error) error { - if err != nil && !h.HasGitOpsObserver(orgID) { - return nil // only broadcast if it was OK - } - - msg := dashboardEvent{ - UID: dashboard.UID, - Action: ActionSaved, - User: newUserDisplayDTOFromRequester(requester), - Message: message, - Dashboard: dashboard, - } - - if err != nil { - msg.Error = err.Error() - } - - return h.publish(orgID, msg) -} - -// DashboardDeleted will broadcast to all connected dashboards -func (h *DashboardHandler) DashboardDeleted(orgID int64, requester identity.Requester, uid string) error { +func (h *DashboardHandler) DashboardSaved(orgID int64, uid string) error { return h.publish(orgID, dashboardEvent{ UID: uid, - Action: ActionDeleted, - User: newUserDisplayDTOFromRequester(requester), + Action: ActionSaved, }) } -// HasGitOpsObserver will return true if anyone is listening to the `gitops` channel -func (h *DashboardHandler) HasGitOpsObserver(orgID int64) bool { - count, err := h.ClientCount(orgID, GitopsChannel) - if err != nil { - logger.Error("Error getting client count", "error", err) - return false - } - return count > 0 +// DashboardDeleted will broadcast to all connected dashboards +func (h *DashboardHandler) DashboardDeleted(orgID int64, uid string) error { + return h.publish(orgID, dashboardEvent{ + UID: uid, + Action: ActionDeleted, + }) } diff --git a/pkg/services/live/features/plugin.go b/pkg/services/live/features/plugin.go index de7a55ea2ab..1f7d0768078 100644 --- a/pkg/services/live/features/plugin.go +++ b/pkg/services/live/features/plugin.go @@ -5,9 +5,11 @@ import ( "errors" "github.com/centrifugal/centrifuge" + "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/live/model" "github.com/grafana/grafana/pkg/services/live/orgchannel" diff --git a/pkg/services/live/live.go b/pkg/services/live/live.go index 4d91eae3e5e..7dbca506e2c 100644 --- a/pkg/services/live/live.go +++ b/pkg/services/live/live.go @@ -15,7 +15,6 @@ import ( "github.com/centrifugal/centrifuge" "github.com/gobwas/glob" - jsoniter "github.com/json-iterator/go" "github.com/redis/go-redis/v9" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" @@ -25,25 +24,19 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/live" - "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" - "github.com/grafana/grafana/pkg/apimachinery/errutil" "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/infra/db" - "github.com/grafana/grafana/pkg/infra/localcache" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/middleware/requestmeta" "github.com/grafana/grafana/pkg/plugins" - "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/apiserver" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/featuremgmt" - "github.com/grafana/grafana/pkg/services/live/database" "github.com/grafana/grafana/pkg/services/live/features" "github.com/grafana/grafana/pkg/services/live/livecontext" "github.com/grafana/grafana/pkg/services/live/liveplugin" @@ -57,8 +50,6 @@ import ( "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/pluginsintegration/plugincontext" "github.com/grafana/grafana/pkg/services/pluginsintegration/pluginstore" - "github.com/grafana/grafana/pkg/services/query" - "github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/web" @@ -78,30 +69,23 @@ type CoreGrafanaScope struct { Dashboards DashboardActivityChannel } -func ProvideService(plugCtxProvider *plugincontext.Provider, cfg *setting.Cfg, routeRegister routing.RouteRegister, - pluginStore pluginstore.Store, pluginClient plugins.Client, cacheService *localcache.CacheService, - dataSourceCache datasources.CacheService, sqlStore db.DB, secretsService secrets.Service, - usageStatsService usagestats.Service, queryDataService query.Service, toggles featuremgmt.FeatureToggles, - accessControl accesscontrol.AccessControl, dashboardService dashboards.DashboardService, - orgService org.Service, configProvider apiserver.RestConfigProvider) (*GrafanaLive, error) { +func ProvideService(cfg *setting.Cfg, routeRegister routing.RouteRegister, plugCtxProvider *plugincontext.Provider, + pluginStore pluginstore.Store, pluginClient plugins.Client, dataSourceCache datasources.CacheService, + usageStatsService usagestats.Service, toggles featuremgmt.FeatureToggles, + dashboardService dashboards.DashboardAccessService, + configProvider apiserver.RestConfigProvider) (*GrafanaLive, error) { g := &GrafanaLive{ Cfg: cfg, Features: toggles, PluginContextProvider: plugCtxProvider, - RouteRegister: routeRegister, pluginStore: pluginStore, pluginClient: pluginClient, - CacheService: cacheService, DataSourceCache: dataSourceCache, - SQLStore: sqlStore, - SecretsService: secretsService, - queryDataService: queryDataService, channels: make(map[string]model.ChannelHandler), GrafanaScope: CoreGrafanaScope{ Features: make(map[string]model.ChannelHandlerFactory), }, usageStatsService: usageStatsService, - orgService: orgService, keyPrefix: "gf_live", } @@ -184,22 +168,13 @@ func ProvideService(plugCtxProvider *plugincontext.Provider, cfg *setting.Cfg, r // Initialize the main features dash := &features.DashboardHandler{ - Publisher: g.Publish, - ClientCount: g.ClientCount, - Store: sqlStore, - DashboardService: dashboardService, - AccessControl: accessControl, + Publisher: g.Publish, + ClientCount: g.ClientCount, + AccessControl: dashboardService, } - g.storage = database.NewStorage(g.SQLStore, g.CacheService) g.GrafanaScope.Dashboards = dash g.GrafanaScope.Features["dashboard"] = dash - g.GrafanaScope.Features["broadcast"] = features.NewBroadcastRunner(g.storage) - - // Testing watch with just the provisioning support -- this will be removed when it is well validated - //nolint:staticcheck // not yet migrated to OpenFeature - if toggles.IsEnabledGlobally(featuremgmt.FlagProvisioning) { - g.GrafanaScope.Features["watch"] = features.NewWatchRunner(g.Publish, configProvider) - } + g.GrafanaScope.Features["watch"] = features.NewWatchRunner(g.Publish, configProvider) g.surveyCaller = survey.NewCaller(managedStreamRunner, node) err = g.surveyCaller.SetupHandlers() @@ -388,14 +363,14 @@ func ProvideService(plugCtxProvider *plugincontext.Provider, cfg *setting.Cfg, r UserID: strconv.FormatInt(id, 10), } newCtx := centrifuge.SetCredentials(ctx.Req.Context(), cred) - newCtx = livecontext.SetContextSignedUser(newCtx, user) + newCtx = identity.WithRequester(newCtx, user) r := ctx.Req.WithContext(newCtx) wsHandler.ServeHTTP(ctx.Resp, r) } g.pushWebsocketHandler = func(ctx *contextmodel.ReqContext) { user := ctx.SignedInUser - newCtx := livecontext.SetContextSignedUser(ctx.Req.Context(), user) + newCtx := identity.WithRequester(ctx.Req.Context(), user) newCtx = livecontext.SetContextStreamID(newCtx, web.Params(ctx.Req)[":streamId"]) r := ctx.Req.WithContext(newCtx) pushWSHandler.ServeHTTP(ctx.Resp, r) @@ -403,17 +378,17 @@ func ProvideService(plugCtxProvider *plugincontext.Provider, cfg *setting.Cfg, r g.pushPipelineWebsocketHandler = func(ctx *contextmodel.ReqContext) { user := ctx.SignedInUser - newCtx := livecontext.SetContextSignedUser(ctx.Req.Context(), user) + newCtx := identity.WithRequester(ctx.Req.Context(), user) newCtx = livecontext.SetContextChannelID(newCtx, web.Params(ctx.Req)["*"]) r := ctx.Req.WithContext(newCtx) pushPipelineWSHandler.ServeHTTP(ctx.Resp, r) } - g.RouteRegister.Group("/api/live", func(group routing.RouteRegister) { + routeRegister.Group("/api/live", func(group routing.RouteRegister) { group.Get("/ws", g.websocketHandler) }, middleware.ReqSignedIn, requestmeta.SetSLOGroup(requestmeta.SLOGroupNone)) - g.RouteRegister.Group("/api/live", func(group routing.RouteRegister) { + routeRegister.Group("/api/live", func(group routing.RouteRegister) { group.Get("/push/:streamId", g.pushWebsocketHandler) group.Get("/pipeline/push/*", g.pushPipelineWebsocketHandler) }, middleware.ReqOrgAdmin, requestmeta.SetSLOGroup(requestmeta.SLOGroupNone)) @@ -472,17 +447,11 @@ type GrafanaLive struct { PluginContextProvider *plugincontext.Provider Cfg *setting.Cfg Features featuremgmt.FeatureToggles - RouteRegister routing.RouteRegister - CacheService *localcache.CacheService DataSourceCache datasources.CacheService - SQLStore db.DB - SecretsService secrets.Service pluginStore pluginstore.Store pluginClient plugins.Client - queryDataService query.Service - orgService org.Service - keyPrefix string + keyPrefix string // HA prefix for grafana cloud (since the org is always 1) node *centrifuge.Node surveyCaller *survey.Caller @@ -505,7 +474,6 @@ type GrafanaLive struct { contextGetter *liveplugin.ContextGetter runStreamManager *runstream.Manager - storage *database.Storage usageStatsService usagestats.Service usageStats usageStats @@ -513,18 +481,17 @@ type GrafanaLive struct { // DashboardActivityChannel is a service to advertise dashboard activity type DashboardActivityChannel interface { - // Called when a dashboard is saved -- this includes the error so we can support a - // gitops workflow that knows if the value was saved to the local database or not - // in many cases all direct save requests will fail, but the request should be forwarded - // to any gitops observers - DashboardSaved(orgID int64, requester identity.Requester, message string, dashboard *dashboards.Dashboard, err error) error + // Called when a dashboard is saved + DashboardSaved(orgID int64, uid string) error // Called when a dashboard is deleted - DashboardDeleted(orgID int64, requester identity.Requester, uid string) error + DashboardDeleted(orgID int64, uid string) error +} - // Experimental! Indicate is GitOps is active. This really means - // someone is subscribed to the `grafana/dashboards/gitops` channel - HasGitOpsObserver(orgID int64) bool +// ProvideDashboardActivityChannel extracts the DashboardActivityChannel from GrafanaLive. +// This is used by wire to inject the channel into the dashboard API service. +func ProvideDashboardActivityChannel(live *GrafanaLive) DashboardActivityChannel { + return live.GrafanaScope.Dashboards } func (g *GrafanaLive) getStreamPlugin(ctx context.Context, pluginID string) (backend.StreamHandler, error) { @@ -674,18 +641,13 @@ func (g *GrafanaLive) HandleDatasourceUpdate(orgID int64, dsUID string) { } } -// Use a configuration that's compatible with the standard library -// to minimize the risk of introducing bugs. This will make sure -// that map keys is ordered. -var jsonStd = jsoniter.ConfigCompatibleWithStandardLibrary - func (g *GrafanaLive) handleOnRPC(clientContextWithSpan context.Context, client *centrifuge.Client, e centrifuge.RPCEvent) (centrifuge.RPCReply, error) { logger.Debug("Client calls RPC", "user", client.UserID(), "client", client.ID(), "method", e.Method) if e.Method != "grafana.query" { return centrifuge.RPCReply{}, centrifuge.ErrorMethodNotFound } - user, ok := livecontext.GetContextSignedUser(clientContextWithSpan) - if !ok { + user, err := identity.GetRequester(clientContextWithSpan) + if err != nil { logger.Error("No user found in context", "user", client.UserID(), "client", client.ID(), "method", e.Method) return centrifuge.RPCReply{}, centrifuge.ErrorInternal } @@ -695,38 +657,15 @@ func (g *GrafanaLive) handleOnRPC(clientContextWithSpan context.Context, client return centrifuge.RPCReply{}, centrifuge.ErrorExpired } - var req dtos.MetricRequest - err := json.Unmarshal(e.Data, &req) - if err != nil { - return centrifuge.RPCReply{}, centrifuge.ErrorBadRequest - } - resp, err := g.queryDataService.QueryData(clientContextWithSpan, user, false, req) - if err != nil { - logger.Error("Error query data", "user", client.UserID(), "client", client.ID(), "method", e.Method, "error", err) - if errors.Is(err, datasources.ErrDataSourceAccessDenied) { - return centrifuge.RPCReply{}, ¢rifuge.Error{Code: uint32(http.StatusForbidden), Message: http.StatusText(http.StatusForbidden)} - } - var gfErr errutil.Error - if errors.As(err, &gfErr) && gfErr.Reason.Status() == errutil.StatusBadRequest { - return centrifuge.RPCReply{}, ¢rifuge.Error{Code: uint32(http.StatusBadRequest), Message: http.StatusText(http.StatusBadRequest)} - } - return centrifuge.RPCReply{}, centrifuge.ErrorInternal - } - data, err := jsonStd.Marshal(resp) - if err != nil { - logger.Error("Error marshaling query response", "user", client.UserID(), "client", client.ID(), "method", e.Method, "error", err) - return centrifuge.RPCReply{}, centrifuge.ErrorInternal - } - return centrifuge.RPCReply{ - Data: data, - }, nil + // RPC events not available + return centrifuge.RPCReply{}, centrifuge.ErrorNotAvailable } func (g *GrafanaLive) handleOnSubscribe(clientContextWithSpan context.Context, client *centrifuge.Client, e centrifuge.SubscribeEvent) (centrifuge.SubscribeReply, error) { logger.Debug("Client wants to subscribe", "user", client.UserID(), "client", client.ID(), "channel", e.Channel) - user, ok := livecontext.GetContextSignedUser(clientContextWithSpan) - if !ok { + user, err := identity.GetRequester(clientContextWithSpan) + if err != nil { logger.Error("No user found in context", "user", client.UserID(), "client", client.ID(), "channel", e.Channel) return centrifuge.SubscribeReply{}, centrifuge.ErrorInternal } @@ -831,8 +770,8 @@ func (g *GrafanaLive) handleOnSubscribe(clientContextWithSpan context.Context, c func (g *GrafanaLive) handleOnPublish(clientCtxWithSpan context.Context, client *centrifuge.Client, e centrifuge.PublishEvent) (centrifuge.PublishReply, error) { logger.Debug("Client wants to publish", "user", client.UserID(), "client", client.ID(), "channel", e.Channel) - user, ok := livecontext.GetContextSignedUser(clientCtxWithSpan) - if !ok { + user, err := identity.GetRequester(clientCtxWithSpan) + if err != nil { logger.Error("No user found in context", "user", client.UserID(), "client", client.ID(), "channel", e.Channel) return centrifuge.PublishReply{}, centrifuge.ErrorInternal } @@ -1084,7 +1023,7 @@ func (g *GrafanaLive) ClientCount(orgID int64, channel string) (int, error) { } func (g *GrafanaLive) HandleHTTPPublish(ctx *contextmodel.ReqContext) response.Response { - cmd := dtos.LivePublishCmd{} + cmd := model.LivePublishCmd{} if err := web.Bind(ctx.Req, &cmd); err != nil { return response.Error(http.StatusBadRequest, "bad request data", err) } @@ -1123,7 +1062,7 @@ func (g *GrafanaLive) HandleHTTPPublish(ctx *contextmodel.ReqContext) response.R logger.Error("Error processing input", "user", user, "channel", channel, "error", err) return response.Error(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError), nil) } - return response.JSON(http.StatusOK, dtos.LivePublishResponse{}) + return response.JSON(http.StatusOK, model.LivePublishResponse{}) } } @@ -1151,7 +1090,7 @@ func (g *GrafanaLive) HandleHTTPPublish(ctx *contextmodel.ReqContext) response.R } } logger.Debug("Publication successful", "identity", ctx.GetID(), "channel", cmd.Channel) - return response.JSON(http.StatusOK, dtos.LivePublishResponse{}) + return response.JSON(http.StatusOK, model.LivePublishResponse{}) } type streamChannelListResponse struct { @@ -1178,12 +1117,6 @@ func (g *GrafanaLive) HandleListHTTP(c *contextmodel.ReqContext) response.Respon // HandleInfoHTTP special http response for func (g *GrafanaLive) HandleInfoHTTP(ctx *contextmodel.ReqContext) response.Response { - path := web.Params(ctx.Req)["*"] - if path == "grafana/dashboards/gitops" { - return response.JSON(http.StatusOK, util.DynMap{ - "active": g.GrafanaScope.Dashboards.HasGitOpsObserver(ctx.GetOrgID()), - }) - } return response.JSONStreaming(http.StatusNotFound, util.DynMap{ "message": "Info is not supported for this channel", }) @@ -1405,71 +1338,6 @@ func (g *GrafanaLive) HandleWriteConfigsPostHTTP(c *contextmodel.ReqContext) res }) } -// HandleWriteConfigsPutHTTP ... -func (g *GrafanaLive) HandleWriteConfigsPutHTTP(c *contextmodel.ReqContext) response.Response { - body, err := io.ReadAll(c.Req.Body) - if err != nil { - return response.Error(http.StatusInternalServerError, "Error reading body", err) - } - var cmd pipeline.WriteConfigUpdateCmd - err = json.Unmarshal(body, &cmd) - if err != nil { - return response.Error(http.StatusBadRequest, "Error decoding write config update command", err) - } - if cmd.UID == "" { - return response.Error(http.StatusBadRequest, "UID required", nil) - } - existingBackend, ok, err := g.pipelineStorage.GetWriteConfig(c.Req.Context(), c.GetOrgID(), pipeline.WriteConfigGetCmd{ - UID: cmd.UID, - }) - if err != nil { - return response.Error(http.StatusInternalServerError, "Failed to get write config", err) - } - if ok { - if cmd.SecureSettings == nil { - cmd.SecureSettings = map[string]string{} - } - secureJSONData, err := g.SecretsService.DecryptJsonData(c.Req.Context(), existingBackend.SecureSettings) - if err != nil { - logger.Error("Error decrypting secure settings", "error", err) - return response.Error(http.StatusInternalServerError, "Error decrypting secure settings", err) - } - for k, v := range secureJSONData { - if _, ok := cmd.SecureSettings[k]; !ok { - cmd.SecureSettings[k] = v - } - } - } - result, err := g.pipelineStorage.UpdateWriteConfig(c.Req.Context(), c.GetOrgID(), cmd) - if err != nil { - return response.Error(http.StatusInternalServerError, "Failed to update write config", err) - } - return response.JSON(http.StatusOK, util.DynMap{ - "writeConfig": pipeline.WriteConfigToDto(result), - }) -} - -// HandleWriteConfigsDeleteHTTP ... -func (g *GrafanaLive) HandleWriteConfigsDeleteHTTP(c *contextmodel.ReqContext) response.Response { - body, err := io.ReadAll(c.Req.Body) - if err != nil { - return response.Error(http.StatusInternalServerError, "Error reading body", err) - } - var cmd pipeline.WriteConfigDeleteCmd - err = json.Unmarshal(body, &cmd) - if err != nil { - return response.Error(http.StatusBadRequest, "Error decoding write config delete command", err) - } - if cmd.UID == "" { - return response.Error(http.StatusBadRequest, "UID required", nil) - } - err = g.pipelineStorage.DeleteWriteConfig(c.Req.Context(), c.GetOrgID(), cmd) - if err != nil { - return response.Error(http.StatusInternalServerError, "Failed to delete write config", err) - } - return response.JSON(http.StatusOK, util.DynMap{}) -} - // Write to the standard log15 logger func handleLog(msg centrifuge.LogEntry) { arr := make([]interface{}, 0) diff --git a/pkg/services/live/live_test.go b/pkg/services/live/live_test.go index 00ce4bee3f4..9412f32c6f8 100644 --- a/pkg/services/live/live_test.go +++ b/pkg/services/live/live_test.go @@ -11,20 +11,16 @@ import ( "testing" "time" + "github.com/centrifugal/centrifuge" "github.com/go-jose/go-jose/v4" "github.com/go-jose/go-jose/v4/jwt" "github.com/stretchr/testify/require" - "github.com/centrifugal/centrifuge" - "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/featuremgmt" - "github.com/grafana/grafana/pkg/services/live/livecontext" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tests/testsuite" "github.com/grafana/grafana/pkg/util/testutil" @@ -245,7 +241,7 @@ func Test_handleOnPublish_IDTokenExpiration(t *testing.T) { t.Run("expired token", func(t *testing.T) { expiration := time.Now().Add(-time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnPublish(ctx, client, centrifuge.PublishEvent{ Channel: "test", Data: []byte("test"), @@ -257,7 +253,7 @@ func Test_handleOnPublish_IDTokenExpiration(t *testing.T) { t.Run("unexpired token", func(t *testing.T) { expiration := time.Now().Add(time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnPublish(ctx, client, centrifuge.PublishEvent{ Channel: "test", Data: []byte("test"), @@ -280,7 +276,7 @@ func Test_handleOnRPC_IDTokenExpiration(t *testing.T) { t.Run("expired token", func(t *testing.T) { expiration := time.Now().Add(-time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnRPC(ctx, client, centrifuge.RPCEvent{ Method: "grafana.query", Data: []byte("test"), @@ -292,7 +288,7 @@ func Test_handleOnRPC_IDTokenExpiration(t *testing.T) { t.Run("unexpired token", func(t *testing.T) { expiration := time.Now().Add(time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnRPC(ctx, client, centrifuge.RPCEvent{ Method: "grafana.query", Data: []byte("test"), @@ -315,7 +311,7 @@ func Test_handleOnSubscribe_IDTokenExpiration(t *testing.T) { t.Run("expired token", func(t *testing.T) { expiration := time.Now().Add(-time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnSubscribe(ctx, client, centrifuge.SubscribeEvent{ Channel: "test", }) @@ -326,7 +322,7 @@ func Test_handleOnSubscribe_IDTokenExpiration(t *testing.T) { t.Run("unexpired token", func(t *testing.T) { expiration := time.Now().Add(time.Hour) token := createToken(t, &expiration) - ctx := livecontext.SetContextSignedUser(context.Background(), &identity.StaticRequester{IDToken: token}) + ctx := identity.WithRequester(context.Background(), &identity.StaticRequester{IDToken: token}) reply, err := g.handleOnSubscribe(ctx, client, centrifuge.SubscribeEvent{ Channel: "test", }) @@ -343,25 +339,26 @@ func setupLiveService(cfg *setting.Cfg, t *testing.T) (*GrafanaLive, error) { cfg = setting.NewCfg() } - return ProvideService(nil, - cfg, + return ProvideService(cfg, routing.NewRouteRegister(), - nil, nil, nil, nil, - db.InitTestDB(t), + nil, nil, nil, nil, &usagestats.UsageStatsMock{T: t}, - nil, featuremgmt.WithFeatures(), - acimpl.ProvideAccessControl(featuremgmt.WithFeatures()), &dashboards.FakeDashboardService{}, - nil, nil) + nil) } type dummyTransport struct { name string } +var ( + _ centrifuge.Transport = (*dummyTransport)(nil) +) + func (t *dummyTransport) Name() string { return t.name } +func (t *dummyTransport) AcceptProtocol() string { return "" } func (t *dummyTransport) Protocol() centrifuge.ProtocolType { return centrifuge.ProtocolTypeJSON } func (t *dummyTransport) ProtocolVersion() centrifuge.ProtocolVersion { return centrifuge.ProtocolVersion2 diff --git a/pkg/services/live/livecontext/context.go b/pkg/services/live/livecontext/context.go index b7c18394cab..3184dc22a93 100644 --- a/pkg/services/live/livecontext/context.go +++ b/pkg/services/live/livecontext/context.go @@ -2,27 +2,8 @@ package livecontext import ( "context" - - "github.com/grafana/grafana/pkg/apimachinery/identity" ) -type signedUserContextKeyType int - -var signedUserContextKey signedUserContextKeyType - -func SetContextSignedUser(ctx context.Context, user identity.Requester) context.Context { - ctx = context.WithValue(ctx, signedUserContextKey, user) - return ctx -} - -func GetContextSignedUser(ctx context.Context) (identity.Requester, bool) { - if val := ctx.Value(signedUserContextKey); val != nil { - user, ok := val.(identity.Requester) - return user, ok - } - return nil, false -} - type streamIDContextKey struct{} func SetContextStreamID(ctx context.Context, streamID string) context.Context { diff --git a/pkg/services/live/model/model.go b/pkg/services/live/model/model.go index 03e7ddcf4eb..1f1c782c914 100644 --- a/pkg/services/live/model/model.go +++ b/pkg/services/live/model/model.go @@ -67,21 +67,9 @@ type ChannelHandlerFactory interface { GetHandlerForPath(path string) (ChannelHandler, error) } -type LiveMessage struct { - ID int64 `xorm:"pk autoincr 'id'"` - OrgID int64 `xorm:"org_id"` - Channel string - Data json.RawMessage - Published time.Time +type LivePublishCmd struct { + Channel string `json:"channel"` + Data json.RawMessage `json:"data,omitempty"` } -type SaveLiveMessageQuery struct { - OrgID int64 `xorm:"org_id"` - Channel string - Data json.RawMessage -} - -type GetLiveMessageQuery struct { - OrgID int64 `xorm:"org_id"` - Channel string -} +type LivePublishResponse struct{} diff --git a/pkg/services/live/pipeline/data_output_builtin.go b/pkg/services/live/pipeline/data_output_builtin.go index 1a4ab62f941..a3c99a9f7d2 100644 --- a/pkg/services/live/pipeline/data_output_builtin.go +++ b/pkg/services/live/pipeline/data_output_builtin.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/grafana/grafana/pkg/services/live/livecontext" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/services/live/model" ) @@ -25,8 +25,8 @@ func (s *BuiltinDataOutput) Type() string { } func (s *BuiltinDataOutput) OutputData(ctx context.Context, vars Vars, data []byte) ([]*ChannelData, error) { - u, ok := livecontext.GetContextSignedUser(ctx) - if !ok { + u, err := identity.GetRequester(ctx) + if err != nil { return nil, errors.New("user not found in context") } handler, _, err := s.channelHandlerGetter.GetChannelHandler(ctx, u, vars.Channel) diff --git a/pkg/services/live/pipeline/subscribe_builtin.go b/pkg/services/live/pipeline/subscribe_builtin.go index e9888c59305..20c2660426c 100644 --- a/pkg/services/live/pipeline/subscribe_builtin.go +++ b/pkg/services/live/pipeline/subscribe_builtin.go @@ -7,7 +7,6 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/live" "github.com/grafana/grafana/pkg/apimachinery/identity" - "github.com/grafana/grafana/pkg/services/live/livecontext" "github.com/grafana/grafana/pkg/services/live/model" ) @@ -30,8 +29,8 @@ func (s *BuiltinSubscriber) Type() string { } func (s *BuiltinSubscriber) Subscribe(ctx context.Context, vars Vars, data []byte) (model.SubscribeReply, backend.SubscribeStreamStatus, error) { - u, ok := livecontext.GetContextSignedUser(ctx) - if !ok { + u, err := identity.GetRequester(ctx) + if err != nil { return model.SubscribeReply{}, backend.SubscribeStreamStatusPermissionDenied, nil } handler, _, err := s.channelHandlerGetter.GetChannelHandler(ctx, u, vars.Channel) diff --git a/pkg/services/live/pipeline/subscribe_managed_stream.go b/pkg/services/live/pipeline/subscribe_managed_stream.go index 4f668469995..ce26d0d1a30 100644 --- a/pkg/services/live/pipeline/subscribe_managed_stream.go +++ b/pkg/services/live/pipeline/subscribe_managed_stream.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/grafana/grafana/pkg/services/live/livecontext" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/services/live/managedstream" "github.com/grafana/grafana/pkg/services/live/model" ) @@ -30,8 +30,8 @@ func (s *ManagedStreamSubscriber) Subscribe(ctx context.Context, vars Vars, _ [] logger.Error("Error getting managed stream", "error", err) return model.SubscribeReply{}, 0, err } - u, ok := livecontext.GetContextSignedUser(ctx) - if !ok { + u, err := identity.GetRequester(ctx) + if err != nil { return model.SubscribeReply{}, backend.SubscribeStreamStatusPermissionDenied, nil } return stream.OnSubscribe(ctx, u, model.SubscribeEvent{ diff --git a/pkg/services/live/pipeline/subscribe_multiple.go b/pkg/services/live/pipeline/subscribe_multiple.go index 9b7b6789236..a7a6148a99d 100644 --- a/pkg/services/live/pipeline/subscribe_multiple.go +++ b/pkg/services/live/pipeline/subscribe_multiple.go @@ -4,7 +4,6 @@ import ( "context" "github.com/grafana/grafana-plugin-sdk-go/backend" - "github.com/grafana/grafana/pkg/services/live/model" ) diff --git a/pkg/services/live/pushws/push_pipeline.go b/pkg/services/live/pushws/push_pipeline.go index 0005318bebd..a455e26ba01 100644 --- a/pkg/services/live/pushws/push_pipeline.go +++ b/pkg/services/live/pushws/push_pipeline.go @@ -5,6 +5,7 @@ import ( "github.com/gorilla/websocket" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/services/live/convert" "github.com/grafana/grafana/pkg/services/live/livecontext" "github.com/grafana/grafana/pkg/services/live/pipeline" @@ -44,8 +45,8 @@ func (s *PipelinePushHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) return } - user, ok := livecontext.GetContextSignedUser(r.Context()) - if !ok { + user, err := identity.GetRequester(r.Context()) + if err != nil { logger.Error("No user found in context") rw.WriteHeader(http.StatusInternalServerError) return diff --git a/pkg/services/live/pushws/push_stream.go b/pkg/services/live/pushws/push_stream.go index 649a97d9f34..fafcd79f3f0 100644 --- a/pkg/services/live/pushws/push_stream.go +++ b/pkg/services/live/pushws/push_stream.go @@ -5,8 +5,9 @@ import ( "time" "github.com/gorilla/websocket" - liveDto "github.com/grafana/grafana-plugin-sdk-go/live" + liveDto "github.com/grafana/grafana-plugin-sdk-go/live" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/services/live/convert" "github.com/grafana/grafana/pkg/services/live/livecontext" "github.com/grafana/grafana/pkg/services/live/managedstream" @@ -47,8 +48,8 @@ func (s *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) { return } - user, ok := livecontext.GetContextSignedUser(r.Context()) - if !ok { + user, err := identity.GetRequester(r.Context()) + if err != nil { logger.Error("No user found in context") rw.WriteHeader(http.StatusInternalServerError) return diff --git a/pkg/services/ngalert/accesscontrol.go b/pkg/services/ngalert/accesscontrol.go index e36c123c621..6754b3c0680 100644 --- a/pkg/services/ngalert/accesscontrol.go +++ b/pkg/services/ngalert/accesscontrol.go @@ -173,6 +173,7 @@ var ( Permissions: accesscontrol.ConcatPermissions(templatesReaderRole.Role.Permissions, []accesscontrol.Permission{ {Action: accesscontrol.ActionAlertingNotificationsTemplatesWrite}, {Action: accesscontrol.ActionAlertingNotificationsTemplatesDelete}, + {Action: accesscontrol.ActionAlertingNotificationsTemplatesTest}, }), }, } @@ -288,12 +289,13 @@ var ( Role: accesscontrol.RoleDTO{ Name: accesscontrol.FixedRolePrefix + "alerting:admin", DisplayName: "Full admin access", - Description: "Full write access in Grafana and all external providers, including their permissions and secrets", + Description: "Full write access in Grafana and all external providers, including their permissions, protected fields and secrets", Group: models.AlertRolesGroup, Permissions: accesscontrol.ConcatPermissions(alertingWriterRole.Role.Permissions, []accesscontrol.Permission{ {Action: accesscontrol.ActionAlertingReceiversPermissionsRead, Scope: models.ScopeReceiversAll}, {Action: accesscontrol.ActionAlertingReceiversPermissionsWrite, Scope: models.ScopeReceiversAll}, {Action: accesscontrol.ActionAlertingReceiversReadSecrets, Scope: models.ScopeReceiversAll}, + {Action: accesscontrol.ActionAlertingReceiversUpdateProtected, Scope: models.ScopeReceiversAll}, }), }, Grants: []string{string(org.RoleAdmin)}, diff --git a/pkg/services/ngalert/accesscontrol/receivers.go b/pkg/services/ngalert/accesscontrol/receivers.go index eb2904854bf..f12a9114912 100644 --- a/pkg/services/ngalert/accesscontrol/receivers.go +++ b/pkg/services/ngalert/accesscontrol/receivers.go @@ -95,6 +95,26 @@ var ( ) } + // Asserts pre-conditions for access to modify protected fields of receivers. If this evaluates to false, the user cannot modify protected fields of any receivers. + updateReceiversProtectedPreConditionsEval = ac.EvalAll( + updateReceiversPreConditionsEval, + ac.EvalPermission(ac.ActionAlertingReceiversUpdateProtected), // Action for receivers. UID scope. + ) + + // Asserts access to modify protected fields of a specific receiver. + updateReceiverProtectedEval = func(uid string) ac.Evaluator { + return ac.EvalAll( + updateReceiverEval(uid), + ac.EvalPermission(ac.ActionAlertingReceiversUpdateProtected, models.ScopeReceiversProvider.GetResourceScopeUID(uid)), + ) + } + + // Asserts access to modify protected fields of all receivers. + updateAllReceiverProtectedEval = ac.EvalAll( + updateAllReceiversEval, + ac.EvalPermission(ac.ActionAlertingReceiversUpdateProtected, models.ScopeReceiversAll), + ) + // Delete // Asserts pre-conditions for delete access to receivers. If this evaluates to false, the user cannot delete any receivers. @@ -141,12 +161,13 @@ var ( ) type ReceiverAccess[T models.Identified] struct { - read actionAccess[T] - readDecrypted actionAccess[T] - create actionAccess[T] - update actionAccess[T] - delete actionAccess[T] - permissions actionAccess[T] + read actionAccess[T] + readDecrypted actionAccess[T] + create actionAccess[T] + update actionAccess[T] + updateProtected actionAccess[T] + delete actionAccess[T] + permissions actionAccess[T] } // NewReceiverAccess creates a new ReceiverAccess service. If includeProvisioningActions is true, the service will include @@ -201,6 +222,18 @@ func NewReceiverAccess[T models.Identified](a ac.AccessControl, includeProvision }, authorizeAll: updateAllReceiversEval, }, + updateProtected: actionAccess[T]{ + genericService: genericService{ + ac: a, + }, + resource: "receiver", + action: "update protected fields of", // this produces message "user is not authorized to update protected fields of X receiver" + authorizeSome: updateReceiversProtectedPreConditionsEval, + authorizeOne: func(receiver models.Identified) ac.Evaluator { + return updateReceiverProtectedEval(receiver.GetUID()) + }, + authorizeAll: updateAllReceiverProtectedEval, + }, delete: actionAccess[T]{ genericService: genericService{ ac: a, @@ -311,6 +344,14 @@ func (s ReceiverAccess[T]) AuthorizeUpdate(ctx context.Context, user identity.Re return s.update.Authorize(ctx, user, receiver) } +func (s ReceiverAccess[T]) HasUpdateProtected(ctx context.Context, user identity.Requester, receiver T) (bool, error) { + return s.updateProtected.Has(ctx, user, receiver) +} + +func (s ReceiverAccess[T]) AuthorizeUpdateProtected(ctx context.Context, user identity.Requester, receiver T) error { + return s.updateProtected.Authorize(ctx, user, receiver) +} + // Global // AuthorizeCreate checks if user has access to create receivers. Returns an error if user does not have access. @@ -380,6 +421,12 @@ func (s ReceiverAccess[T]) Access(ctx context.Context, user identity.Requester, basePerms.Set(models.ReceiverPermissionDelete, true) // Has access to all receivers. } + if err := s.updateProtected.AuthorizePreConditions(ctx, user); err != nil { + basePerms.Set(models.ReceiverPermissionModifyProtected, false) + } else if err := s.updateProtected.AuthorizeAll(ctx, user); err == nil { + basePerms.Set(models.ReceiverPermissionModifyProtected, true) + } + if basePerms.AllSet() { // Shortcut for the case when all permissions are known based on preconditions. result := make(map[string]models.ReceiverPermissionSet, len(receivers)) @@ -412,6 +459,11 @@ func (s ReceiverAccess[T]) Access(ctx context.Context, user identity.Requester, permSet.Set(models.ReceiverPermissionDelete, err == nil) } + if _, ok := permSet.Has(models.ReceiverPermissionModifyProtected); !ok { + err := s.updateProtected.authorize(ctx, user, rcv) + permSet.Set(models.ReceiverPermissionModifyProtected, err == nil) + } + result[rcv.GetUID()] = permSet } return result, nil diff --git a/pkg/services/ngalert/accesscontrol/receivers_test.go b/pkg/services/ngalert/accesscontrol/receivers_test.go index 7be1e9498e2..316fa3a98a6 100644 --- a/pkg/services/ngalert/accesscontrol/receivers_test.go +++ b/pkg/services/ngalert/accesscontrol/receivers_test.go @@ -204,6 +204,33 @@ func TestReceiverAccess(t *testing.T) { recv3.UID: permissions(), }, }, + { + name: "update protected cannot update receivers", + user: newEmptyUser( + ac.Permission{Action: ac.ActionAlertingReceiversRead, Scope: models.ScopeReceiversAll}, + ac.Permission{Action: ac.ActionAlertingReceiversUpdateProtected, Scope: models.ScopeReceiversAll}, + ), + expected: map[string]models.ReceiverPermissionSet{ + recv1.UID: permissions(), + recv2.UID: permissions(), + recv3.UID: permissions(), + }, + }, + { + name: "update protected receivers", + user: newEmptyUser( + ac.Permission{Action: ac.ActionAlertingReceiversRead, Scope: models.ScopeReceiversAll}, + ac.Permission{Action: ac.ActionAlertingReceiversUpdateProtected, Scope: models.ScopeReceiversProvider.GetResourceScopeUID(recv1.UID)}, + ac.Permission{Action: ac.ActionAlertingReceiversUpdate, Scope: models.ScopeReceiversProvider.GetResourceScopeUID(recv1.UID)}, + ac.Permission{Action: ac.ActionAlertingReceiversUpdate, Scope: models.ScopeReceiversProvider.GetResourceScopeUID(recv2.UID)}, + ac.Permission{Action: ac.ActionAlertingReceiversUpdateProtected, Scope: models.ScopeReceiversProvider.GetResourceScopeUID(recv3.UID)}, + ), + expected: map[string]models.ReceiverPermissionSet{ + recv1.UID: permissions(models.ReceiverPermissionWrite, models.ReceiverPermissionModifyProtected), + recv2.UID: permissions(models.ReceiverPermissionWrite), + recv3.UID: permissions(), + }, + }, // Receiver delete. { name: "global receiver delete should have delete but no write", diff --git a/pkg/services/ngalert/api/api_alertmanager.go b/pkg/services/ngalert/api/api_alertmanager.go index 90dcb26fc74..f8b7216bcdb 100644 --- a/pkg/services/ngalert/api/api_alertmanager.go +++ b/pkg/services/ngalert/api/api_alertmanager.go @@ -10,8 +10,10 @@ import ( "time" alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers/schema" "github.com/grafana/grafana/pkg/api/response" + "github.com/grafana/grafana/pkg/apimachinery/errutil" "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/accesscontrol" @@ -32,6 +34,7 @@ const ( type receiversAuthz interface { FilterRead(ctx context.Context, user identity.Requester, receivers ...ReceiverStatus) ([]ReceiverStatus, error) + AuthorizeUpdateProtected(context.Context, identity.Requester, ReceiverStatus) error } type AlertmanagerSrv struct { @@ -210,11 +213,16 @@ func (srv AlertmanagerSrv) RouteGetReceivers(c *contextmodel.ReqContext) respons } func (srv AlertmanagerSrv) RoutePostTestReceivers(c *contextmodel.ReqContext, body apimodels.TestReceiversConfigBodyParams) response.Response { - if err := srv.crypto.ProcessSecureSettings(c.Req.Context(), c.GetOrgID(), body.Receivers); err != nil { + if err := srv.crypto.ProcessSecureSettings(c.Req.Context(), c.GetOrgID(), body.Receivers, func(receiverName string, paths []schema.IntegrationFieldPath) error { + return srv.receiverAuthz.AuthorizeUpdateProtected(c.Req.Context(), c.SignedInUser, ReceiverStatus{Name: receiverName}) + }); err != nil { var unknownReceiverError UnknownReceiverError if errors.As(err, &unknownReceiverError) { return ErrResp(http.StatusBadRequest, err, "") } + if errors.As(err, &errutil.Error{}) { + return response.Err(err) + } return ErrResp(http.StatusInternalServerError, err, "failed to post process Alertmanager configuration") } diff --git a/pkg/services/ngalert/api/api_prometheus_test.go b/pkg/services/ngalert/api/api_prometheus_test.go index 25acf56f7d3..71e25d4c963 100644 --- a/pkg/services/ngalert/api/api_prometheus_test.go +++ b/pkg/services/ngalert/api/api_prometheus_test.go @@ -2886,6 +2886,189 @@ func TestRouteGetRuleStatuses(t *testing.T) { }) } }) + + t.Run("with rule_matcher filter", func(t *testing.T) { + fakeStore, fakeAIM, api := setupAPI(t) + + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule1"), gen.WithLabels(map[string]string{"team": "alerting", "severity": "critical"}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule2"), gen.WithLabels(map[string]string{"team": "Alerting", "severity": "warning"}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule3"), gen.WithLabels(map[string]string{"team": "platform", "severity": "critical"}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule4"), gen.WithLabels(map[string]string{"env": "production"}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule_special"), gen.WithLabels(map[string]string{"key": `value"with"quotes`}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule_empty"), gen.WithLabels(map[string]string{"empty": ""}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule_nonempty"), gen.WithLabels(map[string]string{"empty": "nonempty"}), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule_multiline"), gen.WithLabels(map[string]string{"description": "line1\nline2\\end\"quote"}), gen.WithNoNotificationSettings()) + + testCases := []struct { + name string + matchers []string + expectedUIDs []string + }{ + { + name: "equality matcher filters by team=alerting", + matchers: []string{`{"name":"team","value":"alerting","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{"rule1"}, + }, + { + name: "inequality matcher filters severity!=warning", + matchers: []string{`{"name":"severity","value":"warning","isRegex":false,"isEqual":false}`}, + expectedUIDs: []string{"rule1", "rule3", "rule4", "rule_special", "rule_empty", "rule_nonempty", "rule_multiline"}, + }, + { + name: "regex matcher filters team=~plat.*", + matchers: []string{`{"name":"team","value":"plat.*","isRegex":true,"isEqual":true}`}, + expectedUIDs: []string{"rule3"}, + }, + { + name: "not-regex matcher filters severity!~warn.*", + matchers: []string{`{"name":"severity","value":"warn.*","isRegex":true,"isEqual":false}`}, + expectedUIDs: []string{"rule1", "rule3", "rule4", "rule_special", "rule_empty", "rule_nonempty", "rule_multiline"}, + }, + { + name: "multiple matchers are ANDed", + matchers: []string{ + `{"name":"team","value":"alerting","isRegex":false,"isEqual":true}`, + `{"name":"severity","value":"critical","isRegex":false,"isEqual":true}`, + }, + expectedUIDs: []string{"rule1"}, + }, + { + name: "matcher with non-existent label returns no rules", + matchers: []string{`{"name":"nonexistent","value":"value","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{}, + }, + { + name: "equality matcher is case-sensitive", + matchers: []string{`{"name":"team","value":"Alerting","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{"rule2"}, + }, + { + name: "quotes in label value are handled correctly", + matchers: []string{`{"name":"key","value":"value\"with\"quotes","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{"rule_special"}, + }, + { + name: "no matchers returns all rules", + matchers: []string{}, + expectedUIDs: []string{"rule1", "rule2", "rule3", "rule4", "rule_special", "rule_empty", "rule_nonempty", "rule_multiline"}, + }, + { + name: "empty string value matches correctly", + matchers: []string{`{"name":"empty","value":"","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{"rule1", "rule2", "rule3", "rule4", "rule_special", "rule_empty", "rule_multiline"}, + }, + { + name: "special characters in label value are handled correctly", + matchers: []string{`{"name":"description","value":"line1\nline2\\end\"quote","isRegex":false,"isEqual":true}`}, + expectedUIDs: []string{"rule_multiline"}, + }, + { + name: "inequality matcher on non-existent label matches all rules", + matchers: []string{`{"name":"nonexistent","value":"value","isRegex":false,"isEqual":false}`}, + expectedUIDs: []string{"rule1", "rule2", "rule3", "rule4", "rule_special", "rule_empty", "rule_nonempty", "rule_multiline"}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + reqURL := "/api/v1/rules" + for i, matcher := range tc.matchers { + if i == 0 { + reqURL += "?rule_matcher=" + url.QueryEscape(matcher) + } else { + reqURL += "&rule_matcher=" + url.QueryEscape(matcher) + } + } + + req, err := http.NewRequest("GET", reqURL, nil) + require.NoError(t, err) + ctx := &contextmodel.ReqContext{ + Context: &web.Context{Req: req}, + SignedInUser: &user.SignedInUser{OrgID: orgID, Permissions: queryPermissions}, + } + + resp := api.RouteGetRuleStatuses(ctx) + require.Equal(t, http.StatusOK, resp.Status()) + + var res apimodels.RuleResponse + require.NoError(t, json.Unmarshal(resp.Body(), &res)) + require.Equal(t, "success", res.Status) + + actualUIDs := []string{} + for _, group := range res.Data.RuleGroups { + for _, rule := range group.Rules { + actualUIDs = append(actualUIDs, rule.UID) + } + } + + require.ElementsMatch(t, tc.expectedUIDs, actualUIDs) + }) + } + }) + + t.Run("pagination with rule_matcher in-memory filtering", func(t *testing.T) { + fakeStore, fakeAIM, api := setupAPI(t) + + // Create 3 groups with 2 rules each: + // Group 1 & 2: team=backend (won't match filter) + // Group 3: team=frontend (will match filter) + // This tests that pagination continues fetching when early pages are filtered out + + group1Key := ngmodels.AlertRuleGroupKey{OrgID: orgID, NamespaceUID: "namespace1", RuleGroup: "group1"} + group2Key := ngmodels.AlertRuleGroupKey{OrgID: orgID, NamespaceUID: "namespace2", RuleGroup: "group2"} + group3Key := ngmodels.AlertRuleGroupKey{OrgID: orgID, NamespaceUID: "namespace3", RuleGroup: "group3"} + + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule1"), gen.WithLabels(map[string]string{"team": "security"}), gen.WithGroupKey(group1Key), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule2"), gen.WithLabels(map[string]string{"team": "security"}), gen.WithGroupKey(group1Key), gen.WithNoNotificationSettings()) + + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule3"), gen.WithLabels(map[string]string{"team": "security"}), gen.WithGroupKey(group2Key), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule4"), gen.WithLabels(map[string]string{"team": "security"}), gen.WithGroupKey(group2Key), gen.WithNoNotificationSettings()) + + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule5"), gen.WithLabels(map[string]string{"team": "alerting"}), gen.WithGroupKey(group3Key), gen.WithNoNotificationSettings()) + generateRuleAndInstanceWithQuery(t, orgID, fakeAIM, fakeStore, withClassicConditionSingleQuery(), + gen.WithUID("rule6"), gen.WithLabels(map[string]string{"team": "alerting"}), gen.WithGroupKey(group3Key), gen.WithNoNotificationSettings()) + + // Request with regex rule_matcher filter for team=~"alerting" and group_limit=1 to force pagination + matcher := `{"name":"team","value":"alerting","isRegex":true,"isEqual":true}` + reqURL := "/api/v1/rules?rule_matcher=" + url.QueryEscape(matcher) + "&group_limit=1" + + req, err := http.NewRequest("GET", reqURL, nil) + require.NoError(t, err) + ctx := &contextmodel.ReqContext{ + Context: &web.Context{Req: req}, + SignedInUser: &user.SignedInUser{OrgID: orgID, Permissions: queryPermissions}, + } + + resp := api.RouteGetRuleStatuses(ctx) + require.Equal(t, http.StatusOK, resp.Status()) + + var res apimodels.RuleResponse + require.NoError(t, json.Unmarshal(resp.Body(), &res)) + require.Equal(t, "success", res.Status) + + actualUIDs := []string{} + for _, group := range res.Data.RuleGroups { + for _, rule := range group.Rules { + actualUIDs = append(actualUIDs, rule.UID) + } + } + + // Should return group3 rules (rule5, rule6), pagination should continue past filtered groups + require.ElementsMatch(t, []string{"rule5", "rule6"}, actualUIDs) + }) } func setupAPI(t *testing.T) (*fakes.RuleStore, *fakeAlertInstanceManager, PrometheusSrv) { diff --git a/pkg/services/ngalert/api/api_ruler.go b/pkg/services/ngalert/api/api_ruler.go index d81f448f600..9fde7a2ec6f 100644 --- a/pkg/services/ngalert/api/api_ruler.go +++ b/pkg/services/ngalert/api/api_ruler.go @@ -412,11 +412,16 @@ func (srv RulerSrv) RoutePostNameRulesConfig(c *contextmodel.ReqContext, ruleGro deletePermanently = true } - namespace, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.GetOrgID(), c.SignedInUser) + f, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.GetOrgID(), c.SignedInUser) if err != nil { return toNamespaceErrorResponse(err) } + namespace := ngmodels.NewNamespace(f) + if err := namespace.ValidateForRuleStorage(); err != nil { + return ErrResp(http.StatusBadRequest, fmt.Errorf("%w: %s", ngmodels.ErrAlertRuleFailedValidation, err), "") + } + if err := srv.checkGroupLimits(ruleGroupConfig); err != nil { return ErrResp(http.StatusBadRequest, err, "") } @@ -841,10 +846,14 @@ func (srv RulerSrv) RouteUpdateNamespaceRules(c *contextmodel.ReqContext, body a return ErrResp(http.StatusBadRequest, errors.New("missing request body"), "") } - namespace, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.GetOrgID(), c.SignedInUser) + f, err := srv.store.GetNamespaceByUID(c.Req.Context(), namespaceUID, c.GetOrgID(), c.SignedInUser) if err != nil { return toNamespaceErrorResponse(err) } + namespace := ngmodels.NewNamespace(f) + if err := namespace.ValidateForRuleStorage(); err != nil { + return ErrResp(http.StatusBadRequest, fmt.Errorf("%w: %s", ngmodels.ErrAlertRuleFailedValidation, err), "") + } ruleGroups, _, err := srv.searchAuthorizedAlertRules(c.Req.Context(), authorizedRuleGroupQuery{ User: c.SignedInUser, diff --git a/pkg/services/ngalert/api/api_ruler_test.go b/pkg/services/ngalert/api/api_ruler_test.go index c6ddeee2a6c..e09088e4669 100644 --- a/pkg/services/ngalert/api/api_ruler_test.go +++ b/pkg/services/ngalert/api/api_ruler_test.go @@ -18,6 +18,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/infra/log" ac "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" @@ -1288,4 +1289,64 @@ func TestRouteUpdateNamespaceRules(t *testing.T) { updatedRules := getRecordedUpdatedRules(ruleStore) require.Empty(t, updatedRules) }) + + t.Run("should reject update when folder is managed by ManagerKindRepo", func(t *testing.T) { + ruleStore := fakes.NewRuleStore(t) + provisioningStore := fakes.NewFakeProvisioningStore() + + // Create a managed folder + managedFolder := randFolder() + managedFolder.ManagedBy = utils.ManagerKindRepo + ruleStore.Folders[orgID] = append(ruleStore.Folders[orgID], managedFolder) + + // Create some rules in the managed folder + ruleGen := models.RuleGen.With( + models.RuleGen.WithOrgID(orgID), + models.RuleGen.WithNamespaceUID(managedFolder.UID), + ) + rules := ruleGen.GenerateManyRef(2) + ruleStore.PutRule(context.Background(), rules...) + + permissions := createPermissionsForRules(rules, orgID) + requestCtx := createRequestContextWithPerms(orgID, permissions, nil) + + svc := createServiceWithProvenanceStore(ruleStore, provisioningStore) + response := svc.RouteUpdateNamespaceRules(requestCtx, apimodels.UpdateNamespaceRulesRequest{ + IsPaused: util.Pointer(true), + }, managedFolder.UID) + + require.Equal(t, http.StatusBadRequest, response.Status()) + require.Contains(t, string(response.Body()), "cannot store rules in folder managed by Git Sync") + + // Verify no rules were updated + updatedRules := getRecordedUpdatedRules(ruleStore) + require.Empty(t, updatedRules) + }) +} + +func TestRoutePostNameRulesConfig(t *testing.T) { + t.Run("should reject creation when folder is managed by ManagerKindRepo", func(t *testing.T) { + orgID := rand.Int63() + ruleStore := fakes.NewRuleStore(t) + + // Create a managed folder + managedFolder := randFolder() + managedFolder.ManagedBy = utils.ManagerKindRepo + ruleStore.Folders[orgID] = append(ruleStore.Folders[orgID], managedFolder) + + permissions := map[int64]map[string][]string{ + orgID: { + dashboards.ScopeFoldersProvider.GetResourceScopeUID(managedFolder.UID): {dashboards.ActionFoldersRead}, + }, + } + requestCtx := createRequestContextWithPerms(orgID, permissions, nil) + + svc := createService(ruleStore, nil) + response := svc.RoutePostNameRulesConfig(requestCtx, apimodels.PostableRuleGroupConfig{ + Name: "test-group", + }, managedFolder.UID) + + require.Equal(t, http.StatusBadRequest, response.Status()) + require.Contains(t, string(response.Body()), "cannot store rules in folder managed by Git Sync") + }) } diff --git a/pkg/services/ngalert/api/authorization.go b/pkg/services/ngalert/api/authorization.go index 46168688ee6..1c107db22c6 100644 --- a/pkg/services/ngalert/api/authorization.go +++ b/pkg/services/ngalert/api/authorization.go @@ -251,7 +251,7 @@ func (api *API) authorize(method, path string) web.Handler { case http.MethodPost + "/api/alertmanager/grafana/config/api/v1/templates/test": eval = ac.EvalAny( ac.EvalPermission(ac.ActionAlertingNotificationsWrite), - ac.EvalPermission(ac.ActionAlertingNotificationsTemplatesRead), + ac.EvalPermission(ac.ActionAlertingNotificationsTemplatesTest), ) // External Alertmanager Paths diff --git a/pkg/services/ngalert/api/prometheus/api_prometheus.go b/pkg/services/ngalert/api/prometheus/api_prometheus.go index 412a0795469..934805d74f4 100644 --- a/pkg/services/ngalert/api/prometheus/api_prometheus.go +++ b/pkg/services/ngalert/api/prometheus/api_prometheus.go @@ -33,6 +33,12 @@ import ( "go.opentelemetry.io/otel/trace" ) +const ( + queryIncludeInternalLabels = "includeInternalLabels" + queryRuleMatcher = "rule_matcher" + queryInstanceMatcher = "matcher" +) + type RuleStoreReader interface { GetUserVisibleNamespaces(context.Context, int64, identity.Requester) (map[string]*folder.Folder, error) ListAlertRulesStoreV2 @@ -62,6 +68,20 @@ type PrometheusSrv struct { // Package-level OpenTelemetry tracer per Grafana instrumentation conventions. var tracer = otel.Tracer("github.com/grafana/grafana/pkg/services/ngalert/api/prometheus") +// badRequestError returns a Prometheus-compatible error response for bad request data. +func badRequestError(err error) apimodels.RuleResponse { + return apimodels.RuleResponse{ + DiscoveryBase: apimodels.DiscoveryBase{ + Status: "error", + Error: err.Error(), + ErrorType: apiv1.ErrBadData, + }, + Data: apimodels.RuleDiscovery{ + RuleGroups: []apimodels.RuleGroup{}, + }, + } +} + func NewPrometheusSrv(log log.Logger, manager state.AlertInstanceManager, status StatusReader, store RuleStoreReader, authz RuleGroupAccessControlService, provenanceStore ProvenanceStore) *PrometheusSrv { return &PrometheusSrv{ log, @@ -73,8 +93,6 @@ func NewPrometheusSrv(log log.Logger, manager state.AlertInstanceManager, status } } -const queryIncludeInternalLabels = "includeInternalLabels" - func getBoolWithDefault(vals url.Values, field string, d bool) bool { f := vals.Get(field) if f == "" { @@ -188,15 +206,15 @@ func getPanelIDFromQuery(v url.Values) (int64, error) { return 0, nil } -func getMatchersFromQuery(v url.Values) (labels.Matchers, error) { +func getMatchersFromQuery(v url.Values, paramName string) (labels.Matchers, error) { var matchers labels.Matchers - for _, s := range v["matcher"] { + for _, s := range v[paramName] { var m labels.Matcher if err := json.Unmarshal([]byte(s), &m); err != nil { return nil, err } if len(m.Name) == 0 { - return nil, errors.New("bad matcher: the name cannot be blank") + return nil, fmt.Errorf("bad %s: the name cannot be blank", paramName) } matchers = append(matchers, &m) } @@ -296,7 +314,7 @@ func (srv PrometheusSrv) RouteGetRuleStatuses(c *contextmodel.ReqContext) respon allowedNamespaces := map[string]string{} for namespaceUID, folder := range namespaceMap { // only add namespaces that the user has access to rules in - hasAccess, err := srv.authz.HasAccessInFolder(c.Req.Context(), c.SignedInUser, ngmodels.Namespace(*folder.ToFolderReference())) + hasAccess, err := srv.authz.HasAccessInFolder(c.Req.Context(), c.SignedInUser, ngmodels.NewNamespace(folder)) if err != nil { ruleResponse.Status = "error" ruleResponse.Error = fmt.Sprintf("failed to get namespaces visible to the user: %s", err.Error()) @@ -454,9 +472,11 @@ type paginationContext struct { stateFilterSet map[eval.State]struct{} healthFilterSet map[string]struct{} matchers labels.Matchers + ruleLabelMatchers labels.Matchers labelOptions []ngmodels.LabelOption limitAlertsPerRule int64 limitRulesPerGroup int64 + compact bool } // pageResult is the result of fetching and filtering of one page @@ -475,6 +495,9 @@ func accumulateTotals(dest, source map[string]int64) { // fetchAndFilterPage fetches one page from the store and applies filters func (ctx *paginationContext) fetchAndFilterPage(log log.Logger, store ListAlertRulesStoreV2, span trace.Span, token string, remainingGroups, remainingRules int64) (pageResult, error) { + // Split matchers: only equality/inequality are supported by the store + storeMatchers := filterOutRegexMatchers(ctx.ruleLabelMatchers) + byGroupQuery := ngmodels.ListAlertRulesExtendedQuery{ ListAlertRulesQuery: ngmodels.ListAlertRulesQuery{ OrgID: ctx.opts.OrgID, @@ -487,11 +510,13 @@ func (ctx *paginationContext) fetchAndFilterPage(log log.Logger, store ListAlert DataSourceUIDs: ctx.dataSourceUIDs, SearchTitle: ctx.title, SearchRuleGroup: ctx.searchRuleGroup, + LabelMatchers: storeMatchers, }, RuleType: ctx.ruleType, Limit: remainingGroups, RuleLimit: remainingRules, ContinueToken: token, + Compact: ctx.compact, } ruleList, newToken, err := store.ListAlertRulesByGroup(ctx.opts.Ctx, &byGroupQuery) @@ -519,7 +544,7 @@ func (ctx *paginationContext) fetchAndFilterPage(log log.Logger, store ListAlert log, rg.GroupKey, rg.Folder, rg.Rules, ctx.provenanceRecords, ctx.limitAlertsPerRule, ctx.stateFilterSet, ctx.matchers, ctx.labelOptions, - ctx.ruleStatusMutator, ctx.alertStateMutator, + ctx.ruleStatusMutator, ctx.alertStateMutator, ctx.compact, ) ruleGroup.Totals = totals accumulateTotals(result.totalsDelta, totals) @@ -532,6 +557,8 @@ func (ctx *paginationContext) fetchAndFilterPage(log log.Logger, store ListAlert filterRulesByHealth(ruleGroup, ctx.healthFilterSet) } + filterRulesByLabelMatchers(ruleGroup, ctx.ruleLabelMatchers) + if ctx.limitRulesPerGroup > -1 && int64(len(ruleGroup.Rules)) > ctx.limitRulesPerGroup { ruleGroup.Rules = ruleGroup.Rules[0:ctx.limitRulesPerGroup] } @@ -544,6 +571,17 @@ func (ctx *paginationContext) fetchAndFilterPage(log log.Logger, store ListAlert return result, nil } +func filterOutRegexMatchers(matchers labels.Matchers) labels.Matchers { + var result labels.Matchers + for _, m := range matchers { + if m.Type == labels.MatchEqual || m.Type == labels.MatchNotEqual { + result = append(result, m) + } + } + + return result +} + // paginateRuleGroups fetches pages until limits are satisfied applying filters at each step func paginateRuleGroups(log log.Logger, store ListAlertRulesStoreV2, ctx *paginationContext, span trace.Span, maxGroups, maxRules int64, startToken string) ([]apimodels.RuleGroup, map[string]int64, string, error) { allGroups := []apimodels.RuleGroup{} @@ -642,21 +680,30 @@ func PrepareRuleGroupStatusesV2(log log.Logger, store ListAlertRulesStoreV2, opt attribute.Int64("limit_rules", limitRulesPerGroup), attribute.Int64("limit_alerts", limitAlertsPerRule), ) - matchers, err := getMatchersFromQuery(opts.Query) + matchers, err := getMatchersFromQuery(opts.Query, queryInstanceMatcher) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) } span.SetAttributes(attribute.Int("matcher_count", len(matchers))) + ruleLabelMatchers, err := getMatchersFromQuery(opts.Query, queryRuleMatcher) + if err != nil { + return badRequestError(err) + } + regexCount := 0 + for _, m := range ruleLabelMatchers { + if m.Type == labels.MatchRegexp || m.Type == labels.MatchNotRegexp { + regexCount++ + } + } + span.SetAttributes( + attribute.Int("rule_matcher_count", len(ruleLabelMatchers)), + attribute.Int("rule_matcher_regex_count", regexCount), + ) + stateFilterSet, err := GetStatesFromQuery(opts.Query) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) } span.SetAttributes( attribute.Int("state_filter_count", len(stateFilterSet)), @@ -665,10 +712,7 @@ func PrepareRuleGroupStatusesV2(log log.Logger, store ListAlertRulesStoreV2, opt healthFilterSet, err := GetHealthFromQuery(opts.Query) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) } span.SetAttributes( attribute.Int("health_filter_count", len(healthFilterSet)), @@ -785,6 +829,8 @@ func PrepareRuleGroupStatusesV2(log log.Logger, store ListAlertRulesStoreV2, opt } span.SetAttributes(attribute.Int("rule_name_count", len(ruleNamesSet))) + compact := getBoolWithDefault(opts.Query, "compact", false) + span.SetAttributes(attribute.Bool("compact", compact)) pagCtx := &paginationContext{ opts: opts, provenanceRecords: provenanceRecords, @@ -804,9 +850,11 @@ func PrepareRuleGroupStatusesV2(log log.Logger, store ListAlertRulesStoreV2, opt stateFilterSet: stateFilterSet, healthFilterSet: healthFilterSet, matchers: matchers, + ruleLabelMatchers: ruleLabelMatchers, labelOptions: labelOptions, limitAlertsPerRule: limitAlertsPerRule, limitRulesPerGroup: limitRulesPerGroup, + compact: compact, } groups, rulesTotals, continueToken, err := paginateRuleGroups(log, store, pagCtx, span, maxGroups, maxRules, nextToken) @@ -828,6 +876,7 @@ func PrepareRuleGroupStatusesV2(log log.Logger, store ListAlertRulesStoreV2, opt return ruleResponse } +// nolint:gocyclo func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts RuleGroupStatusesOptions, ruleStatusMutator RuleStatusMutator, alertStateMutator RuleAlertStateMutator, provenanceRecords map[string]ngmodels.Provenance) apimodels.RuleResponse { ruleResponse := apimodels.RuleResponse{ DiscoveryBase: apimodels.DiscoveryBase{ @@ -841,41 +890,30 @@ func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts Ru dashboardUID := opts.Query.Get("dashboard_uid") panelID, err := getPanelIDFromQuery(opts.Query) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = fmt.Sprintf("invalid panel_id: %s", err.Error()) - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(fmt.Errorf("invalid panel_id: %w", err)) } if dashboardUID == "" && panelID != 0 { - ruleResponse.Status = "error" - ruleResponse.Error = "panel_id must be set with dashboard_uid" - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(errors.New("panel_id must be set with dashboard_uid")) } limitRulesPerGroup := getInt64WithDefault(opts.Query, "limit_rules", -1) limitAlertsPerRule := getInt64WithDefault(opts.Query, "limit_alerts", -1) - matchers, err := getMatchersFromQuery(opts.Query) + matchers, err := getMatchersFromQuery(opts.Query, queryInstanceMatcher) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) + } + ruleLabelMatchers, err := getMatchersFromQuery(opts.Query, queryRuleMatcher) + if err != nil { + return badRequestError(err) } stateFilterSet, err := GetStatesFromQuery(opts.Query) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) } healthFilterSet, err := GetHealthFromQuery(opts.Query) if err != nil { - ruleResponse.Status = "error" - ruleResponse.Error = err.Error() - ruleResponse.ErrorType = apiv1.ErrBadData - return ruleResponse + return badRequestError(err) } var labelOptions []ngmodels.LabelOption @@ -908,6 +946,9 @@ func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts Ru dataSourceUIDs := opts.Query["datasource_uid"] searchRuleGroup := opts.Query.Get("search.rule_group") + // Split matchers: only equality/inequality are supported by the store + storeMatchers := filterOutRegexMatchers(ruleLabelMatchers) + alertRuleQuery := ngmodels.ListAlertRulesQuery{ OrgID: opts.OrgID, NamespaceUIDs: namespaceUIDs, @@ -919,6 +960,7 @@ func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts Ru SearchTitle: title, SearchRuleGroup: searchRuleGroup, DataSourceUIDs: dataSourceUIDs, + LabelMatchers: storeMatchers, } ruleList, err := store.ListAlertRules(opts.Ctx, &alertRuleQuery) if err != nil { @@ -959,7 +1001,7 @@ func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts Ru break } - ruleGroup, totals := toRuleGroup(log, rg.GroupKey, rg.Folder, rg.Rules, provenanceRecords, limitAlertsPerRule, stateFilterSet, matchers, labelOptions, ruleStatusMutator, alertStateMutator) + ruleGroup, totals := toRuleGroup(log, rg.GroupKey, rg.Folder, rg.Rules, provenanceRecords, limitAlertsPerRule, stateFilterSet, matchers, labelOptions, ruleStatusMutator, alertStateMutator, false) ruleGroup.Totals = totals for k, v := range totals { rulesTotals[k] += v @@ -973,6 +1015,10 @@ func PrepareRuleGroupStatuses(log log.Logger, store ListAlertRulesStore, opts Ru filterRulesByHealth(ruleGroup, healthFilterSet) } + if len(ruleLabelMatchers) > 0 { + filterRulesByLabelMatchers(ruleGroup, ruleLabelMatchers) + } + if limitRulesPerGroup > -1 && int64(len(ruleGroup.Rules)) > limitRulesPerGroup { ruleGroup.Rules = ruleGroup.Rules[0:limitRulesPerGroup] } @@ -1100,6 +1146,30 @@ func filterRulesByHealth(ruleGroup *apimodels.RuleGroup, withHealthFast map[stri ruleGroup.Rules = filteredRules } +func filterRulesByLabelMatchers(ruleGroup *apimodels.RuleGroup, matchers labels.Matchers) { + if len(matchers) == 0 { + return + } + + filteredRules := make([]apimodels.AlertingRule, 0, len(ruleGroup.Rules)) + + for _, rule := range ruleGroup.Rules { + ruleLabels := rule.Labels.Map() + matches := true + for _, m := range matchers { + if !m.Matches(ruleLabels[m.Name]) { + matches = false + break + } + } + if matches { + filteredRules = append(filteredRules, rule) + } + } + + ruleGroup.Rules = filteredRules +} + // This is the same as matchers.Matches but avoids the need to create a LabelSet func matchersMatch(matchers []*labels.Matcher, labels map[string]string) bool { for _, m := range matchers { @@ -1110,7 +1180,7 @@ func matchersMatch(matchers []*labels.Matcher, labels map[string]string) bool { return true } -func toRuleGroup(log log.Logger, groupKey ngmodels.AlertRuleGroupKey, folderFullPath string, rules []*ngmodels.AlertRule, provenanceRecords map[string]ngmodels.Provenance, limitAlerts int64, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption, ruleStatusMutator RuleStatusMutator, ruleAlertStateMutator RuleAlertStateMutator) (*apimodels.RuleGroup, map[string]int64) { +func toRuleGroup(log log.Logger, groupKey ngmodels.AlertRuleGroupKey, folderFullPath string, rules []*ngmodels.AlertRule, provenanceRecords map[string]ngmodels.Provenance, limitAlerts int64, stateFilterSet map[eval.State]struct{}, matchers labels.Matchers, labelOptions []ngmodels.LabelOption, ruleStatusMutator RuleStatusMutator, ruleAlertStateMutator RuleAlertStateMutator, compact bool) (*apimodels.RuleGroup, map[string]int64) { newGroup := &apimodels.RuleGroup{ Name: groupKey.RuleGroup, // file is what Prometheus uses for provisioning, we replace it with namespace which is the folder in Grafana. @@ -1126,10 +1196,14 @@ func toRuleGroup(log log.Logger, groupKey ngmodels.AlertRuleGroupKey, folderFull if prov, exists := provenanceRecords[rule.ResourceID()]; exists { provenance = prov } + var query string + if !compact { + query = ruleToQuery(log, rule) + } alertingRule := apimodels.AlertingRule{ State: "inactive", Name: rule.Title, - Query: ruleToQuery(log, rule), + Query: query, QueriedDatasourceUIDs: extractDatasourceUIDs(rule), Duration: rule.For.Seconds(), KeepFiringFor: rule.KeepFiringFor.Seconds(), diff --git a/pkg/services/ngalert/api/tooling/definitions/prom.go b/pkg/services/ngalert/api/tooling/definitions/prom.go index 128c69787c0..05fb62dc283 100644 --- a/pkg/services/ngalert/api/tooling/definitions/prom.go +++ b/pkg/services/ngalert/api/tooling/definitions/prom.go @@ -462,4 +462,10 @@ type GetGrafanaRuleStatusesParams struct { // in: query // required: false Matchers []string `json:"matcher"` + + // Filter rules by their static labels (not alert instance labels). Each value is a JSON-encoded Prometheus-like matcher (for example, {"type":0,"name":"severity","value":"critical"}). + // For equality matchers with empty string values (e.g., name=""), rules that have the label with an empty value OR rules without the label will match (standard Prometheus behavior). + // in: query + // required: false + RuleLabelMatchers []string `json:"rule_matcher"` } diff --git a/pkg/services/ngalert/api/tooling/post.json b/pkg/services/ngalert/api/tooling/post.json index d9d38ce03b0..1243007dfcf 100644 --- a/pkg/services/ngalert/api/tooling/post.json +++ b/pkg/services/ngalert/api/tooling/post.json @@ -7561,6 +7561,15 @@ }, "name": "matcher", "type": "array" + }, + { + "description": "Filter rules by their static labels (not alert instance labels). Each value is a JSON-encoded Prometheus-like matcher (for example, {\"type\":0,\"name\":\"severity\",\"value\":\"critical\"}).\nFor equality matchers with empty string values (e.g., name=\"\"), rules that have the label with an empty value OR rules without the label will match (standard Prometheus behavior).", + "in": "query", + "items": { + "type": "string" + }, + "name": "rule_matcher", + "type": "array" } ], "responses": { diff --git a/pkg/services/ngalert/api/tooling/spec.json b/pkg/services/ngalert/api/tooling/spec.json index adb65e92ad9..81e0aa894c9 100644 --- a/pkg/services/ngalert/api/tooling/spec.json +++ b/pkg/services/ngalert/api/tooling/spec.json @@ -1947,6 +1947,15 @@ "description": "Filter by label matchers encoded as JSON representations of Prometheus matchers (for example, {\"type\":0,\"name\":\"severity\",\"value\":\"critical\"}). Provide one matcher per query string value.", "name": "matcher", "in": "query" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "description": "Filter rules by their static labels (not alert instance labels). Each value is a JSON-encoded Prometheus-like matcher (for example, {\"type\":0,\"name\":\"severity\",\"value\":\"critical\"}).\nFor equality matchers with empty string values (e.g., name=\"\"), rules that have the label with an empty value OR rules without the label will match (standard Prometheus behavior).", + "name": "rule_matcher", + "in": "query" } ], "responses": { diff --git a/pkg/services/ngalert/eval/eval.go b/pkg/services/ngalert/eval/eval.go index 687e9b2dd03..40e2a257e60 100644 --- a/pkg/services/ngalert/eval/eval.go +++ b/pkg/services/ngalert/eval/eval.go @@ -204,7 +204,7 @@ func IsNonRetryableError(err error) bool { return false } -// HasErrors returns true when Results contains at least one element and all elements are errors +// IsError returns true when Results contains at least one element and all elements are errors func (evalResults Results) IsError() bool { for _, r := range evalResults { if r.State != Error { diff --git a/pkg/services/ngalert/metrics/scheduler.go b/pkg/services/ngalert/metrics/scheduler.go index d6c6707f0a9..9bcff59ffb9 100644 --- a/pkg/services/ngalert/metrics/scheduler.go +++ b/pkg/services/ngalert/metrics/scheduler.go @@ -130,7 +130,7 @@ func NewSchedulerMetrics(r prometheus.Registerer) *Scheduler { Name: "rule_group_rules", Help: "The number of alert rules that are scheduled, by type and state.", }, - []string{"org", "type", "state", "rule_group"}, + []string{"org", "type", "state", "rule_group", "folder_uid"}, ), Groups: promauto.With(r).NewGaugeVec( prometheus.GaugeOpts{ diff --git a/pkg/services/ngalert/models/alert_query.go b/pkg/services/ngalert/models/alert_query.go index 3f03ae2e68f..3c961f8efd4 100644 --- a/pkg/services/ngalert/models/alert_query.go +++ b/pkg/services/ngalert/models/alert_query.go @@ -110,6 +110,12 @@ func (aq *AlertQuery) String() string { } func (aq *AlertQuery) setModelProps() error { + if aq.Model == nil { + // No data to extract, use an empty map. + aq.modelProps = map[string]any{} + return nil + } + aq.modelProps = make(map[string]any) err := json.Unmarshal(aq.Model, &aq.modelProps) if err != nil { diff --git a/pkg/services/ngalert/models/alert_rule.go b/pkg/services/ngalert/models/alert_rule.go index 7ee223e8165..f7bb3d9fcfd 100644 --- a/pkg/services/ngalert/models/alert_rule.go +++ b/pkg/services/ngalert/models/alert_rule.go @@ -18,12 +18,14 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/prometheus/alertmanager/pkg/labels" prommodels "github.com/prometheus/common/model" "github.com/grafana/grafana-plugin-sdk-go/data" alertingModels "github.com/grafana/alerting/models" + "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/services/folder" "github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/setting" @@ -397,6 +399,20 @@ type Namespaced interface { type Namespace folder.FolderReference +func NewNamespace(f *folder.Folder) Namespace { + return Namespace(*f.ToFolderReference()) +} + +func (n Namespace) ValidateForRuleStorage() error { + if n.UID == "" { + return fmt.Errorf("cannot store rules in folder without UID") + } + if n.ManagedBy == utils.ManagerKindRepo { + return fmt.Errorf("cannot store rules in folder managed by Git Sync") + } + return nil +} + func (n Namespace) GetNamespaceUID() string { return n.UID } @@ -997,6 +1013,10 @@ type ListAlertRulesQuery struct { SearchRuleGroup string HasPrometheusRuleDefinition *bool + + // LabelMatchers filters rules by their labels. + // Only equality and inequality matchers are supported, no regex operators. + LabelMatchers labels.Matchers } type ListAlertRulesExtendedQuery struct { @@ -1007,6 +1027,7 @@ type ListAlertRulesExtendedQuery struct { Limit int64 RuleLimit int64 ContinueToken string + Compact bool } // CountAlertRulesQuery is the query for counting alert rules diff --git a/pkg/services/ngalert/models/permissions.go b/pkg/services/ngalert/models/permissions.go index a34e184fc99..ce52755eac8 100644 --- a/pkg/services/ngalert/models/permissions.go +++ b/pkg/services/ngalert/models/permissions.go @@ -9,10 +9,11 @@ import ( type ReceiverPermission string const ( - ReceiverPermissionReadSecret ReceiverPermission = "secrets" - ReceiverPermissionAdmin ReceiverPermission = "admin" - ReceiverPermissionWrite ReceiverPermission = "write" - ReceiverPermissionDelete ReceiverPermission = "delete" + ReceiverPermissionReadSecret ReceiverPermission = "secrets" + ReceiverPermissionAdmin ReceiverPermission = "admin" + ReceiverPermissionWrite ReceiverPermission = "write" + ReceiverPermissionDelete ReceiverPermission = "delete" + ReceiverPermissionModifyProtected ReceiverPermission = "modify-protected" ) // ReceiverPermissions returns all possible silence permissions. @@ -22,6 +23,7 @@ func ReceiverPermissions() []ReceiverPermission { ReceiverPermissionAdmin, ReceiverPermissionWrite, ReceiverPermissionDelete, + ReceiverPermissionModifyProtected, } } diff --git a/pkg/services/ngalert/models/receivers_diff.go b/pkg/services/ngalert/models/receivers_diff.go new file mode 100644 index 00000000000..bfe9328542f --- /dev/null +++ b/pkg/services/ngalert/models/receivers_diff.go @@ -0,0 +1,230 @@ +package models + +import ( + "fmt" + "reflect" + "strings" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/grafana/alerting/receivers/schema" + + "github.com/grafana/grafana/pkg/util/cmputil" +) + +type IntegrationDiffReport struct { + cmputil.DiffReport +} + +// expandPaths recursively collects all sub-paths for keys in the provided map value +func (r IntegrationDiffReport) expandPaths(basePath schema.IntegrationFieldPath, mapVal reflect.Value) []schema.IntegrationFieldPath { + result := make([]schema.IntegrationFieldPath, 0) + iter := mapVal.MapRange() + for iter.Next() { + keyStr := fmt.Sprintf("%v", iter.Key()) // Assume string keys + p := basePath.With(keyStr) + // Recurse if the sub-value is another map + if m, ok := r.getMap(iter.Value()); ok { + result = append(result, r.expandPaths(p, m)...) + continue + } + result = append(result, p) + } + return result +} + +func (r IntegrationDiffReport) getMap(v reflect.Value) (reflect.Value, bool) { + if v.Kind() == reflect.Map { + return v, true + } + if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { + return r.getMap(v.Elem()) + } + return reflect.Value{}, false +} + +func (r IntegrationDiffReport) needExpand(diff cmputil.Diff) (reflect.Value, bool) { + ml, lok := r.getMap(diff.Left) + mr, rok := r.getMap(diff.Right) + if lok == rok { + return reflect.Value{}, false + } + if lok { + return ml, true + } + return mr, true +} + +func (r IntegrationDiffReport) GetSettingsPaths() []schema.IntegrationFieldPath { + diffs := r.GetDiffsForField("Settings") + paths := make([]schema.IntegrationFieldPath, 0, len(diffs)) + for _, diff := range diffs { + // diff.Path has format like Settings[url] or Settings[sub-form][field] + p := diff.Path + var path schema.IntegrationFieldPath + for { + start := strings.Index(p, "[") + if start == -1 { + break + } + p = p[start+1:] + end := strings.Index(p, "]") + if end == -1 { + break + } + fieldName := p[:end] + p = p[end+1:] + path = append(path, fieldName) + } + if m, ok := r.needExpand(diff); ok { + paths = append(paths, r.expandPaths(path, m)...) + continue + } + if len(path) > 0 { + paths = append(paths, path) + } + } + return paths +} + +func (r IntegrationDiffReport) GetSecureSettingsPaths() []schema.IntegrationFieldPath { + diffs := r.GetDiffsForField("SecureSettings") + paths := make([]schema.IntegrationFieldPath, 0, len(diffs)) + for _, diff := range diffs { + if diff.Path == "SecureSettings" { + if m, ok := r.needExpand(diff); ok { + paths = append(paths, r.expandPaths(nil, m)...) + } + continue + } + // diff.Path has format like SecureSettings[field.sub-field.sub] + p := schema.ParseIntegrationPath(diff.Path[len("SecureSettings[") : len(diff.Path)-1]) + paths = append(paths, p) + } + return paths +} + +func (integration *Integration) Diff(incoming Integration) IntegrationDiffReport { + var reporter cmputil.DiffReporter + var settingsCmp = cmpopts.AcyclicTransformer("settingsMap", func(in map[string]any) map[string]any { + if in == nil { + return map[string]any{} + } + return in + }) + var secureCmp = cmpopts.AcyclicTransformer("secureMap", func(in map[string]string) map[string]string { + if in == nil { + return map[string]string{} + } + return in + }) + schemaCmp := cmp.Comparer(func(a, b schema.IntegrationSchemaVersion) bool { + isAZero := reflect.ValueOf(a).IsZero() + isBZero := reflect.ValueOf(b).IsZero() + if isAZero && isBZero { + return true + } + if isAZero || isBZero { + return false + } + return a.Type() == b.Type() && a.Version == b.Version + }) + var cur Integration + if integration != nil { + cur = *integration + } + cmp.Equal(cur, incoming, cmp.Reporter(&reporter), settingsCmp, secureCmp, schemaCmp) + return IntegrationDiffReport{DiffReport: reporter.Diffs} +} + +// HasReceiversDifferentProtectedFields returns true if the receiver has any protected fields that are different from the incoming receiver. +func HasReceiversDifferentProtectedFields(existing, incoming *Receiver) map[string][]schema.IntegrationFieldPath { + existingIntegrations := make(map[string]*Integration, len(existing.Integrations)) + for _, integration := range existing.Integrations { + existingIntegrations[integration.UID] = integration + } + + var result = make(map[string][]schema.IntegrationFieldPath) + for _, in := range incoming.Integrations { + if in.UID == "" { + continue + } + ex, ok := existingIntegrations[in.UID] + if !ok { + continue + } + paths := HasIntegrationsDifferentProtectedFields(ex, in) + if len(paths) > 0 { + result[in.UID] = paths + } + } + return result +} + +// HasIntegrationsDifferentProtectedFields returns list of paths to protected fields that are different between two integrations. +func HasIntegrationsDifferentProtectedFields(existing, incoming *Integration) []schema.IntegrationFieldPath { + diff := existing.Diff(*incoming) + // The incoming receiver always has both secret and non-secret fields in Settings. + // So, if it's specified and happens to be sensitive, we consider it changed + var result []schema.IntegrationFieldPath + settingsDiff := diff.GetSettingsPaths() + for _, path := range settingsDiff { + if IsProtectedField(incoming.Config.Type(), path) { + result = append(result, path) + } + } + return result +} + +// IsProtectedField returns true if the field at the given path is existing protected one. +// This includes: +// 1. URL fields marked as secure in the schema (e.g., webhook URLs with credentials) +// 2. URL fields NOT marked as secure but could contain credentials (e.g., API endpoints) +func IsProtectedField(integrationType schema.IntegrationType, path schema.IntegrationFieldPath) bool { + str := strings.ToLower(string(integrationType)) + pathStr := path.String() + + switch str { + case "prometheus-alertmanager": + return pathStr == "url" + case "dingding": + return pathStr == "url" // marked as secure + case "discord": + return pathStr == "url" // marked as secure (webhook URL) + case "googlechat": + return pathStr == "url" // marked as secure + case "jira": + return pathStr == "api_url" + case "kafka": + return pathStr == "kafkaRestProxy" + case "line": + return false + case "mqtt": + return pathStr == "brokerUrl" + case "oncall": + return pathStr == "url" + case "opsgenie": + return pathStr == "apiUrl" + case "pagerduty": + return pathStr == "url" + case "sensugo": + return pathStr == "url" + case "slack": + return pathStr == "url" || pathStr == "endpointUrl" + case "teams": + return pathStr == "url" + case "victorops": + return pathStr == "url" // marked as secure + case "webex": + return pathStr == "api_url" + case "webhook": + return pathStr == "url" || + pathStr == "http_config.oauth2.token_url" || + pathStr == "http_config.oauth2.proxy_config.proxy_url" + case "wecom": + return pathStr == "url" || // marked as secure + pathStr == "endpointUrl" + default: + return false + } +} diff --git a/pkg/services/ngalert/models/receivers_diff_test.go b/pkg/services/ngalert/models/receivers_diff_test.go new file mode 100644 index 00000000000..dffeaee1dc2 --- /dev/null +++ b/pkg/services/ngalert/models/receivers_diff_test.go @@ -0,0 +1,262 @@ +package models + +import ( + "slices" + "testing" + + alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers/schema" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestIntegrationDiff(t *testing.T) { + s, _ := alertingNotify.GetSchemaVersionForIntegration("webhook", schema.V1) + a := Integration{ + UID: "test-uid", + Name: "test-name", + Config: s, + DisableResolveMessage: false, + Settings: map[string]any{ + "url": "http://localhost", + "name": 123, + "flag": true, + "child": map[string]any{ + "sub-form-field": "test", + }, + }, + SecureSettings: map[string]string{ + "password": "12345", + "token": "token-12345", + }, + } + + t.Run("no diff if equal", func(t *testing.T) { + result := a.Diff(a) + assert.Empty(t, result) + }) + + t.Run("should deep compare settings", func(t *testing.T) { + b := a + b.Settings = map[string]any{ + "url": "http://localhost:123", + "flag": false, + "child": map[string]any{ + "sub-form-field": "test123", + "sub-child": map[string]any{ + "test": "test", + }, + }, + } + + result := a.Diff(b) + assert.ElementsMatch(t, + []string{"Settings[url]", "Settings[name]", "Settings[flag]", "Settings[child][sub-form-field]", "Settings[child][sub-child]"}, + result.Paths()) + }) + + t.Run("should shallow compare schemas", func(t *testing.T) { + b := a + b.Config, _ = alertingNotify.GetSchemaVersionForIntegration("slack", schema.V1) + result := a.Diff(b) + assert.ElementsMatch(t, + []string{"Config"}, + result.Paths()) + }) + + t.Run("should compare with zero objects", func(t *testing.T) { + result := a.Diff(Integration{}) + assert.ElementsMatch(t, + []string{ + "UID", + "Name", + "Config", + "Settings[child]", + "Settings[flag]", + "Settings[name]", + "Settings[url]", + "SecureSettings[password]", + "SecureSettings[token]", + }, + result.Paths()) + }) +} + +func TestIntegrationDiffReport_GetSettingsPaths(t *testing.T) { + a := Integration{ + UID: "test-uid", + Name: "test-name", + Config: schema.IntegrationSchemaVersion{}, + DisableResolveMessage: false, + Settings: map[string]any{ + "url": "http://localhost", + "child": map[string]any{ + "field": "test", + "sub-child": map[string]any{ + "test": "test", + }, + }, + }, + } + + testCases := []struct { + name string + left map[string]any + right map[string]any + paths []string + }{ + { + name: "empty", + left: map[string]any{}, + right: map[string]any{}, + }, + { + name: "left is empty", + left: map[string]any{}, + right: map[string]any{ + "field": "test", + }, + paths: []string{"field"}, + }, + { + name: "right is empty", + left: map[string]any{ + "field": "test", + }, + right: map[string]any{}, + paths: []string{"field"}, + }, + { + name: "expands nested", + left: map[string]any{ + "field": map[string]any{ + "sub-field": map[string]any{ + "test": "test", + }, + }, + }, + right: map[string]any{ + "another": map[string]any{ + "sub-field": map[string]any{ + "test": "test", + }, + }, + }, + paths: []string{ + "field.sub-field.test", + "another.sub-field.test", + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + b := a + b.Settings = tc.right + a.Settings = tc.left + diff := a.Diff(b) + + actual := diff.GetSettingsPaths() + actualStrings := make([]string, 0, len(actual)) + for _, f := range actual { + actualStrings = append(actualStrings, f.String()) + } + assert.ElementsMatch(t, tc.paths, actualStrings) + }) + } +} + +func TestHasDifferentProtectedFields(t *testing.T) { + m := IntegrationMuts + + testCase := []struct { + name string + existing Integration + incoming Integration + expected map[string][]string + }{ + { + name: "different UID do not match", + existing: IntegrationGen(m.WithUID("existing"), m.WithValidConfig("webhook"))(), + incoming: IntegrationGen( + m.WithValidConfig("webhook"), + m.AddSetting("url", "http://some-other-url"), + m.WithUID("incoming"), + )(), + expected: nil, + }, + { + name: "find url protected", + existing: IntegrationGen(m.WithUID("1"), m.WithValidConfig("webhook"))(), + incoming: IntegrationGen( + m.WithValidConfig("webhook"), + m.AddSetting("url", "http://some-other-url"), + m.AddSetting("http_config", map[string]any{ + "oauth2": map[string]any{ + "proxy_config": map[string]any{ + "proxy_url": "http://some-other-url-proxy", + }, + "token_url": "http://some-other-url-token", + }, + }), + m.WithUID("1"), + )(), + expected: map[string][]string{ + "1": { + "http_config.oauth2.proxy_config.proxy_url", + "http_config.oauth2.token_url", + "url", + }, + }, + }, + { + name: "secure and protected", // simulate the situation when protected secured field is in secure settings but the incoming one has it in settings + existing: IntegrationGen( + m.WithUID("1"), + m.WithValidConfig("discord"), + m.RemoveSetting("url"), + m.WithSecureSettings(map[string]string{ + "url": "", + }))(), + incoming: IntegrationGen( + m.WithValidConfig("discord"), + m.AddSetting("url", "http://some-other-url"), + m.WithSecureSettings(nil), + m.WithUID("1"), + )(), + expected: map[string][]string{ + "1": { + "url", + }, + }, + }, + } + + for _, tc := range testCase { + t.Run(tc.name, func(t *testing.T) { + existing := &Receiver{ + Integrations: []*Integration{ + &tc.existing, + }, + } + incoming := &Receiver{ + Integrations: []*Integration{ + &tc.incoming, + }, + } + actual := HasReceiversDifferentProtectedFields(existing, incoming) + if len(tc.expected) == 0 { + require.Empty(t, actual) + return + } + actualStrings := make(map[string][]string, len(actual)) + for uid, paths := range actual { + for _, path := range paths { + actualStrings[uid] = append(actualStrings[uid], path.String()) + } + slices.Sort(actualStrings[uid]) + } + assert.EqualValues(t, tc.expected, actualStrings) + }) + } +} diff --git a/pkg/services/ngalert/models/testing.go b/pkg/services/ngalert/models/testing.go index 886f13d029a..8180afb0012 100644 --- a/pkg/services/ngalert/models/testing.go +++ b/pkg/services/ngalert/models/testing.go @@ -973,6 +973,12 @@ func (a AlertInstanceMutators) WithAnnotations(annotations InstanceAnnotations) } } +func (a AlertInstanceMutators) WithResultFingerprint(fp string) AlertInstanceMutator { + return func(i *AlertInstance) { + i.ResultFingerprint = fp + } +} + type Mutator[T any] func(*T) // CopyNotificationSettings creates a deep copy of NotificationSettings. @@ -1451,6 +1457,12 @@ func (n IntegrationMutators) AddSecureSetting(key, val string) Mutator[Integrati } } +func (n IntegrationMutators) RemoveSetting(key string) Mutator[Integration] { + return func(c *Integration) { + delete(c.Settings, key) + } +} + func randomMapKey[K comparable, V any](m map[K]V) (K, V) { randIdx := rand.Intn(len(m)) i := 0 diff --git a/pkg/services/ngalert/notifier/alertmanager.go b/pkg/services/ngalert/notifier/alertmanager.go index 05e42a66b09..f192ed88058 100644 --- a/pkg/services/ngalert/notifier/alertmanager.go +++ b/pkg/services/ngalert/notifier/alertmanager.go @@ -12,6 +12,7 @@ import ( "github.com/grafana/alerting/models" alertingNotify "github.com/grafana/alerting/notify" "github.com/grafana/alerting/notify/nfstatus" + alertingTemplates "github.com/grafana/alerting/templates" "github.com/prometheus/alertmanager/config" amv2 "github.com/prometheus/alertmanager/api/v2/models" @@ -58,6 +59,7 @@ type alertmanager struct { decryptFn alertingNotify.GetDecryptedValueFn crypto Crypto features featuremgmt.FeatureToggles + dynamicLimits alertingNotify.DynamicLimits } // maintenanceOptions represent the options for components that need maintenance on a frequency within the Alertmanager. @@ -148,6 +150,16 @@ func NewAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A return nil, err } + limits := alertingNotify.DynamicLimits{ + Dispatcher: nilLimits{}, + Templates: alertingTemplates.Limits{ + MaxTemplateOutputSize: cfg.UnifiedAlerting.AlertmanagerMaxTemplateOutputSize, + }, + } + if err := limits.Templates.Validate(); err != nil { + return nil, fmt.Errorf("invalid template limits: %w", err) + } + am := &alertmanager{ Base: gam, ConfigMetrics: m.AlertmanagerConfigMetrics, @@ -158,6 +170,7 @@ func NewAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A decryptFn: decryptFn, crypto: crypto, features: featureToggles, + dynamicLimits: limits, } return am, nil @@ -382,7 +395,7 @@ func (am *alertmanager) applyConfig(ctx context.Context, cfg *apimodels.Postable TimeIntervals: amConfig.TimeIntervals, Templates: templates, Receivers: receivers, - DispatcherLimits: &nilLimits{}, + Limits: am.dynamicLimits, Raw: rawConfig, Hash: configHash, }) diff --git a/pkg/services/ngalert/notifier/alertmanager_config.go b/pkg/services/ngalert/notifier/alertmanager_config.go index 87d573124e7..7e755903791 100644 --- a/pkg/services/ngalert/notifier/alertmanager_config.go +++ b/pkg/services/ngalert/notifier/alertmanager_config.go @@ -333,7 +333,7 @@ func (moa *MultiOrgAlertmanager) SaveAndApplyAlertmanagerConfiguration(ctx conte config.ExtraConfigs = extraConfigs } - if err := moa.Crypto.ProcessSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers); err != nil { + if err := moa.Crypto.ProcessSecureSettings(ctx, org, config.AlertmanagerConfig.Receivers, nil); err != nil { return fmt.Errorf("failed to post process Alertmanager configuration: %w", err) } diff --git a/pkg/services/ngalert/notifier/crypto.go b/pkg/services/ngalert/notifier/crypto.go index ab5d5f03096..246cd03d64d 100644 --- a/pkg/services/ngalert/notifier/crypto.go +++ b/pkg/services/ngalert/notifier/crypto.go @@ -29,16 +29,18 @@ const ( cryptoPrefix = "crypto_" ) +type AuthorizeProtectedFn func(uid string, paths []schema.IntegrationFieldPath) error + // Crypto allows decryption of Alertmanager Configuration and encryption of arbitrary payloads. type Crypto interface { - LoadSecureSettings(ctx context.Context, orgId int64, receivers []*definitions.PostableApiReceiver) error + LoadSecureSettings(ctx context.Context, orgId int64, receivers []*definitions.PostableApiReceiver, fn AuthorizeProtectedFn) error Encrypt(ctx context.Context, payload []byte, opt secrets.EncryptionOptions) ([]byte, error) Decrypt(ctx context.Context, payload []byte) ([]byte, error) EncryptExtraConfigs(ctx context.Context, config *definitions.PostableUserConfig) error DecryptExtraConfigs(ctx context.Context, config *definitions.PostableUserConfig) error getDecryptedSecret(r *definitions.PostableGrafanaReceiver, key string) (string, error) - ProcessSecureSettings(ctx context.Context, orgId int64, recvs []*definitions.PostableApiReceiver) error + ProcessSecureSettings(ctx context.Context, orgId int64, recvs []*definitions.PostableApiReceiver, fn AuthorizeProtectedFn) error } // alertmanagerCrypto implements decryption of Alertmanager configuration and encryption of arbitrary payloads based on Grafana's encryptions. @@ -57,7 +59,7 @@ func NewCrypto(secrets secrets.Service, configs configurationStore, log log.Logg } // ProcessSecureSettings encrypts new secure settings and loads existing secure settings from the database. -func (c *alertmanagerCrypto) ProcessSecureSettings(ctx context.Context, orgId int64, recvs []*definitions.PostableApiReceiver) error { +func (c *alertmanagerCrypto) ProcessSecureSettings(ctx context.Context, orgId int64, recvs []*definitions.PostableApiReceiver, authorizeProtected AuthorizeProtectedFn) error { // First, we encrypt the new or updated secure settings. Then, we load the existing secure settings from the database // and add back any that weren't updated. // We perform these steps in this order to ensure the hash of the secure settings remains stable when no secure @@ -68,7 +70,7 @@ func (c *alertmanagerCrypto) ProcessSecureSettings(ctx context.Context, orgId in return fmt.Errorf("failed to encrypt receivers: %w", err) } - if err := c.LoadSecureSettings(ctx, orgId, recvs); err != nil { + if err := c.LoadSecureSettings(ctx, orgId, recvs, authorizeProtected); err != nil { return err } @@ -167,7 +169,7 @@ func encryptReceiverConfigs(c []*definitions.PostableApiReceiver, encrypt defini } // LoadSecureSettings adds the corresponding unencrypted secrets stored to the list of input receivers. -func (c *alertmanagerCrypto) LoadSecureSettings(ctx context.Context, orgId int64, receivers []*definitions.PostableApiReceiver) error { +func (c *alertmanagerCrypto) LoadSecureSettings(ctx context.Context, orgId int64, receivers []*definitions.PostableApiReceiver, authorizeProtected AuthorizeProtectedFn) error { // Get the last known working configuration. amConfig, err := c.configs.GetLatestAlertmanagerConfiguration(ctx, orgId) if err != nil { @@ -176,10 +178,10 @@ func (c *alertmanagerCrypto) LoadSecureSettings(ctx context.Context, orgId int64 return fmt.Errorf("failed to get latest configuration: %w", err) } } - + var currentConfig *definitions.PostableUserConfig currentReceiverMap := make(map[string]*definitions.PostableGrafanaReceiver) if amConfig != nil { - currentConfig, err := Load([]byte(amConfig.AlertmanagerConfiguration)) + currentConfig, err = Load([]byte(amConfig.AlertmanagerConfiguration)) // If the current config is un-loadable, treat it as if it never existed. Providing a new, valid config should be able to "fix" this state. if err != nil { c.log.Warn("Last known alertmanager configuration was invalid. Overwriting...") @@ -209,6 +211,33 @@ func (c *alertmanagerCrypto) LoadSecureSettings(ctx context.Context, orgId int64 return UnknownReceiverError{UID: gr.UID} } + if authorizeProtected != nil { + incoming, errIn := legacy_storage.PostableGrafanaReceiverToIntegration(gr) + existing, errEx := legacy_storage.PostableGrafanaReceiverToIntegration(cgmr) + var secure []schema.IntegrationFieldPath + authz := true + if errIn == nil && errEx == nil { + secure = models.HasIntegrationsDifferentProtectedFields(existing, incoming) + authz = len(secure) > 0 + } + // if conversion failed, consider there are changes and authorize + if authz && currentConfig != nil { + var receiverName string + NAME: + for _, rcv := range currentConfig.AlertmanagerConfig.Receivers { + for _, intg := range rcv.GrafanaManagedReceivers { + if intg.UID == cgmr.UID { + receiverName = rcv.Name + break NAME + } + } + } + if err := authorizeProtected(receiverName, secure); err != nil { + return err + } + } + } + // Frontend sends only the secure settings that have to be updated // Therefore we have to copy from the last configuration only those secure settings not included in the request for key, encryptedValue := range cgmr.SecureSettings { diff --git a/pkg/services/ngalert/notifier/receiver_svc.go b/pkg/services/ngalert/notifier/receiver_svc.go index 56a68fb3e55..e05b12a2920 100644 --- a/pkg/services/ngalert/notifier/receiver_svc.go +++ b/pkg/services/ngalert/notifier/receiver_svc.go @@ -80,6 +80,9 @@ type receiverAccessControlService interface { AuthorizeUpdate(context.Context, identity.Requester, *models.Receiver) error AuthorizeDeleteByUID(context.Context, identity.Requester, string) error + HasUpdateProtected(context.Context, identity.Requester, *models.Receiver) (bool, error) + AuthorizeUpdateProtected(context.Context, identity.Requester, *models.Receiver) error + Access(ctx context.Context, user identity.Requester, receivers ...*models.Receiver) (map[string]models.ReceiverPermissionSet, error) } @@ -474,6 +477,18 @@ func (rs *ReceiverService) UpdateReceiver(ctx context.Context, r *models.Receive return nil, err } + // if user does not have permissions to update protected, check the diff and return error if there is a change in protected fields + canUpdateProtected, _ := rs.authz.HasUpdateProtected(ctx, user, r) + if !canUpdateProtected { + diff := models.HasReceiversDifferentProtectedFields(existing, r) + if len(diff) > 0 { + err = rs.authz.AuthorizeUpdateProtected(ctx, user, r) + if err != nil { + return nil, makeProtectedFieldsAuthzError(err, diff) + } + } + } + // We need to perform two important steps to process settings on an updated integration: // 1. Encrypt new or updated secret fields as they will arrive in plain text. // 2. For updates, callers do not re-send unchanged secure settings and instead mark them in SecureFields. We need diff --git a/pkg/services/ngalert/notifier/receiver_svc_err.go b/pkg/services/ngalert/notifier/receiver_svc_err.go new file mode 100644 index 00000000000..06b27602f75 --- /dev/null +++ b/pkg/services/ngalert/notifier/receiver_svc_err.go @@ -0,0 +1,30 @@ +package notifier + +import ( + "errors" + "slices" + + "github.com/grafana/alerting/receivers/schema" + + "github.com/grafana/grafana/pkg/apimachinery/errutil" +) + +func makeProtectedFieldsAuthzError(err error, diff map[string][]schema.IntegrationFieldPath) error { + var authzErr errutil.Error + if !errors.As(err, &authzErr) { + return err + } + if authzErr.PublicPayload == nil { + authzErr.PublicPayload = map[string]interface{}{} + } + fields := make(map[string][]string, len(diff)) + for field, paths := range diff { + fields[field] = make([]string, len(paths)) + for i, path := range paths { + fields[field][i] = path.String() + } + slices.Sort(fields[field]) + } + authzErr.PublicPayload["changed_protected_fields"] = fields + return authzErr +} diff --git a/pkg/services/ngalert/notifier/receiver_svc_test.go b/pkg/services/ngalert/notifier/receiver_svc_test.go index 8d4b7630436..10e84f33b62 100644 --- a/pkg/services/ngalert/notifier/receiver_svc_test.go +++ b/pkg/services/ngalert/notifier/receiver_svc_test.go @@ -659,8 +659,9 @@ func TestReceiverService_Update(t *testing.T) { writer := &user.SignedInUser{OrgID: 1, Permissions: map[int64]map[string][]string{ 1: { - accesscontrol.ActionAlertingNotificationsWrite: nil, - accesscontrol.ActionAlertingNotificationsRead: nil, + accesscontrol.ActionAlertingNotificationsWrite: nil, + accesscontrol.ActionAlertingNotificationsRead: nil, + accesscontrol.ActionAlertingReceiversUpdateProtected: {models.ScopeReceiversAll}, }, }} decryptUser := &user.SignedInUser{OrgID: 1, Permissions: map[int64]map[string][]string{ @@ -1310,7 +1311,7 @@ func TestReceiverServiceAC_Update(t *testing.T) { }, }} - slackIntegration := models.IntegrationGen(models.IntegrationMuts.WithName("test receiver"), models.IntegrationMuts.WithValidConfig("slack")) + slackIntegration := models.IntegrationGen(models.IntegrationMuts.WithName("test receiver"), models.IntegrationMuts.WithValidConfig("webhook")) emailIntegration := models.IntegrationGen(models.IntegrationMuts.WithName("test receiver"), models.IntegrationMuts.WithValidConfig("email")) recv1 := models.ReceiverGen(models.ReceiverMuts.WithName("receiver1"), models.ReceiverMuts.WithIntegrations(slackIntegration(), emailIntegration()))() recv2 := models.ReceiverGen(models.ReceiverMuts.WithName("receiver2"), models.ReceiverMuts.WithIntegrations(slackIntegration(), emailIntegration()))() @@ -1322,8 +1323,8 @@ func TestReceiverServiceAC_Update(t *testing.T) { name string permissions map[string][]string existing []models.Receiver - - hasAccess []models.Receiver + incoming []models.Receiver + hasAccess []models.Receiver }{ { name: "not authorized without permissions", @@ -1411,6 +1412,43 @@ func TestReceiverServiceAC_Update(t *testing.T) { existing: allReceivers(), hasAccess: []models.Receiver{recv1, recv3}, }, + { + name: "protected fields modified without permission", + permissions: map[string][]string{ + accesscontrol.ActionAlertingReceiversUpdate: {models.ScopeReceiversAll}, + accesscontrol.ActionAlertingReceiversRead: {models.ScopeReceiversAll}, + }, + existing: []models.Receiver{ + recv1, + }, + incoming: []models.Receiver{ + func() models.Receiver { + f := recv1.Clone() + f.Integrations[0].Settings["url"] = "https://example.com/new" + return f + }(), + }, + hasAccess: nil, + }, + { + name: "protected fields modified with permission", + permissions: map[string][]string{ + accesscontrol.ActionAlertingReceiversUpdate: {models.ScopeReceiversAll}, + accesscontrol.ActionAlertingReceiversRead: {models.ScopeReceiversAll}, + accesscontrol.ActionAlertingReceiversUpdateProtected: {models.ScopeReceiversAll}, + }, + existing: []models.Receiver{ + recv1, + }, + incoming: []models.Receiver{ + func() models.Receiver { + f := recv1.Clone() + f.Integrations[0].Settings["url"] = "https://example.com/new" + return f + }(), + }, + hasAccess: []models.Receiver{recv1}, + }, } for _, tc := range testCases { @@ -1436,7 +1474,11 @@ func TestReceiverServiceAC_Update(t *testing.T) { } return false } - for _, recv := range allReceivers() { + incoming := allReceivers() + if tc.incoming != nil { + incoming = tc.incoming + } + for _, recv := range incoming { clone := recv.Clone() clone.Version = versions[recv.UID] response, err := sut.UpdateReceiver(context.Background(), &clone, nil, orgId, usr) @@ -1734,6 +1776,7 @@ func TestReceiverService_AccessControlMetadata(t *testing.T) { expectedPermissions.Set(models.ReceiverPermissionAdmin, false) expectedPermissions.Set(models.ReceiverPermissionWrite, false) expectedPermissions.Set(models.ReceiverPermissionDelete, false) + expectedPermissions.Set(models.ReceiverPermissionModifyProtected, false) expectedPermissions.Set(models.ReceiverPermissionReadSecret, true) expected := map[string]models.ReceiverPermissionSet{ diff --git a/pkg/services/ngalert/provisioning/alert_rules.go b/pkg/services/ngalert/provisioning/alert_rules.go index aa6c4c55b34..b5ff7506650 100644 --- a/pkg/services/ngalert/provisioning/alert_rules.go +++ b/pkg/services/ngalert/provisioning/alert_rules.go @@ -114,7 +114,7 @@ func (service *AlertRuleService) ListAlertRules(ctx context.Context, user identi } folderUIDs := make([]string, 0, len(folders)) for _, f := range folders { - access, err := service.authz.HasAccessInFolder(ctx, user, models.Namespace(*f.ToFolderReference())) + access, err := service.authz.HasAccessInFolder(ctx, user, models.NewNamespace(f)) if err != nil { return nil, nil, "", err } @@ -407,6 +407,9 @@ func (service *AlertRuleService) UpdateRuleGroup(ctx context.Context, user ident if err := models.ValidateRuleGroupInterval(intervalSeconds, service.baseIntervalSeconds); err != nil { return err } + if err := service.ensureNamespace(ctx, user, user.GetOrgID(), namespaceUID); err != nil { + return err + } return service.xact.InTransaction(ctx, func(ctx context.Context) error { query := &models.ListAlertRulesQuery{ OrgID: user.GetOrgID(), @@ -471,6 +474,10 @@ func (service *AlertRuleService) ReplaceRuleGroup(ctx context.Context, user iden return err } + if err := service.ensureNamespace(ctx, user, user.GetOrgID(), group.FolderUID); err != nil { + return err + } + // If the rule group is reserved for no-group rules, we cannot have multiple rules in it. if models.IsNoGroupRuleGroup(group.Title) && len(group.Rules) > 1 { return fmt.Errorf("rule group %s is reserved for no-group rules and cannot be used for rule groups with multiple rules", group.Title) @@ -1025,6 +1032,7 @@ func (service *AlertRuleService) checkGroupLimits(group models.AlertRuleGroup) e // ensureNamespace ensures that the rule has a valid namespace UID. // If the rule does not have a namespace UID or the namespace (folder) does not exist it will return an error. +// If the folder is managed by a manager, it will also return an error. func (service *AlertRuleService) ensureNamespace(ctx context.Context, user identity.Requester, orgID int64, namespaceUID string) error { if namespaceUID == "" { return fmt.Errorf("%w: folderUID must be set", models.ErrAlertRuleFailedValidation) @@ -1037,18 +1045,23 @@ func (service *AlertRuleService) ensureNamespace(ctx context.Context, user ident } // ensure the namespace exists - _, err := service.folderService.Get(ctx, &folder.GetFolderQuery{ + f, err := service.folderService.Get(ctx, &folder.GetFolderQuery{ OrgID: orgID, UID: &namespaceUID, SignedInUser: user, }) - if err != nil { + if err != nil || f == nil { if errors.Is(err, dashboards.ErrFolderNotFound) { return fmt.Errorf("%w: folder does not exist", models.ErrAlertRuleFailedValidation) } return err } + // check if the folder is managed by a manager + if err := models.NewNamespace(f).ValidateForRuleStorage(); err != nil { + return fmt.Errorf("%w: %s", models.ErrAlertRuleFailedValidation, err) + } + return nil } diff --git a/pkg/services/ngalert/provisioning/alert_rules_test.go b/pkg/services/ngalert/provisioning/alert_rules_test.go index c552f797429..ed001a527c4 100644 --- a/pkg/services/ngalert/provisioning/alert_rules_test.go +++ b/pkg/services/ngalert/provisioning/alert_rules_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/apimachinery/identity" + "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/expr" "github.com/grafana/grafana/pkg/infra/db" @@ -867,6 +868,27 @@ func TestIntegrationAlertRuleService(t *testing.T) { require.NoError(t, err) require.Equal(t, int64(120), rule.IntervalSeconds) }) + + t.Run("UpdateRuleGroup should reject when folder is managed by a manager", func(t *testing.T) { + service, _, _, ac := initService(t) + ac.CanWriteAllRulesFunc = func(ctx context.Context, user identity.Requester) (bool, error) { + return true, nil + } + + managedFolderUID := "managed-folder-update-group" + fs := foldertest.NewFakeService() + fs.AddFolder(&folder.Folder{ + OrgID: orgID, + UID: managedFolderUID, + Title: "Managed Folder", + ManagedBy: utils.ManagerKindRepo, + }) + service.folderService = fs + + err := service.UpdateRuleGroup(context.Background(), u, managedFolderUID, "some-group", 120) + require.ErrorIs(t, err, models.ErrAlertRuleFailedValidation) + require.ErrorContains(t, err, "cannot store rules in folder managed by Git Sync") + }) } func TestIntegrationCreateAlertRule(t *testing.T) { @@ -1166,6 +1188,30 @@ func TestIntegrationCreateAlertRule(t *testing.T) { require.NoError(t, err) require.True(t, models.IsNoGroupRuleGroup(retrievedRule.RuleGroup), "Rule should be considered NoGroup rule") }) + + t.Run("should reject creation when folder is managed by a manager", func(t *testing.T) { + service, _, _, ac := initService(t) + ac.CanWriteAllRulesFunc = func(ctx context.Context, user identity.Requester) (bool, error) { + return true, nil + } + + managedFolderUID := "managed-folder" + fs := foldertest.NewFakeService() + fs.AddFolder(&folder.Folder{ + OrgID: orgID, + UID: managedFolderUID, + Title: "Managed Folder", + ManagedBy: utils.ManagerKindRepo, + }) + service.folderService = fs + + rule := dummyRule("test-managed-folder", orgID) + rule.NamespaceUID = managedFolderUID + + _, err := service.CreateAlertRule(context.Background(), u, rule, models.ProvenanceNone) + require.ErrorIs(t, err, models.ErrAlertRuleFailedValidation) + require.ErrorContains(t, err, "cannot store rules in folder managed by Git Sync") + }) } func TestUpdateAlertRule(t *testing.T) { @@ -1316,6 +1362,36 @@ func TestUpdateAlertRule(t *testing.T) { require.Equal(t, "nogroup-update-new", updated.Title) require.Equal(t, originalInterval, updated.IntervalSeconds) }) + + t.Run("should reject update when folder is managed by a manager", func(t *testing.T) { + service, ruleStore, provenanceStore, ac := initService(t) + ac.CanWriteAllRulesFunc = func(ctx context.Context, user identity.Requester) (bool, error) { + return true, nil + } + + managedFolderUID := "managed-folder-update" + fs := foldertest.NewFakeService() + fs.AddFolder(&folder.Folder{ + OrgID: orgID, + UID: managedFolderUID, + Title: "Managed Folder", + ManagedBy: utils.ManagerKindRepo, + }) + service.folderService = fs + + // Create an existing rule + existingRule := dummyRule("test-managed-folder-update", orgID) + existingRule.NamespaceUID = managedFolderUID + _, err := ruleStore.InsertAlertRules(context.Background(), models.NewUserUID(u), []models.InsertRule{{AlertRule: existingRule}}) + require.NoError(t, err) + require.NoError(t, provenanceStore.SetProvenance(context.Background(), &existingRule, orgID, models.ProvenanceNone)) + + // Try to update the rule + existingRule.Title = "Updated Title" + _, err = service.UpdateAlertRule(context.Background(), u, existingRule, models.ProvenanceNone) + require.ErrorIs(t, err, models.ErrAlertRuleFailedValidation) + require.ErrorContains(t, err, "cannot store rules in folder managed by Git Sync") + }) } func TestDeleteAlertRule(t *testing.T) { @@ -2054,6 +2130,33 @@ func TestReplaceGroup(t *testing.T) { require.Error(t, err) require.ErrorContains(t, err, "cannot move rule out of this group") }) + + t.Run("should reject replace when folder is managed by a manager", func(t *testing.T) { + service, _, _, ac := initService(t) + ac.CanWriteAllRulesFunc = func(ctx context.Context, user identity.Requester) (bool, error) { + return true, nil + } + + managedFolderUID := "managed-folder-replace" + fs := foldertest.NewFakeService() + fs.AddFolder(&folder.Folder{ + OrgID: orgID, + UID: managedFolderUID, + Title: "Managed Folder", + ManagedBy: utils.ManagerKindRepo, + }) + service.folderService = fs + + group := models.AlertRuleGroup{ + Title: "test-group", + FolderUID: managedFolderUID, + Interval: 60, + } + + err := service.ReplaceRuleGroup(context.Background(), u, group, models.ProvenanceNone, "") + require.ErrorIs(t, err, models.ErrAlertRuleFailedValidation) + require.ErrorContains(t, err, "cannot store rules in folder managed by Git Sync") + }) } func TestDeleteRuleGroup(t *testing.T) { diff --git a/pkg/services/ngalert/schedule/alert_rule.go b/pkg/services/ngalert/schedule/alert_rule.go index 3991df89e77..ebb3a1aa1e9 100644 --- a/pkg/services/ngalert/schedule/alert_rule.go +++ b/pkg/services/ngalert/schedule/alert_rule.go @@ -47,10 +47,10 @@ type Rule interface { Identifier() ngmodels.AlertRuleKeyWithGroup } -type ruleFactoryFunc func(context.Context, *ngmodels.AlertRule) Rule +type ruleFactoryFunc func(context.Context, ruleWithFolder) Rule -func (f ruleFactoryFunc) new(ctx context.Context, rule *ngmodels.AlertRule) Rule { - return f(ctx, rule) +func (f ruleFactoryFunc) new(ctx context.Context, rf ruleWithFolder) Rule { + return f(ctx, rf) } func newRuleFactory( @@ -70,11 +70,11 @@ func newRuleFactory( evalAppliedHook evalAppliedFunc, stopAppliedHook stopAppliedFunc, ) ruleFactoryFunc { - return func(ctx context.Context, rule *ngmodels.AlertRule) Rule { - if rule.Type() == ngmodels.RuleTypeRecording { + return func(ctx context.Context, rf ruleWithFolder) Rule { + if rf.rule.Type() == ngmodels.RuleTypeRecording { return newRecordingRule( ctx, - rule.GetKeyWithGroup(), + rf.rule.GetKeyWithGroup(), retryConfig, clock, evalFactory, @@ -89,7 +89,7 @@ func newRuleFactory( } return newAlertRule( ctx, - rule.GetKeyWithGroup(), + rf, appURL, disableGrafanaFolder, retryConfig, @@ -111,7 +111,8 @@ type evalAppliedFunc = func(ngmodels.AlertRuleKey, time.Time) type stopAppliedFunc = func(ngmodels.AlertRuleKey) type alertRule struct { - key ngmodels.AlertRuleKeyWithGroup + key ngmodels.AlertRuleKeyWithGroup + currentFingerprint fingerprint evalCh chan *Evaluation updateCh chan *Evaluation @@ -139,7 +140,7 @@ type alertRule struct { func newAlertRule( parent context.Context, - key ngmodels.AlertRuleKeyWithGroup, + rf ruleWithFolder, appURL *url.URL, disableGrafanaFolder bool, retryConfig RetryConfig, @@ -154,10 +155,13 @@ func newAlertRule( evalAppliedHook func(ngmodels.AlertRuleKey, time.Time), stopAppliedHook func(ngmodels.AlertRuleKey), ) *alertRule { + key := rf.rule.GetKeyWithGroup() + initialFingerprint := rf.Fingerprint() ctx, stop := util.WithCancelCause(ngmodels.WithRuleKey(parent, key.AlertRuleKey)) - return &alertRule{ + a := &alertRule{ key: key, + currentFingerprint: initialFingerprint, evalCh: make(chan *Evaluation), updateCh: make(chan *Evaluation), ctx: ctx, @@ -176,6 +180,8 @@ func newAlertRule( tracer: tracer, featureToggles: featureToggles, } + + return a } func (a *alertRule) Identifier() ngmodels.AlertRuleKeyWithGroup { @@ -246,22 +252,23 @@ func (a *alertRule) Run() error { grafanaCtx := a.ctx a.logger.Debug("Alert rule routine started") - var currentFingerprint fingerprint + firstEvalDone := false + defer a.stopApplied() for { select { // used by external services (API) to notify that rule is updated. case ctx := <-a.updateCh: fp := ctx.Fingerprint() - if currentFingerprint == fp { - a.logger.Info("Rule's fingerprint has not changed. Skip resetting the state", "currentFingerprint", currentFingerprint) + if a.currentFingerprint == fp { + a.logger.Info("Rule's fingerprint has not changed. Skip resetting the state", "currentFingerprint", a.currentFingerprint) continue } a.logger.Info("Clearing the state of the rule because it was updated", "isPaused", ctx.rule.IsPaused, "fingerprint", fp) // clear the state. So the next evaluation will start from the scratch. a.resetState(grafanaCtx, ctx.rule, ctx.rule.IsPaused) - currentFingerprint = fp + a.currentFingerprint = fp // evalCh - used by the scheduler to signal that evaluation is needed. case ctx, ok := <-a.evalCh: if !ok { @@ -295,20 +302,21 @@ func (a *alertRule) Run() error { for { isPaused := ctx.rule.IsPaused - // Do not clean up state if the eval loop has just started. var needReset bool - if currentFingerprint != 0 && currentFingerprint != f { - logger.Debug("Got a new version of alert rule. Clear up the state", "current_fingerprint", currentFingerprint, "fingerprint", f) + if a.currentFingerprint != f { + logger.Debug("Got a new version of alert rule. Clear up the state", "current_fingerprint", a.currentFingerprint, "fingerprint", f) needReset = true } // We need to reset state if the loop has started and the alert is already paused. It can happen, // if we have an alert with state and we do file provision with stateful Grafana, that state // lingers in DB and won't be cleaned up until next alert rule update. - needReset = needReset || (currentFingerprint == 0 && isPaused) + needReset = needReset || (!firstEvalDone && isPaused) if needReset { a.resetState(grafanaCtx, ctx.rule, isPaused) } - currentFingerprint = f + + firstEvalDone = true + a.currentFingerprint = f if isPaused { logger.Debug("Skip rule evaluation because it is paused") return @@ -319,7 +327,7 @@ func (a *alertRule) Run() error { evalTotal.Inc() } - fpStr := currentFingerprint.String() + fpStr := a.currentFingerprint.String() utcTick := ctx.scheduledAt.UTC().Format(time.RFC3339Nano) tracingCtx, span := a.tracer.Start(grafanaCtx, "alert rule execution", trace.WithAttributes( attribute.String("rule_uid", ctx.rule.UID), diff --git a/pkg/services/ngalert/schedule/alert_rule_test.go b/pkg/services/ngalert/schedule/alert_rule_test.go index 48be6bb4a40..6f4144b37bf 100644 --- a/pkg/services/ngalert/schedule/alert_rule_test.go +++ b/pkg/services/ngalert/schedule/alert_rule_test.go @@ -334,7 +334,7 @@ func TestAlertRuleAfterEval(t *testing.T) { ruleStore.PutRule(context.Background(), rule) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) return &testContext{ rule: rule, @@ -503,7 +503,14 @@ func blankRuleForTests(ctx context.Context, key models.AlertRuleKeyWithGroup) *a Log: log.NewNopLogger(), } st := state.NewManager(managerCfg, state.NewNoopPersister()) - return newAlertRule(ctx, key, nil, false, RetryConfig{}, nil, st, nil, nil, nil, log.NewNopLogger(), nil, featuremgmt.WithFeatures(), nil, nil) + // Create a minimal rule from the key + rule := &models.AlertRule{ + OrgID: key.OrgID, + UID: key.UID, + RuleGroup: key.RuleGroup, + } + rf := ruleWithFolder{rule: rule, folderTitle: ""} + return newAlertRule(ctx, rf, nil, false, RetryConfig{}, nil, st, nil, nil, nil, log.NewNopLogger(), nil, featuremgmt.WithFeatures(), nil, nil) } func TestRuleRoutine(t *testing.T) { @@ -540,7 +547,7 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) go func() { _ = ruleInfo.Run() }() @@ -728,7 +735,8 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) - ruleInfo := factory.new(ctx, rule) + folderTitle := "" + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) go func() { err := ruleInfo.Run() stoppedChan <- err @@ -750,7 +758,7 @@ func TestRuleRoutine(t *testing.T) { require.NotEmpty(t, sch.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID)) factory := ruleFactoryFromScheduler(sch) - ruleInfo := factory.new(context.Background(), rule) + ruleInfo := factory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) go func() { err := ruleInfo.Run() stoppedChan <- err @@ -774,7 +782,7 @@ func TestRuleRoutine(t *testing.T) { require.NotEmpty(t, sch.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID)) factory := ruleFactoryFromScheduler(sch) - ruleInfo := factory.new(context.Background(), rule) + ruleInfo := factory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) go func() { err := ruleInfo.Run() stoppedChan <- err @@ -804,7 +812,7 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) go func() { _ = ruleInfo.Run() @@ -871,6 +879,140 @@ func TestRuleRoutine(t *testing.T) { }) }) + t.Run("when update is sent before first evaluation", func(t *testing.T) { + rule := gen.With(withQueryForState(t, eval.Normal)).GenerateRef() + folderTitle := "folderName" + + evalAppliedChan := make(chan time.Time) + + sender := NewSyncAlertsSenderMock() + sender.EXPECT().Send(mock.Anything, rule.GetKey(), mock.Anything).Return() + + sch, ruleStore, _, _ := createSchedule(evalAppliedChan, sender, clock.NewMock()) + ruleStore.PutRule(context.Background(), rule) + sch.schedulableAlertRules.set([]*models.AlertRule{rule}, map[models.FolderKey]string{rule.GetFolderKey(): folderTitle}) + + // Add state to verify it's not cleared + states := []*state.State{ + { + AlertRuleUID: rule.UID, + CacheID: data.Labels(rule.Labels).Fingerprint(), + OrgID: rule.OrgID, + State: eval.Alerting, + StartsAt: sch.clock.Now(), + EndsAt: sch.clock.Now().Add(5 * time.Second), + Labels: rule.Labels, + }, + } + sch.stateManager.Put(states) + + t.Run("should not reset state if fingerprint is the same", func(t *testing.T) { + factory := ruleFactoryFromScheduler(sch) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) + + go func() { + _ = ruleInfo.Run() + }() + + // Send update before first evaluation - same rule, same fingerprint + // This should not reset state since fingerprint is the same + ruleInfo.Update(&Evaluation{rule: rule, folderTitle: folderTitle}) + + // Give time for update to be processed + time.Sleep(100 * time.Millisecond) + + actualStates := sch.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID) + require.NotEmpty(t, actualStates) + }) + + t.Run("should reset state if fingerprint is different", func(t *testing.T) { + // Re-add state for this test + sch.stateManager.Put(states) + + sender := NewSyncAlertsSenderMock() + sender.EXPECT().Send(mock.Anything, rule.GetKey(), mock.Anything).Return() + + sch2, ruleStore2, _, _ := createSchedule(make(chan time.Time), sender, clock.NewMock()) + ruleStore2.PutRule(context.Background(), rule) + sch2.schedulableAlertRules.set([]*models.AlertRule{rule}, map[models.FolderKey]string{rule.GetFolderKey(): folderTitle}) + sch2.stateManager.Put(states) + + factory := ruleFactoryFromScheduler(sch2) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) + + go func() { + _ = ruleInfo.Run() + }() + + // Send update before first eval, with a changed alert rule title. + // This should reset state and send resolved alerts + updatedRule := models.CopyRule(rule, gen.WithTitle(util.GenerateShortUID())) + ruleInfo.Update(&Evaluation{rule: updatedRule, folderTitle: folderTitle}) + + // Wait for sender to be called (which happens when state is cleared and resolved alerts are sent) + require.Eventually(t, func() bool { + return len(sender.Calls()) > 0 + }, 5*time.Second, 100*time.Millisecond) + + // State should be cleared because fingerprint changed + actualStates := sch2.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID) + require.Empty(t, actualStates) + }) + }) + + t.Run("paused rule should reset state on first evaluation", func(t *testing.T) { + rule := gen.With(withQueryForState(t, eval.Normal)).GenerateRef() + rule.IsPaused = true + folderTitle := "folderName" + + sender := NewSyncAlertsSenderMock() + sender.EXPECT().Send(mock.Anything, rule.GetKey(), mock.Anything).Return() + + sch, ruleStore, _, _ := createSchedule(make(chan time.Time), sender, clock.NewMock()) + ruleStore.PutRule(context.Background(), rule) + sch.schedulableAlertRules.set([]*models.AlertRule{rule}, map[models.FolderKey]string{rule.GetFolderKey(): folderTitle}) + + states := []*state.State{ + { + AlertRuleUID: rule.UID, + CacheID: data.Labels(rule.Labels).Fingerprint(), + OrgID: rule.OrgID, + State: eval.Alerting, + StartsAt: sch.clock.Now(), + EndsAt: sch.clock.Now().Add(5 * time.Second), + Labels: rule.Labels, + }, + } + sch.stateManager.Put(states) + require.NotEmpty(t, sch.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID)) + + factory := ruleFactoryFromScheduler(sch) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: folderTitle}) + + go func() { + _ = ruleInfo.Run() + }() + + ruleInfo.Eval(&Evaluation{ + scheduledAt: sch.clock.Now(), + rule: rule, + folderTitle: folderTitle, + }) + + require.Eventually(t, func() bool { + return len(sender.Calls()) > 0 + }, 5*time.Second, 100*time.Millisecond) + + actualStates := sch.stateManager.GetStatesForRuleUID(rule.OrgID, rule.UID) + require.Empty(t, actualStates) + }) + t.Run("when evaluation fails", func(t *testing.T) { rule := gen.With(withQueryForState(t, eval.Error)).GenerateRef() rule.ExecErrState = models.ErrorErrState @@ -910,7 +1052,7 @@ func TestRuleRoutine(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: ""}) go func() { _ = ruleInfo.Run() @@ -1044,7 +1186,7 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: ""}) go func() { _ = ruleInfo.Run() @@ -1078,7 +1220,7 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: ""}) go func() { _ = ruleInfo.Run() @@ -1119,7 +1261,7 @@ func TestRuleRoutine(t *testing.T) { factory := ruleFactoryFromScheduler(sch) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: ""}) go func() { _ = ruleInfo.Run() @@ -1214,7 +1356,7 @@ func TestAlertRuleRetry(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - ruleInfo := factory.new(ctx, rule) + ruleInfo := factory.new(ctx, ruleWithFolder{rule: rule, folderTitle: ""}) go func() { _ = ruleInfo.Run() diff --git a/pkg/services/ngalert/schedule/metrics.go b/pkg/services/ngalert/schedule/metrics.go index e3281c33710..f4630b39cad 100644 --- a/pkg/services/ngalert/schedule/metrics.go +++ b/pkg/services/ngalert/schedule/metrics.go @@ -117,7 +117,7 @@ func (sch *schedule) updateRulesMetrics(alertRules []*models.AlertRule) { // Set metrics for key, count := range buckets { - sch.metrics.GroupRules.WithLabelValues(fmt.Sprint(key.orgID), key.ruleType.String(), key.state, makeRuleGroupLabelValue(key.ruleGroup)).Set(float64(count)) + sch.metrics.GroupRules.WithLabelValues(fmt.Sprint(key.orgID), key.ruleType.String(), key.state, makeRuleGroupLabelValue(key.ruleGroup), key.ruleGroup.NamespaceUID).Set(float64(count)) } for orgID, numRulesNfSettings := range orgsNfSettings { sch.metrics.SimpleNotificationRules.WithLabelValues(fmt.Sprint(orgID)).Set(float64(numRulesNfSettings)) diff --git a/pkg/services/ngalert/schedule/recording_rule_test.go b/pkg/services/ngalert/schedule/recording_rule_test.go index e8a61979d19..da25c38a2df 100644 --- a/pkg/services/ngalert/schedule/recording_rule_test.go +++ b/pkg/services/ngalert/schedule/recording_rule_test.go @@ -239,7 +239,7 @@ func TestRecordingRuleAfterEval(t *testing.T) { ruleStore.PutRule(context.Background(), rule) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) evalDoneChan := make(chan time.Time, 1) // Buffer to avoid blocking afterEvalCh := make(chan struct{}, 1) // Buffer to avoid blocking @@ -444,7 +444,7 @@ func testRecordingRule_Integration(t *testing.T, writeTarget *writer.TestRemoteW folderTitle := ruleStore.getNamespaceTitle(rule.NamespaceUID) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) evalDoneChan := make(chan time.Time) process.(*recordingRule).evalAppliedHook = func(_ models.AlertRuleKey, t time.Time) { evalDoneChan <- t @@ -583,7 +583,7 @@ func testRecordingRule_Integration(t *testing.T, writeTarget *writer.TestRemoteW folderTitle := ruleStore.getNamespaceTitle(rule.NamespaceUID) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) evalDoneChan := make(chan time.Time) process.(*recordingRule).evalAppliedHook = func(_ models.AlertRuleKey, t time.Time) { evalDoneChan <- t @@ -728,7 +728,7 @@ func testRecordingRule_Integration(t *testing.T, writeTarget *writer.TestRemoteW folderTitle := ruleStore.getNamespaceTitle(rule.NamespaceUID) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) evalDoneChan := make(chan time.Time) process.(*recordingRule).evalAppliedHook = func(_ models.AlertRuleKey, t time.Time) { evalDoneChan <- t @@ -787,7 +787,7 @@ func testRecordingRule_Integration(t *testing.T, writeTarget *writer.TestRemoteW folderTitle := ruleStore.getNamespaceTitle(rule.NamespaceUID) ruleFactory := ruleFactoryFromScheduler(sch) - process := ruleFactory.new(context.Background(), rule) + process := ruleFactory.new(context.Background(), ruleWithFolder{rule: rule, folderTitle: ""}) evalDoneChan := make(chan time.Time) process.(*recordingRule).evalAppliedHook = func(_ models.AlertRuleKey, t time.Time) { evalDoneChan <- t diff --git a/pkg/services/ngalert/schedule/registry.go b/pkg/services/ngalert/schedule/registry.go index ede71c94d75..892e0af8235 100644 --- a/pkg/services/ngalert/schedule/registry.go +++ b/pkg/services/ngalert/schedule/registry.go @@ -21,7 +21,7 @@ var ( ) type ruleFactory interface { - new(context.Context, *models.AlertRule) Rule + new(context.Context, ruleWithFolder) Rule } type ruleRegistry struct { @@ -35,14 +35,14 @@ func newRuleRegistry() ruleRegistry { // getOrCreate gets a rule routine from registry for the provided rule. If it does not exist, it creates a new one. // Returns a pointer to the rule routine and a flag that indicates whether it is a new struct or not. -func (r *ruleRegistry) getOrCreate(context context.Context, item *models.AlertRule, factory ruleFactory) (Rule, bool) { +func (r *ruleRegistry) getOrCreate(context context.Context, rf ruleWithFolder, factory ruleFactory) (Rule, bool) { r.mu.Lock() defer r.mu.Unlock() - key := item.GetKey() + key := rf.rule.GetKey() rule, ok := r.rules[key] if !ok { - rule = factory.new(context, item) + rule = factory.new(context, rf) r.rules[key] = rule } return rule, !ok diff --git a/pkg/services/ngalert/schedule/schedule.go b/pkg/services/ngalert/schedule/schedule.go index 44dced0cdea..ba12fe33461 100644 --- a/pkg/services/ngalert/schedule/schedule.go +++ b/pkg/services/ngalert/schedule/schedule.go @@ -320,10 +320,22 @@ func (sch *schedule) processTick(ctx context.Context, dispatcherGroup *errgroup. sch.stopAppliedFunc, ) for _, item := range alertRules { - ruleRoutine, newRoutine := sch.registry.getOrCreate(ctx, item, ruleFactory) key := item.GetKey() logger := sch.log.FromContext(ctx).New(key.LogContext()...) + var folderTitle string + if !sch.disableGrafanaFolder { + title, ok := folderTitles[item.GetFolderKey()] + if ok { + folderTitle = title + } else { + missingFolder[item.NamespaceUID] = append(missingFolder[item.NamespaceUID], item.UID) + } + } + + rf := ruleWithFolder{rule: item, folderTitle: folderTitle} + ruleRoutine, newRoutine := sch.registry.getOrCreate(ctx, rf, ruleFactory) + // enforce minimum evaluation interval if item.IntervalSeconds < int64(sch.minRuleInterval.Seconds()) { logger.Debug("Interval adjusted", "originalInterval", item.IntervalSeconds, "adjustedInterval", sch.minRuleInterval.Seconds()) @@ -337,7 +349,7 @@ func (sch *schedule) processTick(ctx context.Context, dispatcherGroup *errgroup. logger.Debug("Rule restarted because type changed", "old", ruleRoutine.Type(), "new", item.Type()) restartedRules = append(restartedRules, ruleRoutine) sch.registry.del(key) - ruleRoutine, newRoutine = sch.registry.getOrCreate(ctx, item, ruleFactory) + ruleRoutine, newRoutine = sch.registry.getOrCreate(ctx, rf, ruleFactory) } if newRoutine && !invalidInterval { @@ -357,16 +369,6 @@ func (sch *schedule) processTick(ctx context.Context, dispatcherGroup *errgroup. offset := jitterOffsetInTicks(item, sch.baseInterval, sch.jitterEvaluations) isReadyToRun := item.IntervalSeconds != 0 && (tickNum%itemFrequency)-offset == 0 - var folderTitle string - if !sch.disableGrafanaFolder { - title, ok := folderTitles[item.GetFolderKey()] - if ok { - folderTitle = title - } else { - missingFolder[item.NamespaceUID] = append(missingFolder[item.NamespaceUID], item.UID) - } - } - if isReadyToRun { logger.Debug("Rule is ready to run on the current tick", "tick", tick, "frequency", itemFrequency, "offset", offset) readyToRun = append(readyToRun, readyToRunItem{ruleRoutine: ruleRoutine, Evaluation: Evaluation{ @@ -378,12 +380,12 @@ func (sch *schedule) processTick(ctx context.Context, dispatcherGroup *errgroup. if _, isUpdated := updated[key]; isUpdated && !isReadyToRun { // if we do not need to eval the rule, check the whether rule was just updated and if it was, notify evaluation routine about that logger.Debug("Rule has been updated. Notifying evaluation routine") - go func(routine Rule, rule *ngmodels.AlertRule) { + go func(routine Rule, rule *ngmodels.AlertRule, folder string) { routine.Update(&Evaluation{ rule: rule, - folderTitle: folderTitle, + folderTitle: folder, }) - }(ruleRoutine, item) + }(ruleRoutine, item, folderTitle) updatedRules = append(updatedRules, ngmodels.AlertRuleKeyWithVersion{ Version: item.Version, AlertRuleKey: item.GetKey(), diff --git a/pkg/services/ngalert/schedule/schedule_unit_test.go b/pkg/services/ngalert/schedule/schedule_unit_test.go index c90c9b19707..bbfa20fceb1 100644 --- a/pkg/services/ngalert/schedule/schedule_unit_test.go +++ b/pkg/services/ngalert/schedule/schedule_unit_test.go @@ -157,8 +157,8 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1) + grafana_alerting_rule_group_rules{folder_uid="%[3]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, alertRule1.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -199,9 +199,9 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -265,9 +265,9 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="paused",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="paused",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -308,10 +308,10 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="paused",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="paused",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="paused",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="paused",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) }) @@ -336,9 +336,9 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -363,8 +363,8 @@ func TestProcessTicks(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[3]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup2, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) }) @@ -684,8 +684,8 @@ func TestSchedule_updateRulesMetrics(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active", type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1) + grafana_alerting_rule_group_rules{folder_uid="%[3]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, alertRule1.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -705,9 +705,9 @@ func TestSchedule_updateRulesMetrics(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -720,9 +720,9 @@ func TestSchedule_updateRulesMetrics(t *testing.T) { expectedMetric := fmt.Sprintf( `# HELP grafana_alerting_rule_group_rules The number of alert rules that are scheduled, by type and state. # TYPE grafana_alerting_rule_group_rules gauge - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 - grafana_alerting_rule_group_rules{org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 - `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2) + grafana_alerting_rule_group_rules{folder_uid="%[4]s",org="%[1]d",rule_group="%[2]s",state="active",type="alerting"} 1 + grafana_alerting_rule_group_rules{folder_uid="%[5]s",org="%[1]d",rule_group="%[3]s",state="active",type="alerting"} 1 + `, alertRule1.OrgID, folderWithRuleGroup1, folderWithRuleGroup2, alertRule1.NamespaceUID, alertRule2.NamespaceUID) err := testutil.GatherAndCompare(reg, bytes.NewBufferString(expectedMetric), "grafana_alerting_rule_group_rules") require.NoError(t, err) @@ -1107,7 +1107,7 @@ func TestSchedule_deleteAlertRule(t *testing.T) { rule := models.RuleGen.GenerateRef() ruleStore.PutRule(ctx, rule) key := rule.GetKey() - info, _ := sch.registry.getOrCreate(ctx, rule, ruleFactory) + info, _ := sch.registry.getOrCreate(ctx, ruleWithFolder{rule: rule, folderTitle: ""}, ruleFactory) sch.deleteAlertRule(ctx, key) @@ -1126,7 +1126,7 @@ func TestSchedule_deleteAlertRule(t *testing.T) { rule := models.RuleGen.GenerateRef() ruleStore.PutRule(ctx, rule) key := rule.GetKey() - info, _ := sch.registry.getOrCreate(ctx, rule, ruleFactory) + info, _ := sch.registry.getOrCreate(ctx, ruleWithFolder{rule: rule, folderTitle: ""}, ruleFactory) _, err := sch.updateSchedulableAlertRules(ctx) require.NoError(t, err) @@ -1149,7 +1149,7 @@ func TestSchedule_deleteAlertRule(t *testing.T) { rule := models.RuleGen.GenerateRef() ruleStore.PutRule(ctx, rule) key := rule.GetKey() - info, _ := sch.registry.getOrCreate(ctx, rule, ruleFactory) + info, _ := sch.registry.getOrCreate(ctx, ruleWithFolder{rule: rule, folderTitle: ""}, ruleFactory) _, err := sch.updateSchedulableAlertRules(ctx) require.NoError(t, err) @@ -1172,7 +1172,7 @@ func TestSchedule_deleteAlertRule(t *testing.T) { ruleFactory := ruleFactoryFromScheduler(sch) rule := models.RuleGen.GenerateRef() key := rule.GetKey() - info, _ := sch.registry.getOrCreate(ctx, rule, ruleFactory) + info, _ := sch.registry.getOrCreate(ctx, ruleWithFolder{rule: rule, folderTitle: ""}, ruleFactory) _, err := sch.updateSchedulableAlertRules(ctx) require.NoError(t, err) diff --git a/pkg/services/ngalert/state/historian/annotation.go b/pkg/services/ngalert/state/historian/annotation.go index d2353ec42d8..d9cdfaa9d2b 100644 --- a/pkg/services/ngalert/state/historian/annotation.go +++ b/pkg/services/ngalert/state/historian/annotation.go @@ -44,6 +44,7 @@ type AnnotationBackend struct { type RuleStore interface { GetAlertRuleByUID(ctx context.Context, query *ngmodels.GetAlertRuleByUIDQuery) (*ngmodels.AlertRule, error) GetUserVisibleNamespaces(ctx context.Context, orgID int64, user identity.Requester) (map[string]*folder.Folder, error) + GetAlertRuleVersionFolders(ctx context.Context, orgID int64, guid string) ([]string, error) } type AnnotationStore interface { diff --git a/pkg/services/ngalert/state/historian/loki.go b/pkg/services/ngalert/state/historian/loki.go index 137c18f031c..76e3e9025bd 100644 --- a/pkg/services/ngalert/state/historian/loki.go +++ b/pkg/services/ngalert/state/historian/loki.go @@ -505,32 +505,27 @@ func (h *RemoteLokiBackend) getFolderUIDsForFilter(ctx context.Context, query mo if err != nil { return nil, err } - if bypass { // if user has access to all rules and folder, remove filter + + if query.RuleUID != "" { + return h.getFolderUIDsForRuleFilter(ctx, query, bypass) + } + + // If the query has no rule filter, we need to return all folder UIDs the user has access to. + // For a user with access to all rules and folders, the full list of folders will likely be too large to be an + // effective optimization in Loki, so we skip folderUID filtering entirely in that case. + if bypass { return nil, nil } - // if there is a filter by rule UID, find that rule UID and make sure that user has access to it. - if query.RuleUID != "" { - rule, err := h.ruleStore.GetAlertRuleByUID(ctx, &models.GetAlertRuleByUIDQuery{ - UID: query.RuleUID, - OrgID: query.OrgID, - }) - if err != nil { - return nil, fmt.Errorf("failed to fetch alert rule by UID: %w", err) - } - if rule == nil { - return nil, models.ErrAlertRuleNotFound - } - return nil, h.ac.AuthorizeAccessInFolder(ctx, query.SignedInUser, rule) - } - // if no filter, then we need to get all namespaces user has access to + + // All folders the user has access to. folders, err := h.ruleStore.GetUserVisibleNamespaces(ctx, query.OrgID, query.SignedInUser) if err != nil { return nil, fmt.Errorf("failed to fetch folders that user can access: %w", err) } uids := make([]string, 0, len(folders)) - // now keep only UIDs of folder in which user can read rules. + // Keep only UIDs of folder in which user can read rules. for _, f := range folders { - hasAccess, err := h.ac.HasAccessInFolder(ctx, query.SignedInUser, models.Namespace(*f.ToFolderReference())) + hasAccess, err := h.ac.HasAccessInFolder(ctx, query.SignedInUser, models.NewNamespace(f)) if err != nil { return nil, err } @@ -545,3 +540,71 @@ func (h *RemoteLokiBackend) getFolderUIDsForFilter(ctx context.Context, query mo sort.Strings(uids) return uids, nil } + +func (h *RemoteLokiBackend) getFolderUIDsForRuleFilter(ctx context.Context, query models.HistoryQuery, canReadAll bool) ([]string, error) { + rule, err := h.ruleStore.GetAlertRuleByUID(ctx, &models.GetAlertRuleByUIDQuery{ + UID: query.RuleUID, + OrgID: query.OrgID, + }) + if err != nil { + if canReadAll { + // When the user can read all rules, filtering by folder UID is purely an optimization, so we can ignore errors here. + h.log.FromContext(ctx).Debug("failed to fetch alert rule by UID", "err", err) + return nil, nil + } + return nil, fmt.Errorf("failed to fetch alert rule by UID: %w", err) + } + + // First, we check if the user has access to the current version of the rule. If not, we can return early. + // Whether we should check historical folders they might still have access to is not 100% clear, but it seems more + // intuitive to deny access in this case. + if !canReadAll { + if err := h.ac.AuthorizeAccessInFolder(ctx, query.SignedInUser, rule); err != nil { + return nil, err + } + } + + // We want to return folder UIDs when possible, as it's indexed in Loki and will help with query performance. + // However, by just returning the current folder UID the user can lose history when a rule is moved between folders. + // So, we attempt to get historical folder UIDs from the rule's history. + historicalFolders, err := h.ruleStore.GetAlertRuleVersionFolders(ctx, rule.OrgID, rule.GUID) + if err != nil { + // Including historical folders is an edge case enhancement, better to just log the error and continue + // with the current folder UID. + h.log.FromContext(ctx).Debug("failed to include historical folder UIDs for rule", "err", err) + } + + accessibleFolders := make([]string, 0, len(historicalFolders)+1) + dedup := make(map[string]struct{}) + + accessibleFolders = append(accessibleFolders, rule.GetNamespaceUID()) + dedup[rule.GetNamespaceUID()] = struct{}{} + + for _, folderUID := range historicalFolders { + if _, exists := dedup[folderUID]; exists { + continue + } + + if canReadAll { + // If the user can read all rules, no need to check access to each folder. + accessibleFolders = append(accessibleFolders, folderUID) + continue + } + + hasAccess, err := h.ac.HasAccessInFolder(ctx, query.SignedInUser, models.Namespace{ + UID: folderUID, + }) + if err != nil { + // Including historical folders is an edge case enhancement, better to just log the error and continue + // with the current folder UID. + h.log.FromContext(ctx).Debug("failed to check access to folder", "err", err, "folderUID", folderUID) + continue + } + if !hasAccess { + continue + } + accessibleFolders = append(accessibleFolders, folderUID) + } + + return accessibleFolders, nil +} diff --git a/pkg/services/ngalert/state/historian/loki_test.go b/pkg/services/ngalert/state/historian/loki_test.go index a01efe9563b..d5cd482d177 100644 --- a/pkg/services/ngalert/state/historian/loki_test.go +++ b/pkg/services/ngalert/state/historian/loki_test.go @@ -22,6 +22,7 @@ import ( alertingInstrument "github.com/grafana/alerting/http/instrument" "github.com/grafana/alerting/http/instrument/instrumenttest" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/tracing" @@ -868,7 +869,8 @@ func TestGetFolderUIDsForFilter(t *testing.T) { } result, err := createLoki(ac).getFolderUIDsForFilter(context.Background(), models.HistoryQuery{OrgID: orgID, RuleUID: rule.UID, SignedInUser: usr}) assert.NoError(t, err) - assert.Empty(t, result) + assert.Len(t, result, 1) + assert.Contains(t, result, rule.GetNamespaceUID()) assert.Len(t, ac.Calls, 1) assert.Equal(t, "CanReadAllRules", ac.Calls[0].MethodName) @@ -893,7 +895,8 @@ func TestGetFolderUIDsForFilter(t *testing.T) { result, err := loki.getFolderUIDsForFilter(context.Background(), models.HistoryQuery{OrgID: orgID, RuleUID: rule.UID, SignedInUser: usr}) assert.NoError(t, err) - assert.Empty(t, result) + assert.Len(t, result, 1) + assert.Contains(t, result, rule.GetNamespaceUID()) assert.Len(t, ac.Calls, 2) assert.Equal(t, "CanReadAllRules", ac.Calls[0].MethodName) @@ -916,6 +919,21 @@ func TestGetFolderUIDsForFilter(t *testing.T) { require.ErrorIs(t, err, models.ErrAlertRuleNotFound) }) }) + + t.Run("should return folderUID", func(t *testing.T) { + for _, authBypass := range []bool{true, false} { + t.Run(fmt.Sprintf("authBypass=%v", authBypass), func(t *testing.T) { + ac := &acfakes.FakeRuleService{} + ac.CanReadAllRulesFunc = func(ctx context.Context, requester identity.Requester) (bool, error) { + return authBypass, nil + } + result, err := createLoki(ac).getFolderUIDsForFilter(context.Background(), models.HistoryQuery{OrgID: orgID, RuleUID: rule.UID, SignedInUser: usr}) + assert.NoError(t, err) + assert.Len(t, result, 1) + assert.Contains(t, result, rule.GetNamespaceUID()) + }) + } + }) }) t.Run("when rule UID is empty", func(t *testing.T) { @@ -982,6 +1000,161 @@ func TestGetFolderUIDsForFilter(t *testing.T) { }) } +func TestGetFolderUIDsForFilterWithHistoricalFolders(t *testing.T) { + // Simple history generator to avoid repetitive code in test cases. + simpleHistory := func(guid string) map[string][]*models.AlertRuleVersion { + return map[string][]*models.AlertRuleVersion{ + guid: { + &models.AlertRuleVersion{AlertRule: models.RuleGen.With(models.RuleMuts.WithGUID(guid), models.RuleMuts.WithNamespaceUID("folder-current")).Generate()}, + &models.AlertRuleVersion{AlertRule: models.RuleGen.With(models.RuleMuts.WithGUID(guid), models.RuleMuts.WithNamespaceUID("folder-historical-1")).Generate()}, + &models.AlertRuleVersion{AlertRule: models.RuleGen.With(models.RuleMuts.WithGUID(guid), models.RuleMuts.WithNamespaceUID("folder-historical-2")).Generate()}, + &models.AlertRuleVersion{AlertRule: models.RuleGen.With(models.RuleMuts.WithGUID(guid), models.RuleMuts.WithNamespaceUID("folder-historical-3")).Generate()}, + }, + } + } + + // Helper to create simple folder access override functions. + canReadRulesInFolders := func(folderUids ...string) func(folderUID string) (bool, error) { + return func(folderUID string) (bool, error) { + for _, f := range folderUids { + if folderUID == f { + return true, nil + } + } + return false, nil + } + } + + // Helper to fail historical folders query. + failHistoryQueryHook := func(cmd any) error { + q, ok := cmd.(fakes.GenericRecordedQuery) + if !ok { + return nil + } + if q.Name == "GetAlertRuleVersionFolders" { + return errors.New("generic error") + } + return nil + } + + cases := []struct { + name string + // Setup. + existingHistory map[string][]*models.AlertRuleVersion + canReadAllRules bool + rule *models.AlertRule + + // Error overrides. + ruleStoreHook func(cmd any) error + folderAccessOverride func(folderUID string) (bool, error) + + // Expected. + expectedFolders []string + }{ + { + name: "should include historical folders when user can read all rules", + existingHistory: simpleHistory("guid-1"), + canReadAllRules: true, + rule: models.RuleGen.With(models.RuleMuts.WithGUID("guid-1"), models.RuleMuts.WithNamespaceUID("folder-current")).GenerateRef(), + expectedFolders: []string{"folder-current", "folder-historical-1", "folder-historical-2", "folder-historical-3"}, + }, + { + name: "should include only authorized historical folders", + existingHistory: simpleHistory("guid-1"), + folderAccessOverride: canReadRulesInFolders("folder-current", "folder-historical-2"), + rule: models.RuleGen.With(models.RuleMuts.WithGUID("guid-1"), models.RuleMuts.WithNamespaceUID("folder-current")).GenerateRef(), + expectedFolders: []string{"folder-current", "folder-historical-2"}, + }, + { + name: "if historical folders query fails, should return current folder", + existingHistory: simpleHistory("guid-1"), + canReadAllRules: true, + rule: models.RuleGen.With(models.RuleMuts.WithGUID("guid-1"), models.RuleMuts.WithNamespaceUID("folder-current")).GenerateRef(), + ruleStoreHook: failHistoryQueryHook, + expectedFolders: []string{"folder-current"}, + }, + { + name: "if historical folders query fails, should return current folder", + existingHistory: simpleHistory("guid-1"), + folderAccessOverride: canReadRulesInFolders("folder-current", "folder-historical-2"), + rule: models.RuleGen.With(models.RuleMuts.WithGUID("guid-1"), models.RuleMuts.WithNamespaceUID("folder-current")).GenerateRef(), + ruleStoreHook: failHistoryQueryHook, + expectedFolders: []string{"folder-current"}, + }, + { + name: "if access check for historical folders fails, should ignore", + existingHistory: simpleHistory("guid-1"), + rule: models.RuleGen.With(models.RuleMuts.WithGUID("guid-1"), models.RuleMuts.WithNamespaceUID("folder-current")).GenerateRef(), + folderAccessOverride: func(folderUID string) (bool, error) { + switch folderUID { + case "folder-current", "folder-historical-3": + return true, nil + case "folder-historical-2": + return false, nil + case "folder-historical-1": + return false, errors.New("generic error") + } + return false, nil + }, + expectedFolders: []string{"folder-current", "folder-historical-3"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Setup. + orgID := int64(1) + usr := accesscontrol.BackgroundUser("test", 1, org.RoleNone, nil) + + ac := &acfakes.FakeRuleService{} + ac.CanReadAllRulesFunc = func(ctx context.Context, requester identity.Requester) (bool, error) { + return tc.canReadAllRules, nil + } + ac.AuthorizeAccessInFolderFunc = func(ctx context.Context, requester identity.Requester, namespaced models.Namespaced) error { + if tc.canReadAllRules { + return nil + } + hasAccess, err := tc.folderAccessOverride(namespaced.GetNamespaceUID()) + if err != nil { + return err + } + if !hasAccess { + return rulesAuthz.ErrAuthorizationBase.Errorf("%w", err) + } + return nil + } + ac.HasAccessInFolderFunc = func(ctx context.Context, requester identity.Requester, namespaced models.Namespaced) (bool, error) { + if tc.canReadAllRules { + return true, nil + } + return tc.folderAccessOverride(namespaced.GetNamespaceUID()) + } + + rulesStore := fakes.NewRuleStore(t) + rulesStore.Rules = map[int64][]*models.AlertRule{ + orgID: { + tc.rule, + // Add some irrelevant rules to ensure they are ignored. + models.RuleGen.With(models.RuleMuts.WithNamespaceUID(tc.rule.GetNamespaceUID())).GenerateRef(), + models.RuleGen.With(models.RuleMuts.WithNamespaceUID("irrelevant-folder")).GenerateRef(), + }, + } + rulesStore.History = tc.existingHistory + if tc.ruleStoreHook != nil { + rulesStore.Hook = tc.ruleStoreHook + } + + loki := createTestLokiBackend(t, instrumenttest.NewFakeRequester(), metrics.NewHistorianMetrics(prometheus.NewRegistry(), metrics.Subsystem)) + loki.ruleStore = rulesStore + loki.ac = ac + + // Test conditions. + result, err := loki.getFolderUIDsForFilter(context.Background(), models.HistoryQuery{OrgID: orgID, RuleUID: tc.rule.UID, SignedInUser: usr}) + assert.NoError(t, err) + assert.ElementsMatch(t, tc.expectedFolders, result) + }) + } +} + func createTestLokiBackend(t *testing.T, req alertingInstrument.Requester, met *metrics.Historian) *RemoteLokiBackend { url, _ := url.Parse("http://some.url") cfg := lokiclient.LokiConfig{ diff --git a/pkg/services/ngalert/store/alert_rule.go b/pkg/services/ngalert/store/alert_rule.go index 285a24d0b81..5957e7026b2 100644 --- a/pkg/services/ngalert/store/alert_rule.go +++ b/pkg/services/ngalert/store/alert_rule.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/google/uuid" + "github.com/prometheus/alertmanager/pkg/labels" "golang.org/x/exp/maps" "github.com/grafana/grafana/pkg/util/xorm" @@ -238,6 +239,27 @@ func (st DBstore) GetAlertRuleVersions(ctx context.Context, orgID int64, guid st return alertRules, nil } +// GetAlertRuleVersionFolders retrieves a list of unique folder UIDs that the given rule guid has belonged to. +// Returned slice is ordered with more recent folders first. +func (st DBstore) GetAlertRuleVersionFolders(ctx context.Context, orgID int64, guid string) ([]string, error) { + folders := make([]string, 0) + err := st.SQLStore.WithDbSession(ctx, func(sess *db.Session) error { + if err := sess.Table(new(alertRuleVersion)). + Select("rule_namespace_uid"). + Where("rule_org_id = ? AND rule_guid = ?", orgID, guid). + GroupBy("rule_namespace_uid"). + OrderBy("MAX(version) DESC"). + Find(&folders); err != nil { + return err + } + return nil + }) + if err != nil { + return nil, err + } + return folders, nil +} + // ListDeletedRules retrieves a list of deleted alert rules for the specified organization ID from the database. // It ensures that only the latest version of each rule is included and filters out invalid or duplicated versions. // Returns a slice of *models.AlertRule or an error if the operation fails. @@ -631,7 +653,13 @@ func (st DBstore) ListAlertRulesByGroup(ctx context.Context, query *ngmodels.Lis continue } - converted, err := alertRuleToModelsAlertRule(*rule, st.Logger) + var converted ngmodels.AlertRule + if query.Compact { + converted, err = alertRuleToModelsAlertRuleCompact(*rule, st.Logger) + } else { + converted, err = alertRuleToModelsAlertRule(*rule, st.Logger) + } + if err != nil { st.Logger.Error("Invalid rule found in DB store, cannot convert, ignoring it", "func", "ListAlertRulesByGroup", "error", err) continue @@ -796,6 +824,15 @@ func (st DBstore) ListAlertRulesPaginated(ctx context.Context, query *ngmodels.L return result, nextToken, err } +func matchersMatchLabels(matchers labels.Matchers, lbls map[string]string) bool { + for _, m := range matchers { + if !m.Matches(lbls[m.Name]) { + return false + } + } + return true +} + // nolint:gocyclo func (st DBstore) buildListAlertRulesQuery(sess *db.Session, query *ngmodels.ListAlertRulesExtendedQuery) (q *xorm.Session, groupsSet map[string]struct{}, err error) { q = sess.Table("alert_rule") @@ -914,6 +951,13 @@ func (st DBstore) buildListAlertRulesQuery(sess *db.Session, query *ngmodels.Lis } } + if len(query.LabelMatchers) > 0 { + q, err = st.filterByLabelMatchers(query.LabelMatchers, q) + if err != nil { + return nil, groupsSet, err + } + } + // FIXME: record is nullable but we don't save it as null when it's nil switch query.RuleType { case ngmodels.RuleTypeFilterAlerting: @@ -961,6 +1005,11 @@ func (st DBstore) handleRuleRow(rows *xorm.Rows, query *ngmodels.ListAlertRulesE return nil, false } } + if len(query.LabelMatchers) > 0 { // remove false-positive hits from the result + if !matchersMatchLabels(query.LabelMatchers, converted.Labels) { + return nil, false + } + } // MySQL (and potentially other databases) can use case-insensitive comparison. // This code makes sure we return groups that only exactly match the filter. if groupsSet != nil { @@ -1349,6 +1398,23 @@ func (st DBstore) filterWithPrometheusRuleDefinition(value bool, sess *xorm.Sess ), nil } +// filterByLabelMatchers adds filtering for equality and inequality label matchers. +// Returns error if regex matchers are passed. +func (st DBstore) filterByLabelMatchers(matchers labels.Matchers, sess *xorm.Session) (*xorm.Session, error) { + for _, m := range matchers { + if m.Type != labels.MatchEqual && m.Type != labels.MatchNotEqual { + return nil, fmt.Errorf("matcher %q %s %q is not supported", m.Name, m.Type, m.Value) + } + + sql, args, err := buildLabelMatcherCondition(st.SQLStore.GetDialect(), "labels", m) + if err != nil { + return nil, err + } + sess = sess.And(sql, args...) + } + return sess, nil +} + func (st DBstore) RenameReceiverInNotificationSettings(ctx context.Context, orgID int64, oldReceiver, newReceiver string, validateProvenance func(ngmodels.Provenance) bool, dryRun bool) ([]ngmodels.AlertRuleKey, []ngmodels.AlertRuleKey, error) { // fetch entire rules because Update method requires it because it copies rules to version table rules, err := st.ListAlertRules(ctx, &ngmodels.ListAlertRulesQuery{ diff --git a/pkg/services/ngalert/store/alert_rule_labels.go b/pkg/services/ngalert/store/alert_rule_labels.go new file mode 100644 index 00000000000..721071d5219 --- /dev/null +++ b/pkg/services/ngalert/store/alert_rule_labels.go @@ -0,0 +1,51 @@ +package store + +import ( + "fmt" + + "github.com/prometheus/alertmanager/pkg/labels" + + "github.com/grafana/grafana/pkg/services/sqlstore/migrator" +) + +// buildLabelMatcherCondition builds SQL for a label matcher with Prometheus semantics. +// For MySQL/PostgreSQL, it uses JSON functions, and +// for SQLite, it uses GLOB patterns to find matching labels. +func buildLabelMatcherCondition(dialect migrator.Dialect, column string, m *labels.Matcher) (string, []any, error) { + if dialect.DriverName() == migrator.SQLite { + return buildLabelMatcherGlob(column, m) + } + return buildLabelMatcherJSON(dialect, column, m) +} + +func buildLabelMatcherGlob(column string, m *labels.Matcher) (string, []any, error) { + switch { + case m.Type == labels.MatchEqual && m.Value == "": + eqSQL, eqArgs, _ := globEquals(column, m.Name, "") + missingSQL, missingArgs, _ := globKeyMissing(column, m.Name) + return "(" + eqSQL + " OR " + missingSQL + ")", append(eqArgs, missingArgs...), nil + case m.Type == labels.MatchEqual: + return globEquals(column, m.Name, m.Value) + case m.Type == labels.MatchNotEqual: + return globNotEquals(column, m.Name, m.Value) + default: + return "", nil, fmt.Errorf("unsupported matcher type: %v", m.Type) + } +} + +func buildLabelMatcherJSON(dialect migrator.Dialect, column string, m *labels.Matcher) (string, []any, error) { + switch { + case m.Type == labels.MatchEqual && m.Value == "": + eqSQL, eqArgs := jsonEquals(dialect, column, m.Name, "") + missingSQL, missingArgs := jsonKeyMissing(dialect, column, m.Name) + return "(" + eqSQL + " OR " + missingSQL + ")", append(eqArgs, missingArgs...), nil + case m.Type == labels.MatchEqual: + sql, args := jsonEquals(dialect, column, m.Name, m.Value) + return sql, args, nil + case m.Type == labels.MatchNotEqual: + sql, args := jsonNotEquals(dialect, column, m.Name, m.Value) + return sql, args, nil + default: + return "", nil, fmt.Errorf("unsupported matcher type: %v", m.Type) + } +} diff --git a/pkg/services/ngalert/store/alert_rule_labels_test.go b/pkg/services/ngalert/store/alert_rule_labels_test.go new file mode 100644 index 00000000000..9b72d8f00f9 --- /dev/null +++ b/pkg/services/ngalert/store/alert_rule_labels_test.go @@ -0,0 +1,136 @@ +package store + +import ( + "testing" + + "github.com/prometheus/alertmanager/pkg/labels" + "github.com/stretchr/testify/require" + + "github.com/grafana/grafana/pkg/services/sqlstore/migrator" +) + +func TestBuildLabelMatcherGlob(t *testing.T) { + tests := []struct { + name string + matcher *labels.Matcher + wantSQL string + wantArgs []any + wantErr bool + errContains string + }{ + { + name: "MatchEqual with non-empty value", + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: "alerting"}, + wantSQL: "labels GLOB ?", + wantArgs: []any{`*"team":"alerting"*`}, + }, + { + name: "MatchEqual with empty value (Prometheus semantics)", + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: ""}, + wantSQL: `(labels GLOB ? OR labels NOT GLOB ?)`, + wantArgs: []any{`*"team":""*`, `*"team":*`}, + }, + { + name: "MatchNotEqual", + matcher: &labels.Matcher{Type: labels.MatchNotEqual, Name: "team", Value: "alerting"}, + wantSQL: "labels NOT GLOB ?", + wantArgs: []any{`*"team":"alerting"*`}, + }, + { + name: "unsupported matcher type", + matcher: &labels.Matcher{Type: labels.MatchRegexp, Name: "team", Value: "alert.*"}, + wantErr: true, + errContains: "unsupported matcher type", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sql, args, err := buildLabelMatcherGlob("labels", tt.matcher) + if tt.wantErr { + require.Error(t, err) + require.Contains(t, err.Error(), tt.errContains) + return + } + require.NoError(t, err) + require.Equal(t, tt.wantSQL, sql) + require.Equal(t, tt.wantArgs, args) + }) + } +} + +func TestBuildLabelMatcherJSON(t *testing.T) { + tests := []struct { + name string + dialect migrator.Dialect + matcher *labels.Matcher + wantSQL string + wantArgs []any + wantErr bool + errContains string + }{ + { + name: "MySQL MatchEqual with non-empty value", + dialect: migrator.NewMysqlDialect(), + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: "alerting"}, + wantSQL: "JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) = ?", + wantArgs: []any{"team", "alerting"}, + }, + { + name: "MySQL MatchEqual with empty value", + dialect: migrator.NewMysqlDialect(), + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: ""}, + wantSQL: "(JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) = ? OR JSON_EXTRACT(labels, CONCAT('$.', ?)) IS NULL)", + wantArgs: []any{"team", "", "team"}, + }, + { + name: "MySQL MatchNotEqual", + dialect: migrator.NewMysqlDialect(), + matcher: &labels.Matcher{Type: labels.MatchNotEqual, Name: "team", Value: "alerting"}, + wantSQL: "(JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) IS NULL OR JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) != ?)", + wantArgs: []any{"team", "team", "alerting"}, + }, + { + name: "PostgreSQL MatchEqual with non-empty value", + dialect: migrator.NewPostgresDialect(), + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: "alerting"}, + wantSQL: "jsonb_extract_path_text(labels::jsonb, ?) = ?", + wantArgs: []any{"team", "alerting"}, + }, + { + name: "PostgreSQL MatchEqual with empty value", + dialect: migrator.NewPostgresDialect(), + matcher: &labels.Matcher{Type: labels.MatchEqual, Name: "team", Value: ""}, + wantSQL: "(jsonb_extract_path_text(labels::jsonb, ?) = ? OR jsonb_extract_path_text(labels::jsonb, ?) IS NULL)", + wantArgs: []any{"team", "", "team"}, + }, + { + name: "PostgreSQL MatchNotEqual", + dialect: migrator.NewPostgresDialect(), + matcher: &labels.Matcher{Type: labels.MatchNotEqual, Name: "team", Value: "alerting"}, + wantSQL: "(jsonb_extract_path_text(labels::jsonb, ?) IS NULL OR jsonb_extract_path_text(labels::jsonb, ?) != ?)", + wantArgs: []any{"team", "team", "alerting"}, + }, + { + name: "unsupported matcher type", + dialect: migrator.NewMysqlDialect(), + matcher: &labels.Matcher{Type: labels.MatchRegexp, Name: "team", Value: "alert.*"}, + wantErr: true, + errContains: "unsupported matcher type", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sql, args, err := buildLabelMatcherJSON(tt.dialect, "labels", tt.matcher) + if tt.wantErr { + require.Error(t, err) + require.Contains(t, err.Error(), tt.errContains) + return + } + require.NoError(t, err) + require.Equal(t, tt.wantSQL, sql) + require.Equal(t, tt.wantArgs, args) + }) + } +} diff --git a/pkg/services/ngalert/store/alert_rule_test.go b/pkg/services/ngalert/store/alert_rule_test.go index 93f6f9e57a4..29b82f943ba 100644 --- a/pkg/services/ngalert/store/alert_rule_test.go +++ b/pkg/services/ngalert/store/alert_rule_test.go @@ -13,6 +13,7 @@ import ( "github.com/benbjohnson/clock" "github.com/google/uuid" + "github.com/prometheus/alertmanager/pkg/labels" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1726,6 +1727,55 @@ func TestIntegrationGetRuleVersions(t *testing.T) { }) } +func TestIntegrationGetAlertRuleVersionFolders(t *testing.T) { + tutil.SkipIntegrationTestInShortMode(t) + + // Setup. + cfg := setting.NewCfg() + cfg.UnifiedAlerting = setting.UnifiedAlertingSettings{BaseInterval: time.Duration(rand.Int64N(100)+1) * time.Second} + sqlStore := db.InitTestDB(t) + folderService := setupFolderService(t, sqlStore, cfg, featuremgmt.WithFeatures()) + b := &fakeBus{} + store := createTestStore(sqlStore, folderService, &logtest.Fake{}, cfg.UnifiedAlerting, b) + orgID := int64(1) + gen := models.RuleGen + gen = gen.With(gen.WithIntervalMatching(store.Cfg.BaseInterval), gen.WithOrgID(orgID), gen.WithVersion(1)) + + inserted, err := store.InsertAlertRules(context.Background(), &models.AlertingUserUID, []models.InsertRule{{AlertRule: gen.Generate()}}) + require.NoError(t, err) + ruleV1, err := store.GetAlertRuleByUID(context.Background(), &models.GetAlertRuleByUIDQuery{UID: inserted[0].UID}) + require.NoError(t, err) + + oldRule := ruleV1 + updatedRule := ruleV1 + updateRule := func(title string, folderUID string) { + oldRule = updatedRule + updatedRule = models.CopyRule(oldRule, gen.WithTitle(title), gen.WithNamespaceUID(folderUID)) + require.NoError(t, store.UpdateAlertRules(context.Background(), &models.AlertingUserUID, []models.UpdateRule{{Existing: oldRule, New: *updatedRule}})) + updatedRule.Version++ // Simulate version increment after update to avoid conflict errors. + } + + // Update rule a couple of times to create versions. + originalFolder := oldRule.NamespaceUID + updateRule(util.GenerateShortUID(), originalFolder) + updateRule(util.GenerateShortUID(), "newfolder-1") + updateRule(util.GenerateShortUID(), "newfolder-2") + updateRule(util.GenerateShortUID(), "newfolder-2") + updateRule(util.GenerateShortUID(), originalFolder) + updateRule(util.GenerateShortUID(), "current-folder") + + t.Run("should return rule versions folders sorted in decreasing order", func(t *testing.T) { + historicalFolders, err := store.GetAlertRuleVersionFolders(context.Background(), updatedRule.OrgID, updatedRule.GUID) + require.NoError(t, err) + assert.Equal(t, []string{ // Return folders with more recent first. + "current-folder", + originalFolder, + "newfolder-2", + "newfolder-1", + }, historicalFolders) + }) +} + // createAlertRule creates an alert rule in the database and returns it. // If a generator is not specified, uniqueness of primary key is not guaranteed. func createRule(tb testing.TB, store *DBstore, generator *models.AlertRuleGenerator) *models.AlertRule { @@ -2385,6 +2435,157 @@ func TestIntegration_ListAlertRules(t *testing.T) { }) } }) + + t.Run("filter by LabelMatchers", func(t *testing.T) { + sqlStore := db.InitTestDB(t) + folderService := setupFolderService(t, sqlStore, cfg, featuremgmt.WithFeatures()) + store := createTestStore(sqlStore, folderService, &logtest.Fake{}, cfg.UnifiedAlerting, b) + + ruleLower := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"team": "alerting", "severity": "warning"}), + ruleGen.WithTitle("rule_lowercase"))) + ruleUpper := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"team": "Alerting", "severity": "critical"}), + ruleGen.WithTitle("rule_uppercase"))) + ruleSpecial := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"key": `value"with"quotes`}), + ruleGen.WithTitle("rule_special"))) + ruleGlob := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"glob": "*[?]"}), + ruleGen.WithTitle("rule_glob"))) + ruleSpecialChars := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"json": "line1\nline2\\end\"quote"}), + ruleGen.WithTitle("rule_special_chars"))) + ruleEmpty := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"empty": ""}), + ruleGen.WithTitle("rule_empty"))) + ruleNonempty := createRule(t, store, ruleGen.With( + ruleGen.WithLabels(map[string]string{"empty": "nonempty"}), + ruleGen.WithTitle("rule_nonempty"))) + + tc := []struct { + name string + labelMatchers labels.Matchers + expectedRules []*models.AlertRule + }{ + { + name: "equality matcher is case-sensitive", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "team", "alerting"); return m }(), + }, + expectedRules: []*models.AlertRule{ruleLower}, + }, + { + name: "equality matcher matches uppercase when specified", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "team", "Alerting"); return m }(), + }, + expectedRules: []*models.AlertRule{ruleUpper}, + }, + { + name: "inequality matcher is case-sensitive", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchNotEqual, "team", "alerting"); return m }(), + }, + expectedRules: []*models.AlertRule{ruleUpper, ruleSpecial, ruleGlob, ruleSpecialChars, ruleEmpty, ruleNonempty}, + }, + { + name: "special characters in labels are handled correctly", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { + m, _ := labels.NewMatcher(labels.MatchEqual, "key", `value"with"quotes`) + return m + }(), + }, + expectedRules: []*models.AlertRule{ruleSpecial}, + }, + { + name: "matcher with non-existent label returns no rules", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "nonexistent", "value"); return m }(), + }, + expectedRules: []*models.AlertRule{}, + }, + { + name: "multiple matchers are ANDed", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "team", "Alerting"); return m }(), + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "severity", "critical"); return m }(), + }, + expectedRules: []*models.AlertRule{ruleUpper}, + }, + { + name: "GLOB special characters are escaped correctly", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "glob", "*[?]"); return m }(), + }, + expectedRules: []*models.AlertRule{ruleGlob}, + }, + { + name: "JSON escape characters are handled correctly", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { + m, _ := labels.NewMatcher(labels.MatchEqual, "json", "line1\nline2\\end\"quote") + return m + }(), + }, + expectedRules: []*models.AlertRule{ruleSpecialChars}, + }, + { + name: "empty string value matches correctly", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchEqual, "empty", ""); return m }(), + }, + expectedRules: []*models.AlertRule{ruleLower, ruleUpper, ruleSpecial, ruleGlob, ruleSpecialChars, ruleEmpty}, + }, + { + name: "inequality matcher on non-existent label matches all rules", + labelMatchers: labels.Matchers{ + func() *labels.Matcher { + m, _ := labels.NewMatcher(labels.MatchNotEqual, "nonexistent", "value") + return m + }(), + }, + expectedRules: []*models.AlertRule{ruleLower, ruleUpper, ruleSpecial, ruleGlob, ruleSpecialChars, ruleEmpty, ruleNonempty}, + }, + } + + for _, tt := range tc { + t.Run(tt.name, func(t *testing.T) { + query := &models.ListAlertRulesQuery{ + OrgID: orgID, + LabelMatchers: tt.labelMatchers, + } + result, err := store.ListAlertRules(context.Background(), query) + require.NoError(t, err) + require.ElementsMatch(t, tt.expectedRules, result) + }) + } + + t.Run("regex matcher returns error from store", func(t *testing.T) { + query := &models.ListAlertRulesQuery{ + OrgID: orgID, + LabelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchRegexp, "team", "alert.*"); return m }(), + }, + } + _, err := store.ListAlertRules(context.Background(), query) + require.Error(t, err) + require.ErrorContains(t, err, "is not supported") + }) + + t.Run("not-regex matcher returns error from store", func(t *testing.T) { + query := &models.ListAlertRulesQuery{ + OrgID: orgID, + LabelMatchers: labels.Matchers{ + func() *labels.Matcher { m, _ := labels.NewMatcher(labels.MatchNotRegexp, "team", "alert.*"); return m }(), + }, + } + _, err := store.ListAlertRules(context.Background(), query) + require.Error(t, err) + require.ErrorContains(t, err, "is not supported") + }) + }) } func TestIntegration_ListAlertRulesPaginated(t *testing.T) { diff --git a/pkg/services/ngalert/store/compat.go b/pkg/services/ngalert/store/compat.go index 4f4194facc1..fbb69addc72 100644 --- a/pkg/services/ngalert/store/compat.go +++ b/pkg/services/ngalert/store/compat.go @@ -10,11 +10,38 @@ import ( "github.com/grafana/grafana/pkg/services/ngalert/models" ) +// We only care about the data source UIDs. +type compactQuery struct { + DatasourceUID string `json:"datasourceUid"` +} + func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, error) { + return convertAlertRuleToModel(ar, l, false) +} + +// alertRuleToModelsAlertRuleCompact transforms an alertRule to a models.AlertRule +// ignoring alert queries (except for data source UIDs), notification settings, and metadata. +func alertRuleToModelsAlertRuleCompact(ar alertRule, l log.Logger) (models.AlertRule, error) { + return convertAlertRuleToModel(ar, l, true) +} + +// convertAlertRuleToModel creates a models.AlertRule from an alertRule. +// When 'compact' is set to 'true', it skips parsing the alert queries (except for the data source UID), notification +// settings, and metadata, thus reducing the number of JSON serializations needed. +func convertAlertRuleToModel(ar alertRule, l log.Logger, compact bool) (models.AlertRule, error) { var data []models.AlertQuery - err := json.Unmarshal([]byte(ar.Data), &data) - if err != nil { - return models.AlertRule{}, fmt.Errorf("failed to parse data: %w", err) + if compact { + var cqs []compactQuery + if err := json.Unmarshal([]byte(ar.Data), &cqs); err != nil { + return models.AlertRule{}, fmt.Errorf("failed to parse data: %w", err) + } + for _, cq := range cqs { + data = append(data, models.AlertQuery{DatasourceUID: cq.DatasourceUID}) + } + } else { + if err := json.Unmarshal([]byte(ar.Data), &data); err != nil { + return models.AlertRule{}, fmt.Errorf("failed to parse data: %w", err) + } } result := models.AlertRule{ @@ -52,6 +79,7 @@ func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, e result.UpdatedBy = util.Pointer(models.UserUID(*ar.UpdatedBy)) } + var err error if ar.NoDataState != "" { result.NoDataState, err = models.NoDataStateFromString(ar.NoDataState) if err != nil { @@ -90,7 +118,7 @@ func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, e } } - if ar.NotificationSettings != "" { + if !compact && ar.NotificationSettings != "" { ns, err := parseNotificationSettings(ar.NotificationSettings) if err != nil { return models.AlertRule{}, fmt.Errorf("failed to parse notification settings: %w", err) @@ -98,7 +126,7 @@ func alertRuleToModelsAlertRule(ar alertRule, l log.Logger) (models.AlertRule, e result.NotificationSettings = ns } - if ar.Metadata != "" { + if !compact && ar.Metadata != "" { err = json.Unmarshal([]byte(ar.Metadata), &result.Metadata) if err != nil { return models.AlertRule{}, fmt.Errorf("failed to metadata: %w", err) diff --git a/pkg/services/ngalert/store/compat_test.go b/pkg/services/ngalert/store/compat_test.go index 990ec5dd3e1..ef80f51d668 100644 --- a/pkg/services/ngalert/store/compat_test.go +++ b/pkg/services/ngalert/store/compat_test.go @@ -65,6 +65,85 @@ func TestAlertRuleToModelsAlertRule(t *testing.T) { }) } +func TestAlertRuleToModelsAlertRuleCompact(t *testing.T) { + t.Run("should only extract datasource UIDs in compact mode", func(t *testing.T) { + rule := alertRule{ + ID: 1, + OrgID: 1, + UID: "test-uid", + Title: "Test Rule", + Condition: "A", + Data: `[{"datasourceUid":"ds1","refId":"A","queryType":"test","model":{"expr":"up"}},{"datasourceUid":"ds2","refId":"B","queryType":"test","model":{"expr":"down"}}]`, + IntervalSeconds: 60, + Version: 1, + NamespaceUID: "ns-uid", + RuleGroup: "test-group", + NoDataState: "NoData", + ExecErrState: "Error", + NotificationSettings: `[{"receiver":"test-receiver"}]`, + Metadata: `{"editor_settings":{"simplified_query_and_expressions_section":true}}`, + } + + compactResult, err := alertRuleToModelsAlertRuleCompact(rule, &logtest.Fake{}) + require.NoError(t, err) + + // Should have datasource UIDs. + require.Len(t, compactResult.Data, 2) + require.Equal(t, "ds1", compactResult.Data[0].DatasourceUID) + require.Equal(t, "ds2", compactResult.Data[1].DatasourceUID) + + // But should not have full query data (RefID, QueryType, Model should be empty). + require.Empty(t, compactResult.Data[0].RefID) + require.Empty(t, compactResult.Data[0].QueryType) + require.Nil(t, compactResult.Data[0].Model) + require.Empty(t, compactResult.Data[1].RefID) + require.Empty(t, compactResult.Data[1].QueryType) + require.Nil(t, compactResult.Data[1].Model) + + // Should not have notification settings. + require.Empty(t, compactResult.NotificationSettings) + + // Should not have metadata (should be zero value). + require.Equal(t, ngmodels.AlertRuleMetadata{}, compactResult.Metadata) + }) + + t.Run("should parse full data in non-compact mode", func(t *testing.T) { + rule := alertRule{ + ID: 1, + OrgID: 1, + UID: "test-uid", + Title: "Test Rule", + Condition: "A", + Data: `[{"datasourceUid":"ds1","refId":"A","queryType":"test","model":{"expr":"up"}},{"datasourceUid":"ds2","refId":"B","queryType":"test","model":{"expr":"down"}}]`, + IntervalSeconds: 60, + Version: 1, + NamespaceUID: "ns-uid", + RuleGroup: "test-group", + NoDataState: "NoData", + ExecErrState: "Error", + NotificationSettings: `[{"receiver":"test-receiver"}]`, + Metadata: `{"editor_settings":{"simplified_query_and_expressions_section":true}}`, + } + + fullResult, err := alertRuleToModelsAlertRule(rule, &logtest.Fake{}) + require.NoError(t, err) + + // Should have full query data. + require.Len(t, fullResult.Data, 2) + require.Equal(t, "ds1", fullResult.Data[0].DatasourceUID) + require.Equal(t, "A", fullResult.Data[0].RefID) + require.Equal(t, "test", fullResult.Data[0].QueryType) + require.NotNil(t, fullResult.Data[0].Model) + + // Should have notification settings. + require.Len(t, fullResult.NotificationSettings, 1) + require.Equal(t, "test-receiver", fullResult.NotificationSettings[0].Receiver) + + // Should have metadata (metadata is parsed from JSON to struct). + require.NotEqual(t, ngmodels.AlertRuleMetadata{}, fullResult.Metadata) + }) +} + func TestAlertRuleVersionToAlertRule(t *testing.T) { g := ngmodels.RuleGen diff --git a/pkg/services/ngalert/store/instance_database.go b/pkg/services/ngalert/store/instance_database.go index a9d57d1ab8f..cc385ef4c63 100644 --- a/pkg/services/ngalert/store/instance_database.go +++ b/pkg/services/ngalert/store/instance_database.go @@ -364,10 +364,10 @@ func (st InstanceDBStore) insertInstancesBatch(sess *sqlstore.DBSession, batch [ query := strings.Builder{} placeholders := make([]string, 0, len(batch)) - args := make([]any, 0, len(batch)*13) + args := make([]any, 0, len(batch)*14) query.WriteString("INSERT INTO alert_instance ") - query.WriteString("(rule_org_id, rule_uid, labels, labels_hash, current_state, current_reason, current_state_since, current_state_end, last_eval_time, fired_at, resolved_at, last_sent_at, annotations) VALUES ") + query.WriteString("(rule_org_id, rule_uid, labels, labels_hash, current_state, current_reason, current_state_since, current_state_end, last_eval_time, fired_at, resolved_at, last_sent_at, result_fingerprint, annotations) VALUES ") for _, instance := range batch { if err := models.ValidateAlertInstance(instance); err != nil { @@ -387,7 +387,7 @@ func (st InstanceDBStore) insertInstancesBatch(sess *sqlstore.DBSession, batch [ continue } - placeholders = append(placeholders, "(?,?,?,?,?,?,?,?,?,?,?,?,?)") + placeholders = append(placeholders, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)") args = append(args, instance.RuleOrgID, instance.RuleUID, @@ -401,6 +401,7 @@ func (st InstanceDBStore) insertInstancesBatch(sess *sqlstore.DBSession, batch [ nullableTimeToUnix(instance.FiredAt), nullableTimeToUnix(instance.ResolvedAt), nullableTimeToUnix(instance.LastSentAt), + instance.ResultFingerprint, annotationsJSON, ) } diff --git a/pkg/services/ngalert/store/instance_database_test.go b/pkg/services/ngalert/store/instance_database_test.go index 3cf264d4a36..4f833d0fd17 100644 --- a/pkg/services/ngalert/store/instance_database_test.go +++ b/pkg/services/ngalert/store/instance_database_test.go @@ -8,6 +8,8 @@ import ( "time" "github.com/golang/snappy" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/grafana/grafana/pkg/util/testutil" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" @@ -391,27 +393,33 @@ func TestIntegrationFullSync(t *testing.T) { t.Run("Should save all instances when batch size is bigger than 1", func(t *testing.T) { batchSize = 2 - newRuleUID := "y" - err := ng.InstanceStore.FullSync(ctx, append(instances, *models.AlertInstanceGen(models.InstanceMuts.WithOrgID(orgID), models.InstanceMuts.WithRuleUID(newRuleUID))), batchSize, nil) + testInstances := []models.AlertInstance{ + *models.AlertInstanceGen(models.InstanceMuts.WithOrgID(orgID), models.InstanceMuts.WithRuleUID("batch1"), models.InstanceMuts.WithResultFingerprint("fp0")), + *models.AlertInstanceGen(models.InstanceMuts.WithOrgID(orgID), models.InstanceMuts.WithRuleUID("batch2"), models.InstanceMuts.WithResultFingerprint("fp1")), + *models.AlertInstanceGen(models.InstanceMuts.WithOrgID(orgID), models.InstanceMuts.WithRuleUID("batch3"), models.InstanceMuts.WithResultFingerprint("fp2")), + } + + err := ng.InstanceStore.FullSync(ctx, testInstances, batchSize, nil) require.NoError(t, err) res, err := ng.InstanceStore.ListAlertInstances(ctx, &models.ListAlertInstancesQuery{ RuleOrgID: orgID, }) require.NoError(t, err) - require.Len(t, res, len(instances)+1) - for _, ruleUID := range append(ruleUIDs, newRuleUID) { - found := false - for _, instance := range res { - if instance.RuleUID == ruleUID { - found = true - continue - } - } - if !found { - t.Errorf("Instance with RuleUID '%s' not found", ruleUID) - } + + savedInstances := make([]models.AlertInstance, len(res)) + for i, r := range res { + savedInstances[i] = *r } + + opts := []cmp.Option{ + cmpopts.EquateApproxTime(time.Second), // we don't get the same precision back from the DB + cmpopts.EquateEmpty(), + cmpopts.SortSlices(func(a, b models.AlertInstance) bool { + return a.RuleUID < b.RuleUID + }), + } + require.Empty(t, cmp.Diff(testInstances, savedInstances, opts...)) }) t.Run("Should not fail when the instances are empty", func(t *testing.T) { diff --git a/pkg/services/ngalert/store/json.go b/pkg/services/ngalert/store/json.go new file mode 100644 index 00000000000..7b634246951 --- /dev/null +++ b/pkg/services/ngalert/store/json.go @@ -0,0 +1,101 @@ +package store + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/grafana/grafana/pkg/services/sqlstore/migrator" +) + +// JSON functions for MySQL/PostgreSQL + +func jsonEquals(dialect migrator.Dialect, column, key, value string) (string, []any) { + switch dialect.DriverName() { + case migrator.MySQL: + return fmt.Sprintf("JSON_UNQUOTE(JSON_EXTRACT(%s, CONCAT('$.', ?))) = ?", column), []any{key, value} + case migrator.Postgres: + return fmt.Sprintf("jsonb_extract_path_text(%s::jsonb, ?) = ?", column), []any{key, value} + default: + return "", nil + } +} + +func jsonNotEquals(dialect migrator.Dialect, column, key, value string) (string, []any) { + var jx string + switch dialect.DriverName() { + case migrator.MySQL: + jx = fmt.Sprintf("JSON_UNQUOTE(JSON_EXTRACT(%s, CONCAT('$.', ?)))", column) + case migrator.Postgres: + jx = fmt.Sprintf("jsonb_extract_path_text(%s::jsonb, ?)", column) + default: + return "", nil + } + return fmt.Sprintf("(%s IS NULL OR %s != ?)", jx, jx), []any{key, key, value} +} + +func jsonKeyMissing(dialect migrator.Dialect, column, key string) (string, []any) { + switch dialect.DriverName() { + case migrator.MySQL: + return fmt.Sprintf("JSON_EXTRACT(%s, CONCAT('$.', ?)) IS NULL", column), []any{key} + case migrator.Postgres: + return fmt.Sprintf("jsonb_extract_path_text(%s::jsonb, ?) IS NULL", column), []any{key} + default: + return "", nil + } +} + +// GLOB functions for SQLite + +func globEquals(column, key, value string) (string, []any, error) { + pattern, err := buildGlobPattern(key, value) + if err != nil { + return "", nil, err + } + return column + " GLOB ?", []any{"*" + pattern + "*"}, nil +} + +func globNotEquals(column, key, value string) (string, []any, error) { + pattern, err := buildGlobPattern(key, value) + if err != nil { + return "", nil, err + } + return column + " NOT GLOB ?", []any{"*" + pattern + "*"}, nil +} + +func globKeyMissing(column, key string) (string, []any, error) { + pattern, err := buildGlobKeyPattern(key) + if err != nil { + return "", nil, err + } + return column + " NOT GLOB ?", []any{"*" + pattern + "*"}, nil +} + +// Search for `"key":"value"` +func buildGlobPattern(key, value string) (string, error) { + keyJSON, err := json.Marshal(key) + if err != nil { + return "", fmt.Errorf("failed to marshal key: %w", err) + } + valueJSON, err := json.Marshal(value) + if err != nil { + return "", fmt.Errorf("failed to marshal value: %w", err) + } + return escapeGlobPattern(fmt.Sprintf(`%s:%s`, string(keyJSON), string(valueJSON))), nil +} + +// Search for `"key":` +func buildGlobKeyPattern(key string) (string, error) { + keyJSON, err := json.Marshal(key) + if err != nil { + return "", fmt.Errorf("failed to marshal key: %w", err) + } + return escapeGlobPattern(string(keyJSON) + ":"), nil +} + +func escapeGlobPattern(pattern string) string { + pattern = strings.ReplaceAll(pattern, "[", "[[]") + pattern = strings.ReplaceAll(pattern, "*", "[*]") + pattern = strings.ReplaceAll(pattern, "?", "[?]") + return pattern +} diff --git a/pkg/services/ngalert/store/json_test.go b/pkg/services/ngalert/store/json_test.go new file mode 100644 index 00000000000..89f85a027a6 --- /dev/null +++ b/pkg/services/ngalert/store/json_test.go @@ -0,0 +1,185 @@ +package store + +import ( + "testing" + + "github.com/grafana/grafana/pkg/services/sqlstore/migrator" + "github.com/stretchr/testify/require" +) + +func TestJsonEquals(t *testing.T) { + tests := []struct { + name string + dialect migrator.Dialect + column string + key string + value string + wantSQL string + wantArgs []any + }{ + { + name: "MySQL", + dialect: migrator.NewMysqlDialect(), + column: "labels", + key: "team", + value: "alerting", + wantSQL: "JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) = ?", + wantArgs: []any{"team", "alerting"}, + }, + { + name: "PostgreSQL", + dialect: migrator.NewPostgresDialect(), + column: "labels", + key: "team", + value: "alerting", + wantSQL: "jsonb_extract_path_text(labels::jsonb, ?) = ?", + wantArgs: []any{"team", "alerting"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sql, args := jsonEquals(tt.dialect, tt.column, tt.key, tt.value) + require.Equal(t, tt.wantSQL, sql) + require.Equal(t, tt.wantArgs, args) + }) + } +} + +func TestJsonNotEquals(t *testing.T) { + tests := []struct { + name string + dialect migrator.Dialect + column string + key string + value string + wantSQL string + wantArgs []any + }{ + { + name: "MySQL", + dialect: migrator.NewMysqlDialect(), + column: "labels", + key: "team", + value: "alerting", + wantSQL: "(JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) IS NULL OR JSON_UNQUOTE(JSON_EXTRACT(labels, CONCAT('$.', ?))) != ?)", + wantArgs: []any{"team", "team", "alerting"}, + }, + { + name: "PostgreSQL", + dialect: migrator.NewPostgresDialect(), + column: "labels", + key: "team", + value: "alerting", + wantSQL: "(jsonb_extract_path_text(labels::jsonb, ?) IS NULL OR jsonb_extract_path_text(labels::jsonb, ?) != ?)", + wantArgs: []any{"team", "team", "alerting"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sql, args := jsonNotEquals(tt.dialect, tt.column, tt.key, tt.value) + require.Equal(t, tt.wantSQL, sql) + require.Equal(t, tt.wantArgs, args) + }) + } +} + +func TestJsonKeyMissing(t *testing.T) { + tests := []struct { + name string + dialect migrator.Dialect + column string + key string + wantSQL string + wantArgs []any + }{ + { + name: "MySQL", + dialect: migrator.NewMysqlDialect(), + column: "labels", + key: "team", + wantSQL: "JSON_EXTRACT(labels, CONCAT('$.', ?)) IS NULL", + wantArgs: []any{"team"}, + }, + { + name: "PostgreSQL", + dialect: migrator.NewPostgresDialect(), + column: "labels", + key: "team", + wantSQL: "jsonb_extract_path_text(labels::jsonb, ?) IS NULL", + wantArgs: []any{"team"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sql, args := jsonKeyMissing(tt.dialect, tt.column, tt.key) + require.Equal(t, tt.wantSQL, sql) + require.Equal(t, tt.wantArgs, args) + }) + } +} + +func TestGlobEquals(t *testing.T) { + sql, args, err := globEquals("labels", "team", "alerting") + require.NoError(t, err) + require.Equal(t, "labels GLOB ?", sql) + require.Equal(t, []any{`*"team":"alerting"*`}, args) +} + +func TestGlobNotEquals(t *testing.T) { + sql, args, err := globNotEquals("labels", "team", "alerting") + require.NoError(t, err) + require.Equal(t, "labels NOT GLOB ?", sql) + require.Equal(t, []any{`*"team":"alerting"*`}, args) +} + +func TestGlobKeyMissing(t *testing.T) { + sql, args, err := globKeyMissing("labels", "team") + require.NoError(t, err) + require.Equal(t, "labels NOT GLOB ?", sql) + require.Equal(t, []any{`*"team":*`}, args) +} + +func TestBuildGlobPattern(t *testing.T) { + tests := []struct { + name string + key string + value string + expected string + }{ + { + name: "simple key-value", + key: "team", + value: "alerting", + expected: `"team":"alerting"`, + }, + { + name: "empty value", + key: "empty", + value: "", + expected: `"empty":""`, + }, + { + name: "special GLOB chars are escaped", + key: "key", + value: "*[?]", + expected: `"key":"[*][[][?]]"`, + }, + { + name: "special chars are escaped", + key: "key", + value: "line1\nline2\\end\"quote", + expected: `"key":"line1\nline2\\end\"quote"`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pattern, err := buildGlobPattern(tt.key, tt.value) + require.NoError(t, err) + require.Equal(t, tt.expected, pattern) + }) + } +} diff --git a/pkg/services/ngalert/tests/fakes/rules.go b/pkg/services/ngalert/tests/fakes/rules.go index cfe790b9853..f4b5afb282d 100644 --- a/pkg/services/ngalert/tests/fakes/rules.go +++ b/pkg/services/ngalert/tests/fakes/rules.go @@ -2,6 +2,7 @@ package fakes import ( "context" + "maps" "math/rand" "slices" "strings" @@ -219,6 +220,7 @@ func (f *RuleStore) ListAlertRulesByGroup(_ context.Context, q *models.ListAlert RuleUIDs: q.RuleUIDs, ReceiverName: q.ReceiverName, HasPrometheusRuleDefinition: q.HasPrometheusRuleDefinition, + LabelMatchers: q.LabelMatchers, } ruleList, err := f.listAlertRules(query) @@ -355,6 +357,20 @@ func (f *RuleStore) listAlertRules(q *models.ListAlertRulesQuery) (models.RulesG if q.ReceiverName != "" && (len(r.NotificationSettings) < 1 || r.NotificationSettings[0].Receiver != q.ReceiverName) { continue } + + if len(q.LabelMatchers) > 0 { + matches := true + for _, m := range q.LabelMatchers { + if !m.Matches(r.Labels[m.Name]) { + matches = false + break + } + } + if !matches { + continue + } + } + copyR := models.CopyRule(r) ruleList = append(ruleList, copyR) } @@ -597,6 +613,30 @@ func (f *RuleStore) GetAlertRuleVersions(_ context.Context, orgID int64, guid st return f.History[guid], nil } +func (f *RuleStore) GetAlertRuleVersionFolders(_ context.Context, orgID int64, guid string) ([]string, error) { + f.mtx.Lock() + defer f.mtx.Unlock() + + q := GenericRecordedQuery{ + Name: "GetAlertRuleVersionFolders", + Params: []any{orgID, guid}, + } + defer func() { + f.RecordedOps = append(f.RecordedOps, q) + }() + + if err := f.Hook(q); err != nil { + return nil, err + } + + folderSet := make(map[string]struct{}) + for _, rule := range f.History[guid] { + folderSet[rule.NamespaceUID] = struct{}{} + } + + return slices.Collect(maps.Keys(folderSet)), nil +} + func (f *RuleStore) ListDeletedRules(_ context.Context, orgID int64) ([]*models.AlertRule, error) { f.mtx.Lock() defer f.mtx.Unlock() diff --git a/pkg/services/org/model.go b/pkg/services/org/model.go index 7873e899eb3..ac0268e051c 100644 --- a/pkg/services/org/model.go +++ b/pkg/services/org/model.go @@ -188,6 +188,8 @@ type SearchOrgUsersQuery struct { SortOpts []model.SortOption // Flag used to allow oss edition to query users without access control DontEnforceAccessControl bool + // Flag used to exclude hidden users from the result + ExcludeHiddenUsers bool User identity.Requester } diff --git a/pkg/services/org/orgimpl/org.go b/pkg/services/org/orgimpl/org.go index 423a4bc8b8d..6df28368f4c 100644 --- a/pkg/services/org/orgimpl/org.go +++ b/pkg/services/org/orgimpl/org.go @@ -27,6 +27,7 @@ func ProvideService(db db.DB, cfg *setting.Cfg, quotaService quota.Service) (org db: db, dialect: db.GetDialect(), log: log, + cfg: cfg, }, cfg: cfg, log: log, diff --git a/pkg/services/org/orgimpl/store.go b/pkg/services/org/orgimpl/store.go index 50bbd68ec82..7e03db60e34 100644 --- a/pkg/services/org/orgimpl/store.go +++ b/pkg/services/org/orgimpl/store.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/grafana/grafana/pkg/apimachinery/identity" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/accesscontrol" @@ -16,6 +17,7 @@ import ( "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) @@ -53,6 +55,7 @@ type sqlStore struct { //TODO: moved to service log log.Logger deletes []string + cfg *setting.Cfg } func (ss *sqlStore) Get(ctx context.Context, orgID int64) (*org.Org, error) { @@ -560,6 +563,14 @@ func (ss *sqlStore) SearchOrgUsers(ctx context.Context, query *org.SearchOrgUser whereParams = append(whereParams, acFilter.Args...) } + if query.ExcludeHiddenUsers { + cond, params := buildHiddenUsersFilter(query.User, ss.cfg.HiddenUsers) + if cond != "" { + whereConditions = append(whereConditions, cond) + whereParams = append(whereParams, params...) + } + } + if query.Query != "" { sql1, param1 := ss.dialect.LikeOperator("email", true, query.Query, true) sql2, param2 := ss.dialect.LikeOperator("name", true, query.Query, true) @@ -825,3 +836,23 @@ func removeUserOrg(sess *db.Session, userID int64) error { func (ss *sqlStore) RegisterDelete(query string) { ss.deletes = append(ss.deletes, query) } + +func buildHiddenUsersFilter(requester identity.Requester, hiddenUsersMap map[string]struct{}) (string, []any) { + if requester != nil && requester.GetIsGrafanaAdmin() { + return "", nil + } + + hiddenUsers := make([]any, 0) + for user := range hiddenUsersMap { + if requester != nil && user == requester.GetLogin() { + continue + } + hiddenUsers = append(hiddenUsers, user) + } + + if len(hiddenUsers) > 0 { + return "u.login NOT IN (?" + strings.Repeat(",?", len(hiddenUsers)-1) + ")", hiddenUsers + } + + return "", nil +} diff --git a/pkg/services/org/orgimpl/store_test.go b/pkg/services/org/orgimpl/store_test.go index 5cd7c356a5c..54f8e9fda39 100644 --- a/pkg/services/org/orgimpl/store_test.go +++ b/pkg/services/org/orgimpl/store_test.go @@ -820,8 +820,9 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { db: store, dialect: store.GetDialect(), log: log.NewNopLogger(), + cfg: cfg, } - // orgUserStore.cfg.Skip + orgSvc, userSvc := createOrgAndUserSvc(t, store, cfg) o, err := orgSvc.CreateWithMember(context.Background(), &org.CreateOrgCommand{Name: "test org"}) @@ -829,6 +830,14 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { seedOrgUsers(t, &orgUserStore, 10, userSvc, o.ID) + user1, err := userSvc.GetByLogin(context.Background(), &user.GetUserByLoginQuery{LoginOrEmail: "user-1"}) + require.NoError(t, err) + + cfg.HiddenUsers = map[string]struct{}{ + "user-1": {}, + "user-2": {}, + } + tests := []struct { desc string query *org.SearchOrgUsersQuery @@ -840,7 +849,7 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { OrgID: o.ID, User: &user.SignedInUser{ OrgID: o.ID, - Permissions: map[int64]map[string][]string{1: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, }, }, expectedNumUsers: 10, @@ -851,7 +860,7 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { OrgID: o.ID, User: &user.SignedInUser{ OrgID: o.ID, - Permissions: map[int64]map[string][]string{1: {accesscontrol.ActionOrgUsersRead: {""}}}, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {""}}}, }, }, expectedNumUsers: 0, @@ -862,8 +871,8 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { OrgID: o.ID, User: &user.SignedInUser{ OrgID: o.ID, - Permissions: map[int64]map[string][]string{1: {accesscontrol.ActionOrgUsersRead: { - "users:id:1", + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: { + "users:id:2", "users:id:5", "users:id:9", }}}, @@ -871,6 +880,55 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { }, expectedNumUsers: 3, }, + { + desc: "should exclude hidden users when ExcludeHiddenUsers is true and user is nil", + query: &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: true, + User: nil, + DontEnforceAccessControl: true, + }, + expectedNumUsers: 8, + }, + { + desc: "should not exclude hidden users when ExcludeHiddenUsers is true and user is Grafana Admin", + query: &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: true, + User: &user.SignedInUser{ + OrgID: o.ID, + IsGrafanaAdmin: true, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + }, + }, + expectedNumUsers: 10, + }, + { + desc: "should return all users if ExcludeHiddenUsers is false", + query: &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: false, + User: &user.SignedInUser{ + OrgID: o.ID, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + }, + }, + expectedNumUsers: 10, + }, + { + desc: "should include the hidden user when the request is made by the hidden user and ExcludeHiddenUsers is true", + query: &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: true, + User: &user.SignedInUser{ + UserID: user1.ID, + Login: user1.Login, + OrgID: o.ID, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + }, + }, + expectedNumUsers: 9, + }, } for _, tt := range tests { @@ -879,13 +937,58 @@ func TestIntegration_SQLStore_SearchOrgUsers(t *testing.T) { require.NoError(t, err) assert.Len(t, result.OrgUsers, tt.expectedNumUsers) - if !hasWildcardScope(tt.query.User, accesscontrol.ActionOrgUsersRead) { + // No pagination is applied, so TotalCount should equal to number of returned users + assert.Equal(t, int64(tt.expectedNumUsers), result.TotalCount) + + if tt.query.User != nil && !hasWildcardScope(tt.query.User, accesscontrol.ActionOrgUsersRead) && !tt.query.User.GetIsGrafanaAdmin() { for _, u := range result.OrgUsers { assert.Contains(t, tt.query.User.GetPermissions()[accesscontrol.ActionOrgUsersRead], fmt.Sprintf("users:id:%d", u.UserID)) } } }) } + + t.Run("should paginate correctly when ExcludeHiddenUsers is true", func(t *testing.T) { + query := &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: true, + User: &user.SignedInUser{ + OrgID: o.ID, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + }, + Limit: 5, + Page: 1, + } + result, err := orgUserStore.SearchOrgUsers(context.Background(), query) + require.NoError(t, err) + assert.Len(t, result.OrgUsers, 5) + assert.Equal(t, int64(8), result.TotalCount) + + query.Page = 2 + result, err = orgUserStore.SearchOrgUsers(context.Background(), query) + require.NoError(t, err) + assert.Len(t, result.OrgUsers, 3) + assert.Equal(t, int64(8), result.TotalCount) + }) + + t.Run("should return all users if HiddenUsers is empty", func(t *testing.T) { + oldHiddenUsers := cfg.HiddenUsers + cfg.HiddenUsers = make(map[string]struct{}) + defer func() { cfg.HiddenUsers = oldHiddenUsers }() + + query := &org.SearchOrgUsersQuery{ + OrgID: o.ID, + ExcludeHiddenUsers: true, + User: &user.SignedInUser{ + OrgID: o.ID, + Permissions: map[int64]map[string][]string{o.ID: {accesscontrol.ActionOrgUsersRead: {accesscontrol.ScopeUsersAll}}}, + }, + } + result, err := orgUserStore.SearchOrgUsers(context.Background(), query) + require.NoError(t, err) + assert.Len(t, result.OrgUsers, 10) + assert.Equal(t, int64(10), result.TotalCount) + }) } func TestIntegration_SQLStore_RemoveOrgUser(t *testing.T) { diff --git a/pkg/services/provisioning/dashboards/dashboard.go b/pkg/services/provisioning/dashboards/dashboard.go index 72b980e4198..36cacdaf12a 100644 --- a/pkg/services/provisioning/dashboards/dashboard.go +++ b/pkg/services/provisioning/dashboards/dashboard.go @@ -153,13 +153,20 @@ func (provider *Provisioner) Provision(ctx context.Context) error { // CleanUpOrphanedDashboards deletes provisioned dashboards missing a linked reader. func (provider *Provisioner) CleanUpOrphanedDashboards(ctx context.Context) { - currentReaders := make([]string, len(provider.fileReaders)) + configs := make([]dashboards.ProvisioningConfig, len(provider.fileReaders)) for index, reader := range provider.fileReaders { - currentReaders[index] = reader.Cfg.Name + configs[index] = dashboards.ProvisioningConfig{ + Name: reader.Cfg.Name, + OrgID: reader.Cfg.OrgID, + Folder: reader.Cfg.Folder, + AllowUIUpdates: reader.Cfg.AllowUIUpdates, + } } - if err := provider.provisioner.DeleteOrphanedProvisionedDashboards(ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{ReaderNames: currentReaders}); err != nil { + if err := provider.provisioner.DeleteOrphanedProvisionedDashboards( + ctx, &dashboards.DeleteOrphanedProvisionedDashboardsCommand{Config: configs}, + ); err != nil { provider.log.Warn("Failed to delete orphaned provisioned dashboards", "err", err) } } diff --git a/pkg/services/setting/service.go b/pkg/services/setting/service.go index 5afc9e22159..0a249ef65ac 100644 --- a/pkg/services/setting/service.go +++ b/pkg/services/setting/service.go @@ -2,27 +2,27 @@ package setting import ( "context" + "encoding/json" "fmt" + "io" "net/http" "time" - "github.com/grafana/grafana/pkg/infra/tracing" "github.com/prometheus/client_golang/prometheus" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/trace" "gopkg.in/ini.v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - utilnet "k8s.io/apimachinery/pkg/util/net" + "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apiserver/pkg/endpoints/request" - "k8s.io/client-go/dynamic" - clientrest "k8s.io/client-go/rest" + "k8s.io/client-go/rest" "k8s.io/client-go/transport" authlib "github.com/grafana/authlib/authn" logging "github.com/grafana/grafana/pkg/infra/log" + "github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/semconv" ) @@ -38,18 +38,11 @@ const ( ApiGroup = "setting.grafana.app" apiVersion = "v0alpha1" resource = "settings" - kind = "Setting" - listKind = "SettingList" ) -var settingGroupVersion = schema.GroupVersionResource{ - Group: ApiGroup, - Version: apiVersion, - Resource: resource, -} - -var settingGroupListKind = map[schema.GroupVersionResource]string{ - settingGroupVersion: listKind, +var settingGroupVersion = schema.GroupVersion{ + Group: ApiGroup, + Version: apiVersion, } type remoteSettingServiceMetrics struct { @@ -106,10 +99,10 @@ type Service interface { } type remoteSettingService struct { - dynamicClient dynamic.Interface - log logging.Logger - pageSize int64 - metrics remoteSettingServiceMetrics + restClient *rest.RESTClient + log logging.Logger + pageSize int64 + metrics remoteSettingServiceMetrics } var _ Service = (*remoteSettingService)(nil) @@ -126,7 +119,7 @@ type Config struct { // At least one of WrapTransport or TokenExchangeClient is required. WrapTransport transport.WrapperFunc // TLSClientConfig configures TLS for the client connection. - TLSClientConfig clientrest.TLSClientConfig + TLSClientConfig rest.TLSClientConfig // QPS limits requests per second (defaults to DefaultQPS). QPS float32 // Burst allows request bursts above QPS (defaults to DefaultBurst). @@ -145,29 +138,39 @@ type Setting struct { Value string `json:"value"` } +// settingResource represents a single Setting resource from the K8s API. +type settingResource struct { + Spec Setting `json:"spec"` +} + +// settingListMetadata contains pagination info from the K8s list response. +type settingListMetadata struct { + Continue string `json:"continue,omitempty"` +} + // New creates a Service from the provided configuration. func New(config Config) (Service, error) { log := logging.New(LogPrefix) - dynamicClient, err := getDynamicClient(config, log) + + restClient, err := getRestClient(config, log) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to create REST client: %w", err) } + pageSize := DefaultPageSize if config.PageSize > 0 { pageSize = config.PageSize } - metrics := initMetrics() - return &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: pageSize, - log: log, - metrics: metrics, + restClient: restClient, + log: log, + pageSize: pageSize, + metrics: initMetrics(), }, nil } -func (m *remoteSettingService) ListAsIni(ctx context.Context, labelSelector metav1.LabelSelector) (*ini.File, error) { +func (s *remoteSettingService) ListAsIni(ctx context.Context, labelSelector metav1.LabelSelector) (*ini.File, error) { namespace, ok := request.NamespaceFrom(ctx) ns := semconv.GrafanaNamespaceName(namespace) ctx, span := tracer.Start(ctx, "remoteSettingService.ListAsIni", @@ -178,33 +181,34 @@ func (m *remoteSettingService) ListAsIni(ctx context.Context, labelSelector meta return nil, tracing.Errorf(span, "missing namespace in context") } - settings, err := m.List(ctx, labelSelector) + settings, err := s.List(ctx, labelSelector) if err != nil { return nil, err } - iniFile, err := m.toIni(settings) + iniFile, err := toIni(settings) if err != nil { return nil, tracing.Error(span, err) } return iniFile, nil } -func (m *remoteSettingService) List(ctx context.Context, labelSelector metav1.LabelSelector) ([]*Setting, error) { +func (s *remoteSettingService) List(ctx context.Context, labelSelector metav1.LabelSelector) ([]*Setting, error) { namespace, ok := request.NamespaceFrom(ctx) ns := semconv.GrafanaNamespaceName(namespace) ctx, span := tracer.Start(ctx, "remoteSettingService.List", trace.WithAttributes(ns)) defer span.End() + if !ok || namespace == "" { return nil, tracing.Errorf(span, "missing namespace in context") } - log := m.log.FromContext(ctx).New(ns.Key, ns.Value, "function", "remoteSettingService.List", "traceId", span.SpanContext().TraceID()) + log := s.log.FromContext(ctx).New(ns.Key, ns.Value, "function", "remoteSettingService.List", "traceId", span.SpanContext().TraceID()) startTime := time.Now() var status string defer func() { duration := time.Since(startTime).Seconds() - m.metrics.listDuration.WithLabelValues(status).Observe(duration) + s.metrics.listDuration.WithLabelValues(status).Observe(duration) }() selector, err := metav1.LabelSelectorAsSelector(&labelSelector) @@ -216,64 +220,142 @@ func (m *remoteSettingService) List(ctx context.Context, labelSelector metav1.La log.Debug("empty selector. Fetching all settings") } - var allSettings []*Setting + // Pre-allocate with estimated capacity + allSettings := make([]*Setting, 0, s.pageSize*8) var continueToken string hasNext := true totalPages := 0 // Using an upper limit to prevent infinite loops for hasNext && totalPages < 1000 { totalPages++ - opts := metav1.ListOptions{ - Limit: m.pageSize, - Continue: continueToken, - } - if !selector.Empty() { - opts.LabelSelector = selector.String() - } - settingsList, lErr := m.dynamicClient.Resource(settingGroupVersion).Namespace(namespace).List(ctx, opts) + settings, nextToken, lErr := s.fetchPage(ctx, namespace, selector.String(), continueToken) if lErr != nil { status = "error" return nil, tracing.Error(span, lErr) } - for i := range settingsList.Items { - setting, pErr := parseSettingResource(&settingsList.Items[i]) - if pErr != nil { - status = "error" - return nil, tracing.Error(span, pErr) - } - allSettings = append(allSettings, setting) - } - continueToken = settingsList.GetContinue() + + allSettings = append(allSettings, settings...) + continueToken = nextToken if continueToken == "" { hasNext = false } } status = "success" - m.metrics.listResultSize.WithLabelValues(status).Observe(float64(len(allSettings))) + s.metrics.listResultSize.WithLabelValues(status).Observe(float64(len(allSettings))) return allSettings, nil } -func parseSettingResource(setting *unstructured.Unstructured) (*Setting, error) { - spec, found, err := unstructured.NestedMap(setting.Object, "spec") +func (s *remoteSettingService) fetchPage(ctx context.Context, namespace, labelSelector, continueToken string) ([]*Setting, string, error) { + req := s.restClient.Get(). + Resource(resource). + Namespace(namespace). + Param("limit", fmt.Sprintf("%d", s.pageSize)) + + if labelSelector != "" { + req = req.Param("labelSelector", labelSelector) + } + if continueToken != "" { + req = req.Param("continue", continueToken) + } + + stream, err := req.Stream(ctx) if err != nil { - return nil, fmt.Errorf("failed to get spec from setting: %w", err) - } - if !found { - return nil, fmt.Errorf("spec not found in setting %s", setting.GetName()) + return nil, "", fmt.Errorf("request failed: %w", err) } + defer func() { _ = stream.Close() }() - var result Setting - if err := runtime.DefaultUnstructuredConverter.FromUnstructured(spec, &result); err != nil { - return nil, fmt.Errorf("failed to convert spec to Setting: %w", err) - } - - return &result, nil + return parseSettingList(stream) } -func (m *remoteSettingService) toIni(settings []*Setting) (*ini.File, error) { +// parseSettingList parses a SettingList JSON response using token-by-token streaming. +func parseSettingList(r io.Reader) ([]*Setting, string, error) { + decoder := json.NewDecoder(r) + // Currently, first page may have a large number of items. + settings := make([]*Setting, 0, 1600) + var continueToken string + + // Skip to the start of the object + if _, err := decoder.Token(); err != nil { + return nil, "", fmt.Errorf("expected start of object: %w", err) + } + + for decoder.More() { + // Read field name + tok, err := decoder.Token() + if err != nil { + return nil, "", fmt.Errorf("failed to read field name: %w", err) + } + + fieldName, ok := tok.(string) + if !ok { + continue + } + + switch fieldName { + case "metadata": + var meta settingListMetadata + if err := decoder.Decode(&meta); err != nil { + return nil, "", fmt.Errorf("failed to decode metadata: %w", err) + } + continueToken = meta.Continue + + case "items": + // Parse items array token-by-token + itemSettings, err := parseItems(decoder) + if err != nil { + return nil, "", err + } + settings = append(settings, itemSettings...) + + default: + // Skip unknown fields + var skip json.RawMessage + if err := decoder.Decode(&skip); err != nil { + return nil, "", fmt.Errorf("failed to skip field %s: %w", fieldName, err) + } + } + } + + return settings, continueToken, nil +} + +func parseItems(decoder *json.Decoder) ([]*Setting, error) { + // Expect start of array + tok, err := decoder.Token() + if err != nil { + return nil, fmt.Errorf("expected start of items array: %w", err) + } + if tok != json.Delim('[') { + return nil, fmt.Errorf("expected '[', got %v", tok) + } + + settings := make([]*Setting, 0, DefaultPageSize) + + // Parse each item + for decoder.More() { + var item settingResource + if err := decoder.Decode(&item); err != nil { + return nil, fmt.Errorf("failed to decode setting item: %w", err) + } + settings = append(settings, &Setting{ + Section: item.Spec.Section, + Key: item.Spec.Key, + Value: item.Spec.Value, + }) + } + + // Consume end of array + if _, err := decoder.Token(); err != nil { + return nil, fmt.Errorf("expected end of items array: %w", err) + } + + return settings, nil +} + +func toIni(settings []*Setting) (*ini.File, error) { conf := ini.Empty() for _, setting := range settings { if !conf.HasSection(setting.Section) { @@ -287,7 +369,7 @@ func (m *remoteSettingService) toIni(settings []*Setting) (*ini.File, error) { return conf, nil } -func getDynamicClient(config Config, log logging.Logger) (dynamic.Interface, error) { +func getRestClient(config Config, log logging.Logger) (*rest.RESTClient, error) { if config.URL == "" { return nil, fmt.Errorf("URL cannot be empty") } @@ -296,7 +378,7 @@ func getDynamicClient(config Config, log logging.Logger) (dynamic.Interface, err } wrapTransport := config.WrapTransport - if config.WrapTransport == nil { + if wrapTransport == nil { log.Debug("using default wrapTransport with TokenExchangeClient") wrapTransport = func(rt http.RoundTripper) http.RoundTripper { return &authRoundTripper{ @@ -316,13 +398,24 @@ func getDynamicClient(config Config, log logging.Logger) (dynamic.Interface, err burst = config.Burst } - return dynamic.NewForConfig(&clientrest.Config{ + // Add a default scheme to handle K8s API error responses + scheme := runtime.NewScheme() + + restConfig := &rest.Config{ Host: config.URL, - WrapTransport: wrapTransport, TLSClientConfig: config.TLSClientConfig, + WrapTransport: wrapTransport, QPS: qps, Burst: burst, - }) + // Configure for our API group + APIPath: "/apis", + ContentConfig: rest.ContentConfig{ + GroupVersion: &settingGroupVersion, + NegotiatedSerializer: serializer.NewCodecFactory(scheme).WithoutConversion(), + }, + } + + return rest.RESTClientFor(restConfig) } // authRoundTripper wraps an HTTP transport with token-based authentication. @@ -341,10 +434,9 @@ func (a *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) if err != nil { return nil, fmt.Errorf("failed to exchange token: %w", err) } - req = utilnet.CloneRequest(req) - - req.Header.Set("X-Access-Token", fmt.Sprintf("Bearer %s", token.Token)) - return a.transport.RoundTrip(req) + reqCopy := req.Clone(req.Context()) + reqCopy.Header.Set("X-Access-Token", fmt.Sprintf("Bearer %s", token.Token)) + return a.transport.RoundTrip(reqCopy) } func initMetrics() remoteSettingServiceMetrics { @@ -373,12 +465,12 @@ func initMetrics() remoteSettingServiceMetrics { return metrics } -func (m *remoteSettingService) Describe(descs chan<- *prometheus.Desc) { - m.metrics.listDuration.Describe(descs) - m.metrics.listResultSize.Describe(descs) +func (s *remoteSettingService) Describe(descs chan<- *prometheus.Desc) { + s.metrics.listDuration.Describe(descs) + s.metrics.listResultSize.Describe(descs) } -func (m *remoteSettingService) Collect(metrics chan<- prometheus.Metric) { - m.metrics.listDuration.Collect(metrics) - m.metrics.listResultSize.Collect(metrics) +func (s *remoteSettingService) Collect(metrics chan<- prometheus.Metric) { + s.metrics.listDuration.Collect(metrics) + s.metrics.listResultSize.Collect(metrics) } diff --git a/pkg/services/setting/service_test.go b/pkg/services/setting/service_test.go index 949ccc73a86..9b007fb1dc9 100644 --- a/pkg/services/setting/service_test.go +++ b/pkg/services/setting/service_test.go @@ -1,69 +1,36 @@ package setting import ( + "bytes" "context" "fmt" "net/http" + "net/http/httptest" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/endpoints/request" - "k8s.io/client-go/dynamic/fake" - k8testing "k8s.io/client-go/testing" - - authlib "github.com/grafana/authlib/authn" - "github.com/grafana/grafana/pkg/infra/log" ) func TestRemoteSettingService_ListAsIni(t *testing.T) { - t.Run("should filter settings by label selector", func(t *testing.T) { - // Create multiple settings, only some matching the selector - setting1 := newUnstructuredSetting("test-namespace", Setting{Section: "database", Key: "type", Value: "postgres"}) - setting2 := newUnstructuredSetting("test-namespace", Setting{Section: "server", Key: "port", Value: "3000"}) - setting3 := newUnstructuredSetting("test-namespace", Setting{Section: "database", Key: "host", Value: "localhost"}) - - client := newTestClient(500, setting1, setting2, setting3) - - // Create a selector that should match only database settings - selector := metav1.LabelSelector{ - MatchLabels: map[string]string{ - "section": "database", - }, - } - - ctx := request.WithNamespace(context.Background(), "test-namespace") - result, err := client.ListAsIni(ctx, selector) - - require.NoError(t, err) - assert.NotNil(t, result) - // Should only have database settings, not server settings - assert.True(t, result.HasSection("database")) - assert.Equal(t, "postgres", result.Section("database").Key("type").String()) - assert.Equal(t, "localhost", result.Section("database").Key("host").String()) - // Should NOT have server settings - assert.False(t, result.HasSection("server")) - }) - t.Run("should return all settings with empty selector", func(t *testing.T) { - // Create multiple settings across different sections - setting1 := newUnstructuredSetting("test-namespace", Setting{Section: "server", Key: "port", Value: "3000"}) - setting2 := newUnstructuredSetting("test-namespace", Setting{Section: "database", Key: "type", Value: "mysql"}) - - client := newTestClient(500, setting1, setting2) - - // Empty selector should select everything - selector := metav1.LabelSelector{} + settings := []Setting{ + {Section: "server", Key: "port", Value: "3000"}, + {Section: "database", Key: "type", Value: "mysql"}, + } + server := newTestServer(t, settings, "") + defer server.Close() + client := newTestClient(t, server.URL, 500) ctx := request.WithNamespace(context.Background(), "test-namespace") - result, err := client.ListAsIni(ctx, selector) + + result, err := client.ListAsIni(ctx, metav1.LabelSelector{}) require.NoError(t, err) assert.NotNil(t, result) - // Should have all settings from all sections assert.True(t, result.HasSection("server")) assert.Equal(t, "3000", result.Section("server").Key("port").String()) assert.True(t, result.HasSection("database")) @@ -73,209 +40,244 @@ func TestRemoteSettingService_ListAsIni(t *testing.T) { func TestRemoteSettingService_List(t *testing.T) { t.Run("should handle single page response", func(t *testing.T) { - setting := newUnstructuredSetting("test-namespace", Setting{Section: "server", Key: "port", Value: "3000"}) - - client := newTestClient(500, setting) + settings := []Setting{ + {Section: "server", Key: "port", Value: "3000"}, + } + server := newTestServer(t, settings, "") + defer server.Close() + client := newTestClient(t, server.URL, 500) ctx := request.WithNamespace(context.Background(), "test-namespace") + result, err := client.List(ctx, metav1.LabelSelector{}) require.NoError(t, err) assert.Len(t, result, 1) - - spec := result[0] - assert.Equal(t, "server", spec.Section) - assert.Equal(t, "port", spec.Key) - assert.Equal(t, "3000", spec.Value) + assert.Equal(t, "server", result[0].Section) + assert.Equal(t, "port", result[0].Key) + assert.Equal(t, "3000", result[0].Value) }) - t.Run("should handle multiple pages", func(t *testing.T) { - totalPages := 3 - pageSize := 5 - - pages := make([][]*unstructured.Unstructured, totalPages) - for pageNum := 0; pageNum < totalPages; pageNum++ { - for idx := 0; idx < pageSize; idx++ { - item := newUnstructuredSetting( - "test-namespace", - Setting{ - Section: fmt.Sprintf("section-%d", pageNum), - Key: fmt.Sprintf("key-%d", idx), - Value: fmt.Sprintf("val-%d-%d", pageNum, idx), - }, - ) - pages[pageNum] = append(pages[pageNum], item) - } - } - - scheme := runtime.NewScheme() - dynamicClient := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, settingGroupListKind) - listCallCount := 0 - dynamicClient.PrependReactor("list", "settings", func(action k8testing.Action) (handled bool, ret runtime.Object, err error) { - listCallCount++ - - continueToken := fmt.Sprintf("continue-%d", listCallCount) - if listCallCount == totalPages { - continueToken = "" - } - - if listCallCount <= totalPages { - list := &unstructured.UnstructuredList{ - Object: map[string]interface{}{ - "apiVersion": ApiGroup + "/" + apiVersion, - "kind": listKind, - }, - } - list.SetContinue(continueToken) - for _, item := range pages[listCallCount-1] { - list.Items = append(list.Items, *item) - } - return true, list, nil - } - - return false, nil, nil - }) - - client := &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: int64(pageSize), - log: log.NewNopLogger(), - metrics: initMetrics(), + t.Run("should handle multiple settings", func(t *testing.T) { + settings := []Setting{ + {Section: "server", Key: "port", Value: "3000"}, + {Section: "database", Key: "host", Value: "localhost"}, + {Section: "database", Key: "port", Value: "5432"}, } + server := newTestServer(t, settings, "") + defer server.Close() + client := newTestClient(t, server.URL, 500) ctx := request.WithNamespace(context.Background(), "test-namespace") + result, err := client.List(ctx, metav1.LabelSelector{}) require.NoError(t, err) - assert.Len(t, result, totalPages*pageSize) - assert.Equal(t, totalPages, listCallCount) + assert.Len(t, result, 3) }) - t.Run("should pass label selector when provided", func(t *testing.T) { - scheme := runtime.NewScheme() - dynamicClient := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, settingGroupListKind) - dynamicClient.PrependReactor("list", "settings", func(action k8testing.Action) (handled bool, ret runtime.Object, err error) { - listAction := action.(k8testing.ListActionImpl) - assert.Equal(t, "app=grafana", listAction.ListOptions.LabelSelector) - return true, &unstructured.UnstructuredList{}, nil - }) - - client := &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: 500, - log: log.NewNopLogger(), - metrics: initMetrics(), + t.Run("should handle pagination with continue token", func(t *testing.T) { + // First page + page1Settings := []Setting{ + {Section: "section-0", Key: "key-0", Value: "value-0"}, + {Section: "section-0", Key: "key-1", Value: "value-1"}, + } + // Second page + page2Settings := []Setting{ + {Section: "section-1", Key: "key-0", Value: "value-2"}, + {Section: "section-1", Key: "key-1", Value: "value-3"}, } + requestCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestCount++ + continueToken := r.URL.Query().Get("continue") + + var settings []Setting + var nextContinue string + + if continueToken == "" { + settings = page1Settings + nextContinue = "page2" + } else { + settings = page2Settings + nextContinue = "" + } + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(generateSettingsJSON(settings, nextContinue))) + })) + defer server.Close() + + client := newTestClient(t, server.URL, 2) ctx := request.WithNamespace(context.Background(), "test-namespace") - _, err := client.List(ctx, metav1.LabelSelector{MatchLabels: map[string]string{"app": "grafana"}}) + + result, err := client.List(ctx, metav1.LabelSelector{}) require.NoError(t, err) + assert.Len(t, result, 4) + assert.Equal(t, 2, requestCount) }) - t.Run("should stop pagination at 1000 pages", func(t *testing.T) { - scheme := runtime.NewScheme() - dynamicClient := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, settingGroupListKind) - listCallCount := 0 - dynamicClient.PrependReactor("list", "settings", func(action k8testing.Action) (handled bool, ret runtime.Object, err error) { - listCallCount++ - // Always return a continue token to simulate infinite pagination - list := &unstructured.UnstructuredList{} - list.SetContinue("continue-forever") - return true, list, nil - }) + t.Run("should return error when namespace is missing", func(t *testing.T) { + server := newTestServer(t, nil, "") + defer server.Close() - client := &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: 10, - log: log.NewNopLogger(), - metrics: initMetrics(), - } + client := newTestClient(t, server.URL, 500) + ctx := context.Background() // No namespace - ctx := request.WithNamespace(context.Background(), "test-namespace") - _, err := client.List(ctx, metav1.LabelSelector{}) - - require.NoError(t, err) - assert.Equal(t, 1000, listCallCount, "Should stop at 1000 pages to prevent infinite loops") - }) - - t.Run("should return error when parsing setting fails", func(t *testing.T) { - scheme := runtime.NewScheme() - dynamicClient := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, settingGroupListKind) - dynamicClient.PrependReactor("list", "settings", func(action k8testing.Action) (handled bool, ret runtime.Object, err error) { - // Return a malformed setting without spec - list := &unstructured.UnstructuredList{ - Object: map[string]interface{}{ - "apiVersion": ApiGroup + "/" + apiVersion, - "kind": listKind, - }, - } - malformedSetting := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": ApiGroup + "/" + apiVersion, - "kind": kind, - "metadata": map[string]interface{}{ - "name": "malformed", - "namespace": "test-namespace", - }, - // Missing spec - }, - } - list.Items = append(list.Items, *malformedSetting) - return true, list, nil - }) - - client := &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: 500, - log: log.NewNopLogger(), - metrics: initMetrics(), - } - - ctx := request.WithNamespace(context.Background(), "test-namespace") result, err := client.List(ctx, metav1.LabelSelector{}) require.Error(t, err) assert.Nil(t, result) - assert.Contains(t, err.Error(), "spec not found") - }) -} - -func TestParseSettingResource(t *testing.T) { - t.Run("should parse valid setting resource", func(t *testing.T) { - setting := newUnstructuredSetting("test-namespace", Setting{Section: "database", Key: "type", Value: "postgres"}) - - result, err := parseSettingResource(setting) - - require.NoError(t, err) - assert.NotNil(t, result) - assert.Equal(t, "database", result.Section) - assert.Equal(t, "type", result.Key) - assert.Equal(t, "postgres", result.Value) + assert.Contains(t, err.Error(), "missing namespace") }) - t.Run("should return error when spec is missing", func(t *testing.T) { - setting := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": ApiGroup + "/" + apiVersion, - "kind": kind, - "metadata": map[string]interface{}{ - "name": "test-setting", - "namespace": "test-namespace", - }, - // No spec + t.Run("should return error on HTTP error", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("internal server error")) + })) + defer server.Close() + + client := newTestClient(t, server.URL, 500) + ctx := request.WithNamespace(context.Background(), "test-namespace") + + result, err := client.List(ctx, metav1.LabelSelector{}) + + require.Error(t, err) + assert.Nil(t, result) + }) + + t.Run("should handle API errors", func(t *testing.T) { + statusResponse := `{ + "apiVersion": "v1", + "kind": "Status", + "metadata": {}, + "status": "Failure", + "message": "settings.setting.grafana.app \"test\" not found", + "reason": "NotFound", + "details": { + "name": "test", + "group": "setting.grafana.app", + "kind": "settings" }, - } + "code": 404 + }` - result, err := parseSettingResource(setting) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(statusResponse)) + })) + defer server.Close() + + client := newTestClient(t, server.URL, 500) + ctx := request.WithNamespace(context.Background(), "test-namespace") + + result, err := client.List(ctx, metav1.LabelSelector{}) require.Error(t, err) assert.Nil(t, result) - assert.Contains(t, err.Error(), "spec not found") + assert.Contains(t, err.Error(), "could not find the requested resource") + }) + + t.Run("should handle 500 internal server error", func(t *testing.T) { + statusResponse := `{ + "apiVersion": "v1", + "kind": "Status", + "metadata": {}, + "status": "Failure", + "message": "Internal error occurred: database connection failed", + "reason": "InternalError", + "code": 500 + }` + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(statusResponse)) + })) + defer server.Close() + + client := newTestClient(t, server.URL, 500) + ctx := request.WithNamespace(context.Background(), "test-namespace") + + result, err := client.List(ctx, metav1.LabelSelector{}) + + require.Error(t, err) + assert.Nil(t, result) + assert.Contains(t, err.Error(), "error on the server") + }) + + t.Run("should handle connection errors", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + serverURL := server.URL + server.Close() + + client := newTestClient(t, serverURL, 500) + ctx := request.WithNamespace(context.Background(), "test-namespace") + + result, err := client.List(ctx, metav1.LabelSelector{}) + + require.Error(t, err) + assert.Nil(t, result) + assert.Contains(t, err.Error(), "connection refused") }) } -func TestRemoteSettingService_ToIni(t *testing.T) { +func TestParseSettingList(t *testing.T) { + t.Run("should parse valid settings list", func(t *testing.T) { + jsonData := `{ + "apiVersion": "setting.grafana.app/v0alpha1", + "kind": "SettingList", + "metadata": {"continue": ""}, + "items": [ + {"spec": {"section": "database", "key": "type", "value": "postgres"}}, + {"spec": {"section": "server", "key": "port", "value": "3000"}} + ] + }` + + settings, continueToken, err := parseSettingList(strings.NewReader(jsonData)) + + require.NoError(t, err) + assert.Len(t, settings, 2) + assert.Equal(t, "", continueToken) + assert.Equal(t, "database", settings[0].Section) + assert.Equal(t, "type", settings[0].Key) + assert.Equal(t, "postgres", settings[0].Value) + }) + + t.Run("should parse continue token", func(t *testing.T) { + jsonData := `{ + "apiVersion": "setting.grafana.app/v0alpha1", + "kind": "SettingList", + "metadata": {"continue": "next-page-token"}, + "items": [] + }` + + _, continueToken, err := parseSettingList(strings.NewReader(jsonData)) + + require.NoError(t, err) + assert.Equal(t, "next-page-token", continueToken) + }) + + t.Run("should handle empty items", func(t *testing.T) { + jsonData := `{ + "apiVersion": "setting.grafana.app/v0alpha1", + "kind": "SettingList", + "metadata": {}, + "items": [] + }` + + settings, _, err := parseSettingList(strings.NewReader(jsonData)) + + require.NoError(t, err) + assert.Len(t, settings, 0) + }) +} + +func TestToIni(t *testing.T) { t.Run("should convert settings to ini format", func(t *testing.T) { settings := []*Setting{ {Section: "database", Key: "type", Value: "postgres"}, @@ -283,12 +285,7 @@ func TestRemoteSettingService_ToIni(t *testing.T) { {Section: "server", Key: "http_port", Value: "3000"}, } - client := &remoteSettingService{ - pageSize: 500, - log: log.NewNopLogger(), - } - - result, err := client.toIni(settings) + result, err := toIni(settings) require.NoError(t, err) assert.NotNil(t, result) @@ -302,12 +299,7 @@ func TestRemoteSettingService_ToIni(t *testing.T) { t.Run("should handle empty settings list", func(t *testing.T) { var settings []*Setting - client := &remoteSettingService{ - pageSize: 500, - log: log.NewNopLogger(), - } - - result, err := client.toIni(settings) + result, err := toIni(settings) require.NoError(t, err) assert.NotNil(t, result) @@ -315,35 +307,13 @@ func TestRemoteSettingService_ToIni(t *testing.T) { assert.Len(t, sections, 1) // Only default section }) - t.Run("should create section if it does not exist", func(t *testing.T) { - settings := []*Setting{ - {Section: "new_section", Key: "new_key", Value: "new_value"}, - } - - client := &remoteSettingService{ - pageSize: 500, - log: log.NewNopLogger(), - } - - result, err := client.toIni(settings) - - require.NoError(t, err) - assert.True(t, result.HasSection("new_section")) - assert.Equal(t, "new_value", result.Section("new_section").Key("new_key").String()) - }) - t.Run("should handle multiple keys in same section", func(t *testing.T) { settings := []*Setting{ {Section: "auth", Key: "disable_login_form", Value: "false"}, {Section: "auth", Key: "disable_signout_menu", Value: "true"}, } - client := &remoteSettingService{ - pageSize: 500, - log: log.NewNopLogger(), - } - - result, err := client.toIni(settings) + result, err := toIni(settings) require.NoError(t, err) assert.True(t, result.HasSection("auth")) @@ -383,24 +353,23 @@ func TestNew(t *testing.T) { assert.Equal(t, int64(100), remoteClient.pageSize) }) - t.Run("should use default page size when zero is provided", func(t *testing.T) { + t.Run("should create client with custom QPS and Burst", func(t *testing.T) { config := Config{ URL: "https://example.com", WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, - PageSize: 0, + QPS: 50.0, + Burst: 100, } client, err := New(config) require.NoError(t, err) assert.NotNil(t, client) - remoteClient := client.(*remoteSettingService) - assert.Equal(t, DefaultPageSize, remoteClient.pageSize) }) - t.Run("should return error when config is invalid", func(t *testing.T) { + t.Run("should return error when URL is empty", func(t *testing.T) { config := Config{ - URL: "", // Invalid: empty URL + URL: "", } client, err := New(config) @@ -409,134 +378,126 @@ func TestNew(t *testing.T) { assert.Nil(t, client) assert.Contains(t, err.Error(), "URL cannot be empty") }) -} -func TestGetDynamicClient(t *testing.T) { - logger := log.NewNopLogger() - - t.Run("should return error when SettingServiceURL is empty", func(t *testing.T) { - config := Config{ - URL: "", - WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, - } - - client, err := getDynamicClient(config, logger) - - require.Error(t, err) - assert.Nil(t, client) - assert.Contains(t, err.Error(), "URL cannot be empty") - }) - - t.Run("should return error when both TokenExchangeClient and WrapTransport are nil", func(t *testing.T) { + t.Run("should return error when auth is not configured", func(t *testing.T) { config := Config{ URL: "https://example.com", TokenExchangeClient: nil, WrapTransport: nil, } - client, err := getDynamicClient(config, logger) + client, err := New(config) require.Error(t, err) assert.Nil(t, client) assert.Contains(t, err.Error(), "must set either TokenExchangeClient or WrapTransport") }) - t.Run("should create client with WrapTransport", func(t *testing.T) { - config := Config{ - URL: "https://example.com", - WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, - } - - client, err := getDynamicClient(config, logger) - - require.NoError(t, err) - assert.NotNil(t, client) - }) - - t.Run("should not fail when QPS and Burst are not provided", func(t *testing.T) { - config := Config{ - URL: "https://example.com", - WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, - } - - client, err := getDynamicClient(config, logger) - - require.NoError(t, err) - assert.NotNil(t, client) - }) - - t.Run("should not fail when custom QPS and Burst are provided", func(t *testing.T) { - config := Config{ - URL: "https://example.com", - WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, - QPS: 10.0, - Burst: 20, - } - - client, err := getDynamicClient(config, logger) - - require.NoError(t, err) - assert.NotNil(t, client) - }) - - t.Run("should use WrapTransport when both WrapTransport and TokenExchangeClient are provided", func(t *testing.T) { + t.Run("should use WrapTransport when provided", func(t *testing.T) { wrapTransportCalled := false - tokenExchangeClient := &authlib.TokenExchangeClient{} config := Config{ - URL: "https://example.com", - TokenExchangeClient: tokenExchangeClient, + URL: "https://example.com", WrapTransport: func(rt http.RoundTripper) http.RoundTripper { wrapTransportCalled = true return rt }, } - client, err := getDynamicClient(config, logger) + client, err := New(config) require.NoError(t, err) assert.NotNil(t, client) - assert.True(t, wrapTransportCalled, "WrapTransport should be called and take precedence over TokenExchangeClient") + assert.True(t, wrapTransportCalled) }) } -// Helper function to create an unstructured Setting object for tests -func newUnstructuredSetting(namespace string, spec Setting) *unstructured.Unstructured { - // Generate resource name in the format {section}--{key} - name := fmt.Sprintf("%s--%s", spec.Section, spec.Key) +// Helper functions - obj := &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": ApiGroup + "/" + apiVersion, - "kind": kind, - "metadata": map[string]interface{}{ - "name": name, - "namespace": namespace, - }, - "spec": map[string]interface{}{ - "section": spec.Section, - "key": spec.Key, - "value": spec.Value, - }, - }, - } - // Always set section and key labels - obj.SetLabels(map[string]string{ - "section": spec.Section, - "key": spec.Key, - }) - return obj +func newTestServer(t *testing.T, settings []Setting, continueToken string) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(generateSettingsJSON(settings, continueToken))) + })) } -// Helper function to create a test client with the dynamic fake client -func newTestClient(pageSize int64, objects ...runtime.Object) *remoteSettingService { - scheme := runtime.NewScheme() - dynamicClient := fake.NewSimpleDynamicClientWithCustomListKinds(scheme, settingGroupListKind, objects...) +func newTestClient(t *testing.T, serverURL string, pageSize int64) Service { + t.Helper() + config := Config{ + URL: serverURL, + WrapTransport: func(rt http.RoundTripper) http.RoundTripper { return rt }, + PageSize: pageSize, + } + client, err := New(config) + require.NoError(t, err) + return client +} - return &remoteSettingService{ - dynamicClient: dynamicClient, - pageSize: pageSize, - log: log.NewNopLogger(), - metrics: initMetrics(), +func generateSettingsJSON(settings []Setting, continueToken string) string { + var sb strings.Builder + sb.WriteString(fmt.Sprintf(`{"apiVersion":"setting.grafana.app/v0alpha1","kind":"SettingList","metadata":{"continue":"%s"},"items":[`, continueToken)) + + for i, s := range settings { + if i > 0 { + sb.WriteString(",") + } + sb.WriteString(fmt.Sprintf( + `{"apiVersion":"setting.grafana.app/v0alpha1","kind":"Setting","metadata":{"name":"%s--%s","namespace":"test-namespace"},"spec":{"section":"%s","key":"%s","value":"%s"}}`, + s.Section, s.Key, s.Section, s.Key, s.Value, + )) + } + + sb.WriteString(`]}`) + return sb.String() +} + +// Benchmark tests for streaming JSON parser + +func BenchmarkParseSettingList(b *testing.B) { + jsonData := generateSettingListJSON(4000, 100) + jsonBytes := []byte(jsonData) + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + reader := bytes.NewReader(jsonBytes) + _, _, _ = parseSettingList(reader) } } + +func BenchmarkParseSettingList_SinglePage(b *testing.B) { + jsonData := generateSettingListJSON(500, 50) + jsonBytes := []byte(jsonData) + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + reader := bytes.NewReader(jsonBytes) + _, _, _ = parseSettingList(reader) + } +} + +// generateSettingListJSON generates a K8s-style SettingList JSON response for benchmarks +func generateSettingListJSON(totalSettings, numSections int) string { + var sb strings.Builder + sb.WriteString(`{"apiVersion":"setting.grafana.app/v0alpha1","kind":"SettingList","metadata":{"continue":""},"items":[`) + + settingsPerSection := totalSettings / numSections + first := true + for section := 0; section < numSections; section++ { + for key := 0; key < settingsPerSection; key++ { + if !first { + sb.WriteString(",") + } + first = false + sb.WriteString(fmt.Sprintf( + `{"apiVersion":"setting.grafana.app/v0alpha1","kind":"Setting","metadata":{"name":"section-%03d--key-%03d","namespace":"bench-ns"},"spec":{"section":"section-%03d","key":"key-%03d","value":"value-for-section-%d-key-%d"}}`, + section, key, section, key, section, key, + )) + } + } + + sb.WriteString(`]}`) + return sb.String() +} diff --git a/pkg/services/sqlstore/migrations/accesscontrol/alerting.go b/pkg/services/sqlstore/migrations/accesscontrol/alerting.go index f9942fac80e..deddf59eb12 100644 --- a/pkg/services/sqlstore/migrations/accesscontrol/alerting.go +++ b/pkg/services/sqlstore/migrations/accesscontrol/alerting.go @@ -116,3 +116,49 @@ func (m *receiverCreateScopeMigration) Exec(sess *xorm.Session, mg *migrator.Mig func AddReceiverCreateScopeMigration(mg *migrator.Migrator) { mg.AddMigration("remove scope from alert.notifications.receivers:create", &receiverCreateScopeMigration{}) } + +type receiverProtectedFieldsEditor struct { + migrator.MigrationBase +} + +var _ migrator.CodeMigration = new(alertingMigrator) + +func (m *receiverProtectedFieldsEditor) SQL(migrator.Dialect) string { + return "code migration" +} + +func (m *receiverProtectedFieldsEditor) Exec(sess *xorm.Session, mg *migrator.Migrator) error { + sql := `SELECT * + FROM permission AS P + WHERE action = 'alert.notifications.receivers.secrets:read' + AND EXISTS(SELECT 1 FROM role AS R WHERE R.id = P.role_id AND R.name LIKE 'managed:%') + AND NOT EXISTS(SELECT 1 + FROM permission AS P2 + WHERE P2.role_id = P.role_id + AND P2.action = 'alert.notifications.receivers.protected:write' AND P2.scope = P.scope + )` + var results []accesscontrol.Permission + if err := sess.SQL(sql).Find(&results); err != nil { + return fmt.Errorf("failed to query permissions: %w", err) + } + + permissionsToCreate := make([]accesscontrol.Permission, 0, len(results)) + rolesAffected := make(map[int64][]string, 0) + for _, result := range results { + result.ID = 0 + result.Action = "alert.notifications.receivers.protected:write" + result.Created = time.Now() + result.Updated = time.Now() + permissionsToCreate = append(permissionsToCreate, result) + rolesAffected[result.RoleID] = append(rolesAffected[result.RoleID], result.Identifier) + } + _, err := sess.InsertMulti(&permissionsToCreate) + for id, ids := range rolesAffected { + mg.Logger.Debug("Added permission 'alert.notifications.receivers.protected:write' to managed role", "roleID", id, "identifiers", ids) + } + return err +} + +func AddReceiverProtectedFieldsEditor(mg *migrator.Migrator) { + mg.AddMigration("add 'alert.notifications.receivers.protected:write' to receiver admins", &receiverProtectedFieldsEditor{}) +} diff --git a/pkg/services/sqlstore/migrations/annotation_mig.go b/pkg/services/sqlstore/migrations/annotation_mig.go index 914f73819fc..d1cd33b108f 100644 --- a/pkg/services/sqlstore/migrations/annotation_mig.go +++ b/pkg/services/sqlstore/migrations/annotation_mig.go @@ -261,8 +261,8 @@ func RunDashboardUIDMigrations(sess *xorm.Session, driverName string, logger log logger.Info("Starting batched dashboard_uid migration for annotations (newest first)", "batchSize", batchSize) updateSQL := `UPDATE annotation SET dashboard_uid = (SELECT uid FROM dashboard WHERE dashboard.id = annotation.dashboard_id) - WHERE dashboard_uid IS NULL - AND dashboard_id != 0 + WHERE dashboard_uid IS NULL + AND dashboard_id != 0 AND EXISTS (SELECT 1 FROM dashboard WHERE dashboard.id = annotation.dashboard_id) AND annotation.id IN ( SELECT id FROM annotation @@ -285,19 +285,19 @@ func RunDashboardUIDMigrations(sess *xorm.Session, driverName string, logger log LIMIT $1 )` case MySQL: - updateSQL = `UPDATE annotation - INNER JOIN dashboard ON annotation.dashboard_id = dashboard.id - SET annotation.dashboard_uid = dashboard.uid - WHERE annotation.dashboard_uid IS NULL - AND annotation.dashboard_id != 0 - AND annotation.id IN ( - SELECT id FROM ( - SELECT id FROM annotation - WHERE dashboard_uid IS NULL AND dashboard_id != 0 - ORDER BY id DESC - LIMIT ? - ) AS batch - )` + updateSQL = `UPDATE annotation AS a + JOIN dashboard AS d ON a.dashboard_id = d.id + JOIN ( + SELECT id + FROM annotation + WHERE dashboard_uid IS NULL + AND dashboard_id != 0 + ORDER BY id DESC + LIMIT ? + ) AS batch ON batch.id = a.id + SET a.dashboard_uid = d.uid + WHERE a.dashboard_uid IS NULL + AND a.dashboard_id != 0` } updatedTotal := int64(0) diff --git a/pkg/services/sqlstore/migrations/migrations.go b/pkg/services/sqlstore/migrations/migrations.go index e713525c0f6..17dd7b9c068 100644 --- a/pkg/services/sqlstore/migrations/migrations.go +++ b/pkg/services/sqlstore/migrations/migrations.go @@ -165,5 +165,9 @@ func (oss *OSSMigrations) AddMigration(mg *Migrator) { ualert.AddStateAnnotationsColumn(mg) + ualert.CollateBinAlertRuleNamespace(mg) + ualert.CollateBinAlertRuleGroup(mg) + + accesscontrol.AddReceiverProtectedFieldsEditor(mg) } diff --git a/pkg/services/sqlstore/migrations/ualert/alert_rule_namespace_collation.go b/pkg/services/sqlstore/migrations/ualert/alert_rule_namespace_collation.go new file mode 100644 index 00000000000..2766f337baa --- /dev/null +++ b/pkg/services/sqlstore/migrations/ualert/alert_rule_namespace_collation.go @@ -0,0 +1,10 @@ +package ualert + +import "github.com/grafana/grafana/pkg/services/sqlstore/migrator" + +// CollateBinAlertRuleNamespace ensures that namespace_uid column collates in the same way go sorts strings. +func CollateBinAlertRuleNamespace(mg *migrator.Migrator) { + mg.AddMigration("ensure namespace_uid column sorts the same way as golang", migrator.NewRawSQLMigration(""). + Mysql("ALTER TABLE alert_rule MODIFY namespace_uid VARCHAR(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;"). + Postgres(`ALTER TABLE alert_rule ALTER COLUMN namespace_uid SET DATA TYPE varchar(40) COLLATE "C";`)) +} diff --git a/pkg/services/updatemanager/plugins.go b/pkg/services/updatemanager/plugins.go index 79270f8a1ee..7ee11b261f9 100644 --- a/pkg/services/updatemanager/plugins.go +++ b/pkg/services/updatemanager/plugins.go @@ -13,6 +13,7 @@ import ( "time" "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient" + "github.com/open-feature/go-sdk/openfeature" "go.opentelemetry.io/otel/codes" "github.com/grafana/grafana/pkg/infra/httpclient/httpclientprovider" @@ -96,11 +97,7 @@ func (s *PluginsService) IsDisabled() bool { } func (s *PluginsService) Run(ctx context.Context) error { - s.instrumentedCheckForUpdates(ctx) - //nolint:staticcheck // not yet migrated to OpenFeature - if s.features.IsEnabledGlobally(featuremgmt.FlagPluginsAutoUpdate) { - s.updateAll(ctx) - } + s.checkAndUpdate(ctx) ticker := time.NewTicker(time.Minute * 10) run := true @@ -108,11 +105,7 @@ func (s *PluginsService) Run(ctx context.Context) error { for run { select { case <-ticker.C: - s.instrumentedCheckForUpdates(ctx) - //nolint:staticcheck // not yet migrated to OpenFeature - if s.features.IsEnabledGlobally(featuremgmt.FlagPluginsAutoUpdate) { - s.updateAll(ctx) - } + s.checkAndUpdate(ctx) case <-ctx.Done(): run = false } @@ -140,6 +133,14 @@ func (s *PluginsService) HasUpdate(ctx context.Context, pluginID string) (string return "", false } +// checkAndUpdate checks for updates and applies them if auto-update is enabled. +func (s *PluginsService) checkAndUpdate(ctx context.Context) { + s.instrumentedCheckForUpdates(ctx) + if openfeature.NewDefaultClient().Boolean(ctx, featuremgmt.FlagPluginsAutoUpdate, false, openfeature.TransactionContext(ctx)) { + s.updateAll(ctx) + } +} + func (s *PluginsService) instrumentedCheckForUpdates(ctx context.Context) { start := time.Now() ctx, span := s.tracer.Start(ctx, "updatechecker.PluginsService.checkForUpdates") @@ -226,8 +227,7 @@ func (s *PluginsService) canUpdate(ctx context.Context, plugin pluginstore.Plugi return false } - //nolint:staticcheck // not yet migrated to OpenFeature - if s.features.IsEnabledGlobally(featuremgmt.FlagPluginsAutoUpdate) { + if openfeature.NewDefaultClient().Boolean(ctx, featuremgmt.FlagPluginsAutoUpdate, false, openfeature.TransactionContext(ctx)) { return s.updateChecker.CanUpdate(plugin.ID, plugin.Info.Version, gcomVersion, s.updateStrategy == setting.PluginUpdateStrategyMinor) } diff --git a/pkg/services/updatemanager/plugins_test.go b/pkg/services/updatemanager/plugins_test.go index 0455963f168..75834c44c7d 100644 --- a/pkg/services/updatemanager/plugins_test.go +++ b/pkg/services/updatemanager/plugins_test.go @@ -6,8 +6,10 @@ import ( "net/http" "net/url" "strings" + "sync" "testing" + "github.com/open-feature/go-sdk/openfeature" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/infra/log" @@ -19,6 +21,7 @@ import ( "github.com/grafana/grafana/pkg/services/pluginsintegration/pluginchecker" "github.com/grafana/grafana/pkg/services/pluginsintegration/pluginstore" "github.com/grafana/grafana/pkg/services/pluginsintegration/provisionedplugins" + "github.com/grafana/grafana/pkg/setting" ) type mockPluginPreinstall struct { @@ -240,6 +243,7 @@ func TestPluginUpdateChecker_checkForUpdates(t *testing.T) { require.Empty(t, svc.availableUpdates["test-core-panel"]) }) } + func TestPluginUpdateChecker_updateAll(t *testing.T) { t.Run("update is available", func(t *testing.T) { pluginsFakeStore := map[string]string{} @@ -300,3 +304,88 @@ func (c *fakeHTTPClient) Do(req *http.Request) (*http.Response, error) { return resp, nil } + +func TestPluginsService_PluginsAutoUpdateFlag(t *testing.T) { + updateCheckURL, _ := url.Parse("https://grafana.com/api/plugins/versioncheck") + + tests := []struct { + name string + flagEnabled bool + expectUpdate bool + }{ + { + name: "pluginsAutoUpdate enabled calls updateAll", + flagEnabled: true, + expectUpdate: true, + }, + { + name: "pluginsAutoUpdate disabled does not call updateAll", + flagEnabled: false, + expectUpdate: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + setupOpenFeatureProvider(t, tt.flagEnabled) + + updateCallCount := 0 + + availableUpdates := map[string]availableUpdate{ + "test-plugin": { + localVersion: "0.9.0", + availableVersion: "1.0.0", + }, + } + + svc := &PluginsService{ + availableUpdates: availableUpdates, + httpClient: &fakeHTTPClient{ + fakeResp: `[]`, + }, + log: log.NewNopLogger(), + tracer: tracing.InitializeTracerForTest(), + updateCheckURL: updateCheckURL, + updateChecker: pluginchecker.ProvideService(managedplugins.NewNoop(), provisionedplugins.NewNoop(), &mockPluginPreinstall{}), + pluginStore: &pluginstore.FakePluginStore{PluginList: []pluginstore.Plugin{}}, + pluginInstaller: &pluginfakes.FakePluginInstaller{ + AddFunc: func(ctx context.Context, pluginID, version string, opts plugins.AddOpts) error { + updateCallCount++ + return nil + }, + }, + grafanaVersion: "10.0.0", + } + + ctx := context.Background() + // Test the synchronous initialization work directly, without the long-running ticker loop + svc.checkAndUpdate(ctx) + + if tt.expectUpdate { + require.Equal(t, updateCallCount, 1, "updateAll should be called when flag is enabled") + } else { + require.Equal(t, 0, updateCallCount, "updateAll should not be called when flag is disabled") + } + }) + } +} + +var openfeatureTestMutex sync.Mutex + +func setupOpenFeatureProvider(t *testing.T, flagValue bool) { + t.Helper() + openfeatureTestMutex.Lock() + + err := featuremgmt.InitOpenFeature(featuremgmt.OpenFeatureConfig{ + ProviderType: setting.StaticProviderType, + StaticFlags: map[string]bool{ + featuremgmt.FlagPluginsAutoUpdate: flagValue, + }, + }) + require.NoError(t, err) + + t.Cleanup(func() { + _ = openfeature.SetProviderAndWait(openfeature.NoopProvider{}) + openfeatureTestMutex.Unlock() + }) +} diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go index cc59427da6f..8e309433032 100644 --- a/pkg/setting/setting.go +++ b/pkg/setting/setting.go @@ -247,11 +247,12 @@ type Cfg struct { MetricsGrafanaEnvironmentInfo map[string]string // Dashboards - DashboardVersionsToKeep int - MinRefreshInterval string - DefaultHomeDashboardPath string - DashboardPerformanceMetrics []string - PanelSeriesLimit int + DashboardVersionsToKeep int + MinRefreshInterval string + DefaultHomeDashboardPath string + DashboardPerformanceMetrics []string + PanelSeriesLimit int + DashboardSchemaMigrationCacheTTL time.Duration // Auth LoginCookieName string @@ -617,6 +618,7 @@ type Cfg struct { EnableSearch bool OverridesFilePath string OverridesReloadInterval time.Duration + EnableSQLKVBackend bool // Secrets Management SecretsManagement SecretsManagerSettings @@ -1237,6 +1239,7 @@ func (cfg *Cfg) parseINIFile(iniFile *ini.File) error { cfg.DefaultHomeDashboardPath = dashboards.Key("default_home_dashboard_path").MustString("") cfg.DashboardPerformanceMetrics = util.SplitString(dashboards.Key("dashboard_performance_metrics").MustString("")) cfg.PanelSeriesLimit = dashboards.Key("panel_series_limit").MustInt(0) + cfg.DashboardSchemaMigrationCacheTTL = dashboards.Key("schema_migration_cache_ttl").MustDuration(time.Minute) if err := readUserSettings(iniFile, cfg); err != nil { return err diff --git a/pkg/setting/setting_plugins.go b/pkg/setting/setting_plugins.go index a6842a276a0..5a83c3b1f5a 100644 --- a/pkg/setting/setting_plugins.go +++ b/pkg/setting/setting_plugins.go @@ -102,7 +102,7 @@ func (cfg *Cfg) processPreinstallPlugins(rawInstallPlugins []string, preinstallP if len(parts) > 1 { version = parts[1] if len(parts) > 2 { - url = parts[2] + url = strings.Join(parts[2:], "@") } } diff --git a/pkg/setting/setting_plugins_test.go b/pkg/setting/setting_plugins_test.go index 9b0df2aa583..4c29e5d3fdc 100644 --- a/pkg/setting/setting_plugins_test.go +++ b/pkg/setting/setting_plugins_test.go @@ -210,6 +210,11 @@ func Test_readPluginSettings(t *testing.T) { rawInput: "plugin1@@https://example.com/plugin1.tar.gz", expected: append(defaultPreinstallPluginsList, InstallPlugin{ID: "plugin1", Version: "", URL: "https://example.com/plugin1.tar.gz"}), }, + { + name: "should parse a plugin with credentials in the URL", + rawInput: "plugin1@@https://username:password@example.com/plugin1.tar.gz", + expected: append(defaultPreinstallPluginsList, InstallPlugin{ID: "plugin1", Version: "", URL: "https://username:password@example.com/plugin1.tar.gz"}), + }, { name: "when preinstall_async is false, should add all plugins to preinstall_sync", rawInput: "plugin1", diff --git a/pkg/setting/setting_unified_alerting.go b/pkg/setting/setting_unified_alerting.go index 7a365aec624..0733e8241e6 100644 --- a/pkg/setting/setting_unified_alerting.go +++ b/pkg/setting/setting_unified_alerting.go @@ -153,6 +153,9 @@ type UnifiedAlertingSettings struct { // DeletedRuleRetention defines the maximum duration to retain deleted alerting rules before permanent removal. DeletedRuleRetention time.Duration + + // AlertmanagerMaxTemplateOutputSize specifies the maximum allowed size for rendered template output in bytes. + AlertmanagerMaxTemplateOutputSize int64 } type RecordingRuleSettings struct { @@ -583,6 +586,11 @@ func (cfg *Cfg) ReadUnifiedAlertingSettings(iniFile *ini.File) error { return fmt.Errorf("setting 'deleted_rule_retention' is invalid, only 0 or a positive duration are allowed") } + uaCfg.AlertmanagerMaxTemplateOutputSize = ua.Key("alertmanager_max_template_output_bytes").MustInt64(10485760) + if uaCfg.AlertmanagerMaxTemplateOutputSize < 0 { + return fmt.Errorf("setting 'alertmanager_max_template_output_bytes' is invalid, only 0 or a positive integer are allowed") + } + cfg.UnifiedAlerting = uaCfg return nil } diff --git a/pkg/setting/setting_unified_storage.go b/pkg/setting/setting_unified_storage.go index 4f69daa64fd..72e01ce6ce9 100644 --- a/pkg/setting/setting_unified_storage.go +++ b/pkg/setting/setting_unified_storage.go @@ -100,6 +100,9 @@ func (cfg *Cfg) setUnifiedStorageConfig() { cfg.OverridesFilePath = section.Key("overrides_path").String() cfg.OverridesReloadInterval = section.Key("overrides_reload_period").MustDuration(30 * time.Second) + // use sqlkv (resource/sqlkv) instead of the sql backend (sql/backend) as the StorageServer + cfg.EnableSQLKVBackend = section.Key("enable_sqlkv_backend").MustBool(false) + cfg.MaxFileIndexAge = section.Key("max_file_index_age").MustDuration(0) cfg.MinFileIndexBuildVersion = section.Key("min_file_index_build_version").MustString("") } diff --git a/pkg/setting/settings_zanzana.go b/pkg/setting/settings_zanzana.go index 1a06ea034ef..d30304e4bd0 100644 --- a/pkg/setting/settings_zanzana.go +++ b/pkg/setting/settings_zanzana.go @@ -110,15 +110,24 @@ func (cfg *Cfg) readZanzanaSettings() { zc.Mode = "embedded" } - zc.Token = clientSec.Key("token").MustString("") - zc.TokenExchangeURL = clientSec.Key("token_exchange_url").MustString("") zc.Addr = clientSec.Key("address").MustString("") zc.ServerCertFile = clientSec.Key("tls_cert").MustString("") - // TODO: read Token and TokenExchangeURL from grpc_client_authentication section grpcClientAuthSection := cfg.SectionWithEnvOverrides("grpc_client_authentication") + zc.Token = grpcClientAuthSection.Key("token").MustString("") + zc.TokenExchangeURL = grpcClientAuthSection.Key("token_exchange_url").MustString("") zc.TokenNamespace = grpcClientAuthSection.Key("token_namespace").MustString("stacks-" + cfg.StackID) + // TODO: remove old settings when migrated + token := clientSec.Key("token").MustString("") + tokenExchangeURL := clientSec.Key("token_exchange_url").MustString("") + if token != "" { + zc.Token = token + } + if tokenExchangeURL != "" { + zc.TokenExchangeURL = tokenExchangeURL + } + cfg.ZanzanaClient = zc zs := ZanzanaServerSettings{} diff --git a/pkg/storage/unified/README.md b/pkg/storage/unified/README.md index 7131178e8a1..e9bdbf88e37 100644 --- a/pkg/storage/unified/README.md +++ b/pkg/storage/unified/README.md @@ -280,6 +280,35 @@ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest - make changes in `.proto` file - to compile all protobuf files in the repository run `make protobuf` at its top level +## Enable Quotas/Overrides +Quotas will make unified storage impose resource limits on a namespace. By default, the limit is 1000, but it can be overridden. To enable, create an empty overrides.yaml file in the grafana root directory. + +Then add the following to your grafana ini: +```ini +[feature_toggles] +kubernetesUnifiedStorageQuotas = true + +[unified_storage] +overrides_path = overrides.yaml +overrides_reload_period = 5s +``` + +To overrides the default quota for a tenant, add the following to the overrides.yaml file: +```yaml +overrides: + : + quotas: + .: + limit: 10 +``` +Unless otherwise set, the NAMESPACE when running locally is `default`. + +To access quotas, use the following API endpoint: +``` +GET /apis/quotas.grafana.app/v0alpha1/namespaces//usage?group=&resource= +``` + + ## Setting up search To enable it, add the following to your `custom.ini` under the `[feature_toggles]` and `[unified_storage]` sections: ```ini @@ -1317,4 +1346,34 @@ Key metrics for monitoring Unified Search: - `unified_search_shadow_requests_total`: Shadow traffic request counts - `unified_search_ring_members`: Number of active search server instances +## Data migrations +Unified storage includes an automated migration system that transfers resources from legacy SQL tables to unified storage. Migrations run automatically during Grafana startup when enabled. + +### Supported resources + +- Folders +- Dashboards +- Library panels +- Playlists + +### Validation + +Built-in validators ensure data integrity after migration: + +- **CountValidator**: Verifies resource counts match between legacy and unified storage +- **FolderTreeValidator**: Validates folder parent-child relationships are preserved + +### Configuration + +Enable migrations in `grafana.ini`: + +```ini +[unified_storage] +disable_data_migrations = false +``` + +### Documentation + +For detailed information about migration architecture, validators, and troubleshooting, refer to [migrations/README.md](./migrations/README.md). + \ No newline at end of file diff --git a/pkg/storage/unified/migrations/README.md b/pkg/storage/unified/migrations/README.md new file mode 100644 index 00000000000..b0c84d81678 --- /dev/null +++ b/pkg/storage/unified/migrations/README.md @@ -0,0 +1,122 @@ +# Unified storage data migrations + +Automated migration system for moving Grafana resources from legacy SQL storage to unified storage. + +## Overview + +The migration system transfers resources from legacy SQL tables to Grafana's unified storage backend. It runs automatically during Grafana startup and validates data integrity after each migration. + +### Supported resources + +| Resource | API Group | Legacy table | +|----------|-----------|--------------| +| Folders | `folder.grafana.app` | `dashboard` | +| Dashboards | `dashboard.grafana.app` | `dashboard` | +| Library panels | `dashboard.grafana.app` | `library_element` | +| Playlists | `playlist.grafana.app` | `playlist` | + +## Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ ResourceMigration │ +│ (Orchestrates per-organization migration) │ +└──────────────────────────┬──────────────────────────────────┘ + │ + ┌───────────────────┼───────────────────┐ + ▼ ▼ ▼ + UnifiedMigrator Validators BulkProcess API + (Stream legacy (Validate after (Write to unified + resources) migration) storage) +``` + +### Components + +- **`service.go`**: Migration service entry point and registration +- **`migrator.go`**: Core migration logic using streaming BulkProcess API +- **`resource_migration.go`**: Per-organization migration execution +- **`validator.go`**: Post-migration validation (CountValidator, FolderTreeValidator) +- **`resources.go`**: Registry of migratable resource types + +## How migrations work + +### Migration flow + +1. Grafana starts and checks migration status in `unifiedstorage_migration_log` table +2. For each organization, the migrator: + - Reads resources from legacy SQL tables + - Streams resources to unified storage via BulkProcess API + - Runs validators to verify data integrity +3. Records migration result in `unifiedstorage_migration_log` table + +### Per-organization execution + +Migrations run independently for each organization using namespace format `org-{orgId}`. + +## Validators + +### CountValidator + +Compares resource counts between legacy SQL and unified storage. Accounts for rejected items during validation. + +### FolderTreeValidator + +Verifies folder parent-child relationships are preserved after migration. + +## Configuration + +To enable migrations, set the following in your Grafana configuration: + +```ini +[unified_storage] +disable_data_migrations = false +``` + +## Monitoring + +### Log messages + +Successful migration: + +``` +info: storage.unified.resource_migration Starting migration for all organizations +info: storage.unified.resource_migration Migration completed successfully for all organizations +``` + +Failed migration: + +``` +error: storage.unified.resource_migration Migration validation failed +``` + +### Migration status + +Query the migration log table to check status: + +```sql +SELECT * FROM unifiedstorage_migration_log WHERE migration_id LIKE '%folders-dashboards%'; +``` + +The `migration_id` is defined in `service.go` during registration. Ideally, it should be the resource type(s) being migrated. + +## Development + +### Adding a new validator + +Implement the `Validator` interface: + +```go +type Validator interface { + Name() string + Validate(ctx context.Context, sess *xorm.Session, response *resourcepb.BulkResponse, log log.Logger) error +} +``` + +Register the validator in `service.go` when creating the `ResourceMigration`. + +### Adding a new resource type + +1. Add the resource definition to `registeredResources` in `resources.go` +2. Implement the migrator function in the `MigrationDashboardAccessor` interface +3. Register the migration in `service.go` + diff --git a/pkg/storage/unified/resource/data/sqlkv_delete.sql b/pkg/storage/unified/resource/data/sqlkv_delete.sql new file mode 100644 index 00000000000..60a60746993 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_delete.sql @@ -0,0 +1,3 @@ +DELETE +FROM {{ .Ident .TableName }} +WHERE {{ .Ident "key_path" }} = {{ .Arg .KeyPath }}; diff --git a/pkg/storage/unified/resource/data/sqlkv_get.sql b/pkg/storage/unified/resource/data/sqlkv_get.sql new file mode 100644 index 00000000000..48c83cf0450 --- /dev/null +++ b/pkg/storage/unified/resource/data/sqlkv_get.sql @@ -0,0 +1,3 @@ +SELECT {{ .Ident "value" | .Into .Value }} +FROM {{ .Ident .TableName }} +WHERE {{ .Ident "key_path" }} = {{ .Arg .KeyPath }}; diff --git a/pkg/storage/unified/resource/datastore_test.go b/pkg/storage/unified/resource/datastore_test.go index 8f167c2e16e..02c318fe6d9 100644 --- a/pkg/storage/unified/resource/datastore_test.go +++ b/pkg/storage/unified/resource/datastore_test.go @@ -9,6 +9,9 @@ import ( "testing" "github.com/bwmarrin/snowflake" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" "github.com/stretchr/testify/require" ) @@ -24,6 +27,16 @@ func TestNewDataStore(t *testing.T) { require.NotNil(t, ds) } +// nolint:unused +func setupTestDataStoreSqlKv(t *testing.T) *dataStore { + dbstore := db.InitTestDB(t) + eDB, err := dbimpl.ProvideResourceDB(dbstore, setting.NewCfg(), nil) + require.NoError(t, err) + kv, err := NewSQLKV(eDB) + require.NoError(t, err) + return newDataStore(kv) +} + func TestDataKey_String(t *testing.T) { rv := int64(1934555792099250176) tests := []struct { @@ -679,10 +692,21 @@ func TestParseKey(t *testing.T) { } } -func TestDataStore_Save_And_Get(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() +func runDataStoreTestWith(t *testing.T, storeName string, newStoreFn func(*testing.T) *dataStore, testFn func(*testing.T, context.Context, *dataStore)) { + t.Run(storeName, func(t *testing.T) { + ctx := context.Background() + store := newStoreFn(t) + testFn(t, ctx, store) + }) +} +func TestDataStore_Save_And_Get(t *testing.T) { + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreSaveAndGet) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreSaveAndGet) +} + +func testDataStoreSaveAndGet(t *testing.T, ctx context.Context, ds *dataStore) { rv := node.Generate() testKey := DataKey{ @@ -744,9 +768,12 @@ func TestDataStore_Save_And_Get(t *testing.T) { } func TestDataStore_Delete(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreDelete) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreDelete) +} +func testDataStoreDelete(t *testing.T, ctx context.Context, ds *dataStore) { rv := node.Generate() testKey := DataKey{ @@ -795,9 +822,12 @@ func TestDataStore_Delete(t *testing.T) { } func TestDataStore_List(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreList) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreList) +} +func testDataStoreList(t *testing.T, ctx context.Context, ds *dataStore) { resourceKey := ListRequestKey{ Namespace: "test-namespace", Group: "test-group", @@ -919,9 +949,12 @@ func TestDataStore_List(t *testing.T) { } func TestDataStore_Integration(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreIntegration) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreIntegration) +} +func testDataStoreIntegration(t *testing.T, ctx context.Context, ds *dataStore) { t.Run("full lifecycle test", func(t *testing.T) { resourceKey := ListRequestKey{ Namespace: "integration-ns", @@ -1007,9 +1040,12 @@ func TestDataStore_Integration(t *testing.T) { } func TestDataStore_Keys(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreKeys) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreKeys) +} +func testDataStoreKeys(t *testing.T, ctx context.Context, ds *dataStore) { resourceKey := ListRequestKey{ Namespace: "test-namespace", Group: "test-group", @@ -1154,9 +1190,12 @@ func TestDataStore_Keys(t *testing.T) { } func TestDataStore_ValidationEnforced(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreValidationEnforced) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreValidationEnforced) +} +func testDataStoreValidationEnforced(t *testing.T, ctx context.Context, ds *dataStore) { // Create an invalid key invalidKey := DataKey{ Namespace: "Invalid-Namespace-$$$", @@ -1483,9 +1522,12 @@ func TestListRequestKey_Prefix(t *testing.T) { } func TestDataStore_LastResourceVersion(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreLastResourceVersion) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreLastResourceVersion) +} +func testDataStoreLastResourceVersion(t *testing.T, ctx context.Context, ds *dataStore) { t.Run("returns last resource version for existing data", func(t *testing.T) { resourceKey := ListRequestKey{ Namespace: "test-namespace", @@ -1585,9 +1627,12 @@ func TestDataStore_LastResourceVersion(t *testing.T) { } func TestDataStore_GetLatestResourceKey(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetLatestResourceKey) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetLatestResourceKey) +} +func testDataStoreGetLatestResourceKey(t *testing.T, ctx context.Context, ds *dataStore) { key := GetRequestKey{ Group: "apps", Resource: "resources", @@ -1648,9 +1693,12 @@ func TestDataStore_GetLatestResourceKey(t *testing.T) { } func TestDataStore_GetLatestResourceKey_Deleted(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetLatestResourceKeyDeleted) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetLatestResourceKeyDeleted) +} +func testDataStoreGetLatestResourceKeyDeleted(t *testing.T, ctx context.Context, ds *dataStore) { key := GetRequestKey{ Group: "apps", Resource: "resources", @@ -1676,9 +1724,12 @@ func TestDataStore_GetLatestResourceKey_Deleted(t *testing.T) { } func TestDataStore_GetLatestResourceKey_NotFound(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetLatestResourceKeyNotFound) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetLatestResourceKeyNotFound) +} +func testDataStoreGetLatestResourceKeyNotFound(t *testing.T, ctx context.Context, ds *dataStore) { key := GetRequestKey{ Group: "apps", Resource: "resources", @@ -1691,9 +1742,12 @@ func TestDataStore_GetLatestResourceKey_NotFound(t *testing.T) { } func TestDataStore_GetResourceKeyAtRevision(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetResourceKeyAtRevision) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetResourceKeyAtRevision) +} +func testDataStoreGetResourceKeyAtRevision(t *testing.T, ctx context.Context, ds *dataStore) { key := GetRequestKey{ Group: "apps", Resource: "resources", @@ -1766,9 +1820,12 @@ func TestDataStore_GetResourceKeyAtRevision(t *testing.T) { } func TestDataStore_ListLatestResourceKeys(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListLatestResourceKeys) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListLatestResourceKeys) +} +func testDataStoreListLatestResourceKeys(t *testing.T, ctx context.Context, ds *dataStore) { listKey := ListRequestKey{ Group: "apps", Resource: "resources", @@ -1819,9 +1876,12 @@ func TestDataStore_ListLatestResourceKeys(t *testing.T) { } func TestDataStore_ListLatestResourceKeys_Deleted(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListLatestResourceKeysDeleted) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListLatestResourceKeysDeleted) +} +func testDataStoreListLatestResourceKeysDeleted(t *testing.T, ctx context.Context, ds *dataStore) { listKey := ListRequestKey{ Group: "apps", Resource: "resources", @@ -1869,9 +1929,12 @@ func TestDataStore_ListLatestResourceKeys_Deleted(t *testing.T) { } func TestDataStore_ListLatestResourceKeys_Multiple(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListLatestResourceKeysMultiple) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListLatestResourceKeysMultiple) +} +func testDataStoreListLatestResourceKeysMultiple(t *testing.T, ctx context.Context, ds *dataStore) { listKey := ListRequestKey{ Group: "apps", Resource: "resources", @@ -1940,9 +2003,12 @@ func TestDataStore_ListLatestResourceKeys_Multiple(t *testing.T) { } func TestDataStore_ListResourceKeysAtRevision(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListResourceKeysAtRevision) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListResourceKeysAtRevision) +} +func testDataStoreListResourceKeysAtRevision(t *testing.T, ctx context.Context, ds *dataStore) { // Create multiple resources with different versions rv1 := node.Generate().Int64() rv2 := node.Generate().Int64() @@ -2152,9 +2218,12 @@ func TestDataStore_ListResourceKeysAtRevision(t *testing.T) { } func TestDataStore_ListResourceKeysAtRevision_ValidationErrors(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListResourceKeysAtRevisionValidationErrors) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListResourceKeysAtRevisionValidationErrors) +} +func testDataStoreListResourceKeysAtRevisionValidationErrors(t *testing.T, ctx context.Context, ds *dataStore) { tests := []struct { name string key ListRequestKey @@ -2194,9 +2263,12 @@ func TestDataStore_ListResourceKeysAtRevision_ValidationErrors(t *testing.T) { } func TestDataStore_ListResourceKeysAtRevision_EmptyResults(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListResourceKeysAtRevisionEmptyResults) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListResourceKeysAtRevisionEmptyResults) +} +func testDataStoreListResourceKeysAtRevisionEmptyResults(t *testing.T, ctx context.Context, ds *dataStore) { listKey := ListRequestKey{ Group: "apps", Resource: "resources", @@ -2213,9 +2285,12 @@ func TestDataStore_ListResourceKeysAtRevision_EmptyResults(t *testing.T) { } func TestDataStore_ListResourceKeysAtRevision_ResourcesNewerThanRevision(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreListResourceKeysAtRevisionResourcesNewerThanRevision) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreListResourceKeysAtRevisionResourcesNewerThanRevision) +} +func testDataStoreListResourceKeysAtRevisionResourcesNewerThanRevision(t *testing.T, ctx context.Context, ds *dataStore) { // Create a resource with a high resource version rv := node.Generate().Int64() key := DataKey{ @@ -2681,9 +2756,12 @@ func TestGetRequestKey_Prefix(t *testing.T) { } func TestDataStore_GetResourceStats_Comprehensive(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetResourceStatsComprehensive) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetResourceStatsComprehensive) +} +func testDataStoreGetResourceStatsComprehensive(t *testing.T, ctx context.Context, ds *dataStore) { // Test setup: 3 namespaces × 3 groups × 3 resources × 3 names × 3 versions = 243 total entries // But each name will have only 1 latest version that counts, so 3 × 3 × 3 × 3 = 81 non-deleted resources namespaces := []string{"ns1", "ns2", "ns3"} @@ -2888,9 +2966,12 @@ func TestDataStore_GetResourceStats_Comprehensive(t *testing.T) { } func TestDataStore_getGroupResources(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetGroupResources) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetGroupResources) +} +func testDataStoreGetGroupResources(t *testing.T, ctx context.Context, ds *dataStore) { // Create test data with multiple group/resource combinations testData := []struct { group string @@ -2951,9 +3032,12 @@ func TestDataStore_getGroupResources(t *testing.T) { } func TestDataStore_BatchDelete(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreBatchDelete) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreBatchDelete) +} +func testDataStoreBatchDelete(t *testing.T, ctx context.Context, ds *dataStore) { keys := make([]DataKey, 95) for i := 0; i < 95; i++ { rv := node.Generate().Int64() @@ -2987,9 +3071,12 @@ func TestDataStore_BatchDelete(t *testing.T) { } func TestDataStore_BatchGet(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreBatchGet) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreBatchGet) +} +func testDataStoreBatchGet(t *testing.T, ctx context.Context, ds *dataStore) { t.Run("batch get multiple existing keys", func(t *testing.T) { // Create test data keys := make([]DataKey, 5) @@ -3132,9 +3219,12 @@ func TestDataStore_BatchGet(t *testing.T) { } func TestDataStore_GetLatestAndPredecessor(t *testing.T) { - ds := setupTestDataStore(t) - ctx := context.Background() + runDataStoreTestWith(t, "badger", setupTestDataStore, testDataStoreGetLatestAndPredecessor) + // enable this when sqlkv is ready + // runDataStoreTestWith(t, "sqlkv", setupTestDataStoreSqlKv, testDataStoreGetLatestAndPredecessor) +} +func testDataStoreGetLatestAndPredecessor(t *testing.T, ctx context.Context, ds *dataStore) { resourceKey := ListRequestKey{ Namespace: "test-namespace", Group: "test-group", diff --git a/pkg/storage/unified/resource/eventstore_test.go b/pkg/storage/unified/resource/eventstore_test.go index a9d2ee93eb4..270db1ddd3f 100644 --- a/pkg/storage/unified/resource/eventstore_test.go +++ b/pkg/storage/unified/resource/eventstore_test.go @@ -7,6 +7,10 @@ import ( "time" "github.com/bwmarrin/snowflake" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" + "github.com/grafana/grafana/pkg/tests/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -21,6 +25,20 @@ func setupTestEventStore(t *testing.T) *eventStore { return newEventStore(kv) } +func TestMain(m *testing.M) { + testsuite.Run(m) +} + +// nolint:unused +func setupTestEventStoreSqlKv(t *testing.T) *eventStore { + dbstore := db.InitTestDB(t) + eDB, err := dbimpl.ProvideResourceDB(dbstore, setting.NewCfg(), nil) + require.NoError(t, err) + kv, err := NewSQLKV(eDB) + require.NoError(t, err) + return newEventStore(kv) +} + func TestNewEventStore(t *testing.T) { store := setupTestEventStore(t) assert.NotNil(t, store.kv) @@ -180,10 +198,21 @@ func TestEventStore_ParseEventKey(t *testing.T) { assert.Equal(t, originalKey, parsedKey) } -func TestEventStore_Save_Get(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) +func runEventStoreTestWith(t *testing.T, storeName string, newStoreFn func(*testing.T) *eventStore, testFn func(*testing.T, context.Context, *eventStore)) { + t.Run(storeName, func(t *testing.T) { + ctx := context.Background() + store := newStoreFn(t) + testFn(t, ctx, store) + }) +} +func TestEventStore_Save_Get(t *testing.T) { + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreSaveGet) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreSaveGet) +} + +func testEventStoreSaveGet(t *testing.T, ctx context.Context, store *eventStore) { event := Event{ Namespace: "default", Group: "apps", @@ -216,9 +245,12 @@ func TestEventStore_Save_Get(t *testing.T) { } func TestEventStore_Get_NotFound(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreGetNotFound) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreGetNotFound) +} +func testEventStoreGetNotFound(t *testing.T, ctx context.Context, store *eventStore) { nonExistentKey := EventKey{ Namespace: "default", Group: "apps", @@ -233,9 +265,12 @@ func TestEventStore_Get_NotFound(t *testing.T) { } func TestEventStore_LastEventKey(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreLastEventKey) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreLastEventKey) +} +func testEventStoreLastEventKey(t *testing.T, ctx context.Context, store *eventStore) { // Test when no events exist _, err := store.LastEventKey(ctx) assert.Error(t, err) @@ -292,9 +327,12 @@ func TestEventStore_LastEventKey(t *testing.T) { } func TestEventStore_ListKeysSince(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreListKeysSince) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreListKeysSince) +} +func testEventStoreListKeysSince(t *testing.T, ctx context.Context, store *eventStore) { // Add events with different resource versions events := []Event{ { @@ -349,9 +387,12 @@ func TestEventStore_ListKeysSince(t *testing.T) { } func TestEventStore_ListSince(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreListSince) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreListSince) +} +func testEventStoreListSince(t *testing.T, ctx context.Context, store *eventStore) { // Add events with different resource versions events := []Event{ { @@ -404,9 +445,12 @@ func TestEventStore_ListSince(t *testing.T) { } func TestEventStore_ListSince_Empty(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreListSinceEmpty) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreListSinceEmpty) +} +func testEventStoreListSinceEmpty(t *testing.T, ctx context.Context, store *eventStore) { // List events when store is empty retrievedEvents := make([]Event, 0) for event, err := range store.ListSince(ctx, 0) { @@ -459,9 +503,12 @@ func TestEventKey_Struct(t *testing.T) { } func TestEventStore_Save_InvalidJSON(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreSaveInvalidJSON) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreSaveInvalidJSON) +} +func testEventStoreSaveInvalidJSON(t *testing.T, ctx context.Context, store *eventStore) { // This should work fine as the Event struct should be serializable event := Event{ Namespace: "default", @@ -477,9 +524,12 @@ func TestEventStore_Save_InvalidJSON(t *testing.T) { } func TestEventStore_CleanupOldEvents(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreCleanupOldEvents) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreCleanupOldEvents) +} +func testEventStoreCleanupOldEvents(t *testing.T, ctx context.Context, store *eventStore) { now := time.Now() oldRV := snowflakeFromTime(now.Add(-48 * time.Hour)) // 48 hours ago recentRV := snowflakeFromTime(now.Add(-1 * time.Hour)) // 1 hour ago @@ -565,9 +615,12 @@ func TestEventStore_CleanupOldEvents(t *testing.T) { } func TestEventStore_CleanupOldEvents_NoOldEvents(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreCleanupOldEventsNoOldEvents) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreCleanupOldEventsNoOldEvents) +} +func testEventStoreCleanupOldEventsNoOldEvents(t *testing.T, ctx context.Context, store *eventStore) { // Create an event 1 hour old rv := snowflakeFromTime(time.Now().Add(-1 * time.Hour)) event := Event{ @@ -603,9 +656,12 @@ func TestEventStore_CleanupOldEvents_NoOldEvents(t *testing.T) { } func TestEventStore_CleanupOldEvents_EmptyStore(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreCleanupOldEventsEmptyStore) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreCleanupOldEventsEmptyStore) +} +func testEventStoreCleanupOldEventsEmptyStore(t *testing.T, ctx context.Context, store *eventStore) { // Clean up events from empty store deletedCount, err := store.CleanupOldEvents(ctx, time.Now().Add(-24*time.Hour)) require.NoError(t, err) @@ -613,9 +669,12 @@ func TestEventStore_CleanupOldEvents_EmptyStore(t *testing.T) { } func TestEventStore_BatchDelete(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testEventStoreBatchDelete) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testEventStoreBatchDelete) +} +func testEventStoreBatchDelete(t *testing.T, ctx context.Context, store *eventStore) { // Create multiple events (more than batch size to test batching) eventKeys := make([]string, 75) for i := 0; i < 75; i++ { @@ -722,9 +781,12 @@ func TestSnowflakeFromTime(t *testing.T) { } func TestListKeysSince_WithSnowflakeTime(t *testing.T) { - ctx := context.Background() - store := setupTestEventStore(t) + runEventStoreTestWith(t, "badger", setupTestEventStore, testListKeysSinceWithSnowflakeTime) + // enable this when sqlkv is ready + // runEventStoreTestWith(t, "sqlkv", setupTestEventStoreSqlKv, testListKeysSinceWithSnowflakeTime) +} +func testListKeysSinceWithSnowflakeTime(t *testing.T, ctx context.Context, store *eventStore) { // Create events with snowflake-based resource versions at different times now := time.Now() events := []Event{ diff --git a/pkg/storage/unified/resource/fieldSelector.go b/pkg/storage/unified/resource/fieldSelector.go new file mode 100644 index 00000000000..034085ca07f --- /dev/null +++ b/pkg/storage/unified/resource/fieldSelector.go @@ -0,0 +1,53 @@ +package resource + +import ( + "context" + + "github.com/grafana/grafana/pkg/storage/unified/resourcepb" +) + +// Some list queries can be calculated with simple reads or search index +func (s *server) tryFieldSelector(ctx context.Context, req *resourcepb.ListRequest) *resourcepb.ListResponse { + if req.Source != resourcepb.ListRequest_STORE || req.Options.Key.Namespace == "" { + return nil + } + + var names []string + for _, v := range req.Options.Fields { + if v.Key == "metadata.name" && v.Operator == `=` { + names = v.Values + continue + } + + // TODO: support other field selectors + } + + // The required names + if len(names) > 0 { + read := &resourcepb.ReadRequest{ + Key: req.Options.Key, + ResourceVersion: req.ResourceVersion, + } + rsp := &resourcepb.ListResponse{ + ResourceVersion: 1, // TODO, search result should include when it was indexed + } + for _, name := range names { + read.Key.Name = name + found, err := s.Read(ctx, read) + if err != nil { + return &resourcepb.ListResponse{Error: AsErrorResult(err)} + } + if len(found.Value) > 0 { + rsp.Items = append(rsp.Items, &resourcepb.ResourceWrapper{ + Value: found.Value, + ResourceVersion: found.ResourceVersion, + }) + if found.ResourceVersion > rsp.ResourceVersion { + rsp.ResourceVersion = found.ResourceVersion + } + } + } + return rsp + } + return nil +} diff --git a/pkg/storage/unified/resource/kv.go b/pkg/storage/unified/resource/kv.go index 043ea45f695..0bd413254a4 100644 --- a/pkg/storage/unified/resource/kv.go +++ b/pkg/storage/unified/resource/kv.go @@ -87,6 +87,9 @@ func (k *badgerKV) Get(ctx context.Context, section string, key string) (io.Read if section == "" { return nil, fmt.Errorf("section is required") } + if key == "" { + return nil, fmt.Errorf("key is required") + } key = section + "/" + key @@ -225,6 +228,9 @@ func (k *badgerKV) Delete(ctx context.Context, section string, key string) error if section == "" { return fmt.Errorf("section is required") } + if key == "" { + return fmt.Errorf("key is required") + } txn := k.db.NewTransaction(true) defer txn.Discard() diff --git a/pkg/storage/unified/resource/notifier_test.go b/pkg/storage/unified/resource/notifier_test.go index 7b201f47420..060f8eecfbe 100644 --- a/pkg/storage/unified/resource/notifier_test.go +++ b/pkg/storage/unified/resource/notifier_test.go @@ -6,6 +6,9 @@ import ( "time" "github.com/grafana/grafana-app-sdk/logging" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -22,6 +25,18 @@ func setupTestNotifier(t *testing.T) (*notifier, *eventStore) { return notifier, eventStore } +// nolint:unused +func setupTestNotifierSqlKv(t *testing.T) (*notifier, *eventStore) { + dbstore := db.InitTestDB(t) + eDB, err := dbimpl.ProvideResourceDB(dbstore, setting.NewCfg(), nil) + require.NoError(t, err) + kv, err := NewSQLKV(eDB) + require.NoError(t, err) + eventStore := newEventStore(kv) + notifier := newNotifier(eventStore, notifierOptions{log: &logging.NoOpLogger{}}) + return notifier, eventStore +} + func TestNewNotifier(t *testing.T) { notifier, _ := setupTestNotifier(t) @@ -35,10 +50,21 @@ func TestDefaultWatchOptions(t *testing.T) { assert.Equal(t, defaultBufferSize, opts.BufferSize) } -func TestNotifier_lastEventResourceVersion(t *testing.T) { - ctx := context.Background() - notifier, eventStore := setupTestNotifier(t) +func runNotifierTestWith(t *testing.T, storeName string, newStoreFn func(*testing.T) (*notifier, *eventStore), testFn func(*testing.T, context.Context, *notifier, *eventStore)) { + t.Run(storeName, func(t *testing.T) { + ctx := context.Background() + notifier, eventStore := newStoreFn(t) + testFn(t, ctx, notifier, eventStore) + }) +} +func TestNotifier_lastEventResourceVersion(t *testing.T) { + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierLastEventResourceVersion) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierLastEventResourceVersion) +} + +func testNotifierLastEventResourceVersion(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { // Test with no events rv, err := notifier.lastEventResourceVersion(ctx) assert.Error(t, err) @@ -85,8 +111,12 @@ func TestNotifier_lastEventResourceVersion(t *testing.T) { } func TestNotifier_cachekey(t *testing.T) { - notifier, _ := setupTestNotifier(t) + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierCachekey) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierCachekey) +} +func testNotifierCachekey(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { tests := []struct { name string event Event @@ -136,10 +166,14 @@ func TestNotifier_cachekey(t *testing.T) { } func TestNotifier_Watch_NoEvents(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) - defer cancel() + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierWatchNoEvents) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierWatchNoEvents) +} - notifier, eventStore := setupTestNotifier(t) +func testNotifierWatchNoEvents(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { + ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) + defer cancel() // Add at least one event so that lastEventResourceVersion doesn't return ErrNotFound initialEvent := Event{ @@ -174,10 +208,14 @@ func TestNotifier_Watch_NoEvents(t *testing.T) { } func TestNotifier_Watch_WithExistingEvents(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierWatchWithExistingEvents) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierWatchWithExistingEvents) +} - notifier, eventStore := setupTestNotifier(t) +func testNotifierWatchWithExistingEvents(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() // Save some initial events initialEvents := []Event{ @@ -245,10 +283,14 @@ func TestNotifier_Watch_WithExistingEvents(t *testing.T) { } func TestNotifier_Watch_EventDeduplication(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierWatchEventDeduplication) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierWatchEventDeduplication) +} - notifier, eventStore := setupTestNotifier(t) +func testNotifierWatchEventDeduplication(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() // Add an initial event so that lastEventResourceVersion doesn't return ErrNotFound initialEvent := Event{ @@ -308,9 +350,13 @@ func TestNotifier_Watch_EventDeduplication(t *testing.T) { } func TestNotifier_Watch_ContextCancellation(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierWatchContextCancellation) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierWatchContextCancellation) +} - notifier, eventStore := setupTestNotifier(t) +func testNotifierWatchContextCancellation(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { + ctx, cancel := context.WithCancel(ctx) // Add an initial event so that lastEventResourceVersion doesn't return ErrNotFound initialEvent := Event{ @@ -351,10 +397,14 @@ func TestNotifier_Watch_ContextCancellation(t *testing.T) { } func TestNotifier_Watch_MultipleEvents(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() + runNotifierTestWith(t, "badger", setupTestNotifier, testNotifierWatchMultipleEvents) + // enable this when sqlkv is ready + // runNotifierTestWith(t, "sqlkv", setupTestNotifierSqlKv, testNotifierWatchMultipleEvents) +} - notifier, eventStore := setupTestNotifier(t) +func testNotifierWatchMultipleEvents(t *testing.T, ctx context.Context, notifier *notifier, eventStore *eventStore) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() rv := time.Now().UnixNano() // Add an initial event so that lastEventResourceVersion doesn't return ErrNotFound initialEvent := Event{ diff --git a/pkg/storage/unified/resource/quotas.go b/pkg/storage/unified/resource/quotas.go index d956a6da017..03fe515559e 100644 --- a/pkg/storage/unified/resource/quotas.go +++ b/pkg/storage/unified/resource/quotas.go @@ -47,13 +47,14 @@ type Overrides struct { /* This service loads overrides (currently just quotas) from a YAML file with the following yaml structure: -"123": +overrides: + "123": quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 1500 + dashboard.grafana.app/dashboards: + limit: 1500 + folder.grafana.app/folders: + limit: 1500 */ func NewOverridesService(_ context.Context, logger log.Logger, reg prometheus.Registerer, tracer trace.Tracer, opts ReloadOptions) (*OverridesService, error) { // shouldn't be empty since we use file path existence to determine if we should enable the service @@ -76,12 +77,14 @@ func NewOverridesService(_ context.Context, logger log.Logger, reg prometheus.Re ReloadPeriod: opts.ReloadPeriod, LoadPath: []string{opts.FilePath}, Loader: func(r io.Reader) (interface{}, error) { - var tenants map[string]NamespaceOverrides + var raw struct { + Overrides map[string]NamespaceOverrides `yaml:"overrides"` + } decoder := yaml.NewDecoder(r) - if err := decoder.Decode(&tenants); err != nil { + if err := decoder.Decode(&raw); err != nil { return nil, err } - return &Overrides{Namespaces: tenants}, nil + return &Overrides{Namespaces: raw.Overrides}, nil }, } diff --git a/pkg/storage/unified/resource/quotas_test.go b/pkg/storage/unified/resource/quotas_test.go index 97f9f355af6..097a02d7444 100644 --- a/pkg/storage/unified/resource/quotas_test.go +++ b/pkg/storage/unified/resource/quotas_test.go @@ -27,10 +27,11 @@ func TestNewQuotaService(t *testing.T) { opts: ReloadOptions{}, setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -105,10 +106,11 @@ func TestQuotaService_ConfigReload(t *testing.T) { // Create a temporary config file tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - initialConfig := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + initialConfig := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(initialConfig), 0644)) @@ -139,14 +141,15 @@ func TestQuotaService_ConfigReload(t *testing.T) { assert.Equal(t, 1500, quota.Limit, "initial quota should be 1500") // Update the config file with new values - updatedConfig := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 2500 -"456": - quotas: - grafana.folder.app/folders: - limit: 3000 + updatedConfig := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 2500 + "456": + quotas: + grafana.folder.app/folders: + limit: 3000 ` require.NoError(t, os.WriteFile(tmpFile, []byte(updatedConfig), 0644)) @@ -183,10 +186,11 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns custom quota for matching tenant and resource", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -204,10 +208,11 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns default quota when tenant not found", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -225,10 +230,11 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns default quota when resource not found", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -246,10 +252,11 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "handles namespace without stacks- prefix", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -284,12 +291,13 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "handles multiple resources for same tenant", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 2500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 + grafana.folder.app/folders: + limit: 2500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -307,12 +315,13 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns error when namespace is empty", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 2500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 + grafana.folder.app/folders: + limit: 2500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -330,12 +339,13 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns error when group is empty", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 2500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 + grafana.folder.app/folders: + limit: 2500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -353,12 +363,13 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns error when resource is empty", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 2500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 + grafana.folder.app/folders: + limit: 2500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile @@ -376,12 +387,13 @@ func TestQuotaService_GetQuota(t *testing.T) { name: "returns error when all fields are empty", setupFile: func(t *testing.T) string { tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - grafana.dashboard.app/dashboards: - limit: 1500 - grafana.folder.app/folders: - limit: 2500 + content := `overrides: + "123": + quotas: + grafana.dashboard.app/dashboards: + limit: 1500 + grafana.folder.app/folders: + limit: 2500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) return tmpFile diff --git a/pkg/storage/unified/resource/server.go b/pkg/storage/unified/resource/server.go index c4052938603..7c890e72b00 100644 --- a/pkg/storage/unified/resource/server.go +++ b/pkg/storage/unified/resource/server.go @@ -1039,7 +1039,7 @@ func (s *server) List(ctx context.Context, req *resourcepb.ListRequest) (*resour } // Fast path for getting single value in a list - if rsp := s.tryFastPathList(ctx, req); rsp != nil { + if rsp := s.tryFieldSelector(ctx, req); rsp != nil { return rsp, nil } @@ -1137,40 +1137,6 @@ func (s *server) List(ctx context.Context, req *resourcepb.ListRequest) (*resour return rsp, err } -// Some list queries can be calculated with simple reads -func (s *server) tryFastPathList(ctx context.Context, req *resourcepb.ListRequest) *resourcepb.ListResponse { - if req.Source != resourcepb.ListRequest_STORE || req.Options.Key.Namespace == "" { - return nil - } - - for _, v := range req.Options.Fields { - if v.Key == "metadata.name" && v.Operator == `=` { - if len(v.Values) == 1 { - read := &resourcepb.ReadRequest{ - Key: req.Options.Key, - ResourceVersion: req.ResourceVersion, - } - read.Key.Name = v.Values[0] - found, err := s.Read(ctx, read) - if err != nil { - return &resourcepb.ListResponse{Error: AsErrorResult(err)} - } - - // Return a value when it exists - rsp := &resourcepb.ListResponse{} - if len(found.Value) > 0 { - rsp.Items = []*resourcepb.ResourceWrapper{{ - Value: found.Value, - ResourceVersion: found.ResourceVersion, - }} - } - return rsp - } - } - } - return nil -} - // isTrashItemAuthorized checks if the user has access to the trash item. func (s *server) isTrashItemAuthorized(ctx context.Context, iter ListIterator, trashChecker claims.ItemChecker) bool { user, ok := claims.AuthInfoFrom(ctx) diff --git a/pkg/storage/unified/resource/server_test.go b/pkg/storage/unified/resource/server_test.go index b4ab0cdff2a..0b0bbcfba13 100644 --- a/pkg/storage/unified/resource/server_test.go +++ b/pkg/storage/unified/resource/server_test.go @@ -643,10 +643,11 @@ func TestGetQuotaUsage(t *testing.T) { t.Run("returns usage and limit successfully", func(t *testing.T) { // Create a temporary overrides config file tmpFile := filepath.Join(t.TempDir(), "overrides.yaml") - content := `"123": - quotas: - dashboard.grafana.app/dashboards: - limit: 500 + content := `overrides: + "123": + quotas: + dashboard.grafana.app/dashboards: + limit: 500 ` require.NoError(t, os.WriteFile(tmpFile, []byte(content), 0644)) diff --git a/pkg/storage/unified/resource/sqlkv.go b/pkg/storage/unified/resource/sqlkv.go new file mode 100644 index 00000000000..90171a77a5f --- /dev/null +++ b/pkg/storage/unified/resource/sqlkv.go @@ -0,0 +1,223 @@ +package resource + +import ( + "bytes" + "context" + "database/sql" + "embed" + "errors" + "fmt" + "io" + "iter" + "text/template" + + "github.com/grafana/grafana/pkg/storage/unified/sql/db" + "github.com/grafana/grafana/pkg/storage/unified/sql/dbutil" + "github.com/grafana/grafana/pkg/storage/unified/sql/sqltemplate" +) + +// Templates setup. +var ( + //go:embed data/*.sql + sqlTemplatesFS embed.FS + + sqlTemplates = template.Must(template.New("sql").ParseFS(sqlTemplatesFS, `data/*.sql`)) +) + +func mustTemplate(filename string) *template.Template { + if t := sqlTemplates.Lookup(filename); t != nil { + return t + } + panic(fmt.Sprintf("template file not found: %s", filename)) +} + +// Templates. +var ( + sqlKVGet = mustTemplate("sqlkv_get.sql") + sqlKVDelete = mustTemplate("sqlkv_delete.sql") +) + +// sqlKVSection can be embedded in structs used when rendering query templates +// for queries that reference a particular section. The section will be validated, +// and the template can directly reference the `TableName`. +type sqlKVSection struct { + Section string +} + +func (req sqlKVSection) Validate() error { + if req.Section == "" { + return fmt.Errorf("section is required") + } + + if req.Section != dataSection && req.Section != eventsSection { + return fmt.Errorf("invalid section: %s", req.Section) + } + + return nil +} + +func (req sqlKVSection) TableName() string { + if req.Section == dataSection { + return "resource_history" + } + + return "resource_events" +} + +// sqlKVSectionKey can be embedded in structs used when rendering query templates +// for queries that reference both a section and a particular key. The `key` is +// validated, and the template can reference the corresponding `KeyPath`. +type sqlKVSectionKey struct { + sqlKVSection + Key string +} + +func (req sqlKVSectionKey) Validate() error { + if err := req.sqlKVSection.Validate(); err != nil { + return err + } + if req.Key == "" { + return fmt.Errorf("key is required") + } + + return nil +} + +func (req sqlKVSectionKey) KeyPath() string { + return req.Section + "/" + req.Key +} + +type sqlKVGetRequest struct { + sqltemplate.SQLTemplate + sqlKVSectionKey + *sqlKVGetResponse +} + +type sqlKVGetResponse struct { + Value []byte +} + +func (req sqlKVGetRequest) Validate() error { + return req.sqlKVSectionKey.Validate() +} + +func (req sqlKVGetRequest) Results() ([]byte, error) { + return req.Value, nil +} + +type sqlKVDeleteRequest struct { + sqltemplate.SQLTemplate + sqlKVSectionKey +} + +func (req sqlKVDeleteRequest) Validate() error { + return req.sqlKVSectionKey.Validate() +} + +var _ KV = &sqlKV{} + +type sqlKV struct { + dbProvider db.DBProvider + db db.DB + dialect sqltemplate.Dialect +} + +func NewSQLKV(dbProvider db.DBProvider) (KV, error) { + if dbProvider == nil { + return nil, fmt.Errorf("dbProvider is required") + } + + ctx := context.Background() + dbConn, err := dbProvider.Init(ctx) + if err != nil { + return nil, fmt.Errorf("error initializing DB: %w", err) + } + + dialect := sqltemplate.DialectForDriver(dbConn.DriverName()) + if dialect == nil { + return nil, fmt.Errorf("unsupported database driver: %s", dbConn.DriverName()) + } + + return &sqlKV{ + dbProvider: dbProvider, + db: dbConn, + dialect: dialect, + }, nil +} + +func (k *sqlKV) Ping(ctx context.Context) error { + return k.db.PingContext(ctx) +} + +func (k *sqlKV) Keys(ctx context.Context, section string, opt ListOptions) iter.Seq2[string, error] { + return func(yield func(string, error) bool) { + panic("not implemented!") + } +} + +func (k *sqlKV) Get(ctx context.Context, section string, key string) (io.ReadCloser, error) { + value, err := dbutil.QueryRow(ctx, k.db, sqlKVGet, sqlKVGetRequest{ + SQLTemplate: sqltemplate.New(k.dialect), + sqlKVSectionKey: sqlKVSectionKey{sqlKVSection{section}, key}, + sqlKVGetResponse: new(sqlKVGetResponse), + }) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return nil, fmt.Errorf("failed to get key: %w", err) + } + + return io.NopCloser(bytes.NewReader(value)), nil +} + +func (k *sqlKV) BatchGet(ctx context.Context, section string, keys []string) iter.Seq2[KeyValue, error] { + return func(yield func(KeyValue, error) bool) { + panic("not implemented!") + } +} + +// TODO: this function only exists to support the testing of the sqlkv implementation before +// we have a proper implementation of `Save`. +func (k *sqlKV) TestingSave(ctx context.Context, key string, value []byte) error { + stmt := fmt.Sprintf( + `INSERT INTO resource_events (key_path, value) VALUES (%s, %s)`, + k.dialect.ArgPlaceholder(1), k.dialect.ArgPlaceholder(2), + ) + + _, err := k.db.ExecContext(ctx, stmt, eventsSection+"/"+key, value) + return err +} + +func (k *sqlKV) Save(ctx context.Context, section string, key string) (io.WriteCloser, error) { + panic("not implemented!") +} + +func (k *sqlKV) Delete(ctx context.Context, section string, key string) error { + res, err := dbutil.Exec(ctx, k.db, sqlKVDelete, sqlKVDeleteRequest{ + SQLTemplate: sqltemplate.New(k.dialect), + sqlKVSectionKey: sqlKVSectionKey{sqlKVSection{section}, key}, + }) + if err != nil { + return fmt.Errorf("failed to delete key: %w", err) + } + + rows, err := res.RowsAffected() + if err != nil { + return fmt.Errorf("failed to validate delete: %w", err) + } + + if rows == 0 { + return ErrNotFound + } + + return nil +} + +func (k *sqlKV) BatchDelete(ctx context.Context, section string, keys []string) error { + panic("not implemented!") +} + +func (k *sqlKV) UnixTimestamp(ctx context.Context) (int64, error) { + panic("not implemented!") +} diff --git a/pkg/storage/unified/resource/storage_backend.go b/pkg/storage/unified/resource/storage_backend.go index 0de97b0355e..b0f51702775 100644 --- a/pkg/storage/unified/resource/storage_backend.go +++ b/pkg/storage/unified/resource/storage_backend.go @@ -70,7 +70,12 @@ type kvStorageBackend struct { //reg prometheus.Registerer } -var _ StorageBackend = &kvStorageBackend{} +var _ KVBackend = &kvStorageBackend{} + +type KVBackend interface { + StorageBackend + resourcepb.DiagnosticsServer +} type KVBackendOptions struct { KvStore KV @@ -82,7 +87,7 @@ type KVBackendOptions struct { Reg prometheus.Registerer // TODO add metrics } -func NewKVStorageBackend(opts KVBackendOptions) (StorageBackend, error) { +func NewKVStorageBackend(opts KVBackendOptions) (KVBackend, error) { ctx := context.Background() kv := opts.KvStore @@ -126,6 +131,18 @@ func NewKVStorageBackend(opts KVBackendOptions) (StorageBackend, error) { return backend, nil } +func (k *kvStorageBackend) IsHealthy(ctx context.Context, _ *resourcepb.HealthCheckRequest) (*resourcepb.HealthCheckResponse, error) { + type pinger interface { + Ping(context.Context) error + } + if p, ok := k.kv.(pinger); ok { + if err := p.Ping(ctx); err != nil { + return &resourcepb.HealthCheckResponse{Status: resourcepb.HealthCheckResponse_NOT_SERVING}, fmt.Errorf("KV store health check failed: %w", err) + } + } + return &resourcepb.HealthCheckResponse{Status: resourcepb.HealthCheckResponse_SERVING}, nil +} + // runCleanupOldEvents starts a background goroutine that periodically cleans up old events func (k *kvStorageBackend) runCleanupOldEvents(ctx context.Context) { // Run cleanup every hour diff --git a/pkg/storage/unified/search/builders/document_test.go b/pkg/storage/unified/search/builders/document_test.go index 6c8d02d6cb8..5fcae177696 100644 --- a/pkg/storage/unified/search/builders/document_test.go +++ b/pkg/storage/unified/search/builders/document_test.go @@ -53,8 +53,9 @@ func TestUserDocumentBuilder(t *testing.T) { Group: "iam.grafana.app", Resource: "users", }, []string{ - "user-with-login-and-email", - "user-with-login-only", + "with-login-and-email", + "with-login-only", + "with-last-seen-at-and-role", }) } diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role-out.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role-out.json new file mode 100644 index 00000000000..84e06fd5b90 --- /dev/null +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role-out.json @@ -0,0 +1,16 @@ +{ + "key": { + "namespace": "default", + "group": "iam.grafana.app", + "resource": "users", + "name": "with-last-seen-at-and-role" + }, + "name": "with-last-seen-at-and-role", + "rv": 1234, + "fields": { + "email": "user.three@test.com", + "lastSeenAt": 1698321600, + "login": "user.three", + "role": "Editor" + } +} diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role.json new file mode 100644 index 00000000000..fdd964240a6 --- /dev/null +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-last-seen-at-and-role.json @@ -0,0 +1,14 @@ +{ + "metadata": { + "name": "with-last-seen-at-and-role", + "namespace": "default" + }, + "spec": { + "login": "user.three", + "email": "user.three@test.com", + "role": "Editor" + }, + "status": { + "lastSeenAt": 1698321600 + } +} diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email-out.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email-out.json similarity index 55% rename from pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email-out.json rename to pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email-out.json index b7f75247149..04fd081d011 100644 --- a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email-out.json +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email-out.json @@ -3,12 +3,14 @@ "namespace": "default", "group": "iam.grafana.app", "resource": "users", - "name": "user-with-login-and-email" + "name": "with-login-and-email" }, - "name": "user-with-login-and-email", + "name": "with-login-and-email", "rv": 1234, "fields": { "email": "user.one@test.com", - "login": "user.one" + "lastSeenAt": 0, + "login": "user.one", + "role": "Viewer" } } \ No newline at end of file diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email.json similarity index 79% rename from pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email.json rename to pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email.json index a7eebbc754a..894bf6e977b 100644 --- a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-and-email.json +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-and-email.json @@ -1,6 +1,6 @@ { "metadata": { - "name": "user-with-login-and-email", + "name": "with-login-and-email", "namespace": "default" }, "spec": { diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only-out.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-only-out.json similarity index 51% rename from pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only-out.json rename to pkg/storage/unified/search/builders/testdata/doc/user-with-login-only-out.json index 7672d4b2a09..3aeaeec020e 100644 --- a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only-out.json +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-only-out.json @@ -3,11 +3,13 @@ "namespace": "default", "group": "iam.grafana.app", "resource": "users", - "name": "user-with-login-only" + "name": "with-login-only" }, - "name": "user-with-login-only", + "name": "with-login-only", "rv": 1234, "fields": { - "login": "user.two" + "lastSeenAt": 0, + "login": "user.two", + "role": "Viewer" } } \ No newline at end of file diff --git a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only.json b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-only.json similarity index 77% rename from pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only.json rename to pkg/storage/unified/search/builders/testdata/doc/user-with-login-only.json index 6b3adf2dc1d..affbe8a9c5e 100644 --- a/pkg/storage/unified/search/builders/testdata/doc/user-user-with-login-only.json +++ b/pkg/storage/unified/search/builders/testdata/doc/user-with-login-only.json @@ -1,6 +1,6 @@ { "metadata": { - "name": "user-with-login-only", + "name": "with-login-only", "namespace": "default" }, "spec": { diff --git a/pkg/storage/unified/search/builders/user.go b/pkg/storage/unified/search/builders/user.go index b17cdb99b15..c18c9d33cdc 100644 --- a/pkg/storage/unified/search/builders/user.go +++ b/pkg/storage/unified/search/builders/user.go @@ -12,10 +12,20 @@ import ( ) const ( - USER_EMAIL = "email" - USER_LOGIN = "login" + USER_EMAIL = "email" + USER_LOGIN = "login" + USER_LAST_SEEN_AT = "lastSeenAt" + USER_ROLE = "role" ) +// UserSortableExtraFields are the additional fields that can be used for sorting user search results. +// Should not include standard fields like title. +var UserSortableExtraFields = []string{ + USER_EMAIL, + USER_LOGIN, + USER_LAST_SEEN_AT, +} + var UserTableColumnDefinitions = map[string]*resourcepb.ResourceTableColumnDefinition{ USER_EMAIL: { Name: USER_EMAIL, @@ -35,6 +45,22 @@ var UserTableColumnDefinitions = map[string]*resourcepb.ResourceTableColumnDefin Filterable: true, }, }, + USER_LAST_SEEN_AT: { + Name: USER_LAST_SEEN_AT, + Type: resourcepb.ResourceTableColumnDefinition_INT64, + Description: "The last seen timestamp of the user", + Properties: &resourcepb.ResourceTableColumnDefinition_Properties{ + Filterable: true, + }, + }, + USER_ROLE: { + Name: USER_ROLE, + Type: resourcepb.ResourceTableColumnDefinition_STRING, + Description: "The role of the user", + Properties: &resourcepb.ResourceTableColumnDefinition_Properties{ + Filterable: true, + }, + }, } func GetUserBuilder() (resource.DocumentBuilderInfo, error) { @@ -75,6 +101,8 @@ func (u *userDocumentBuilder) BuildDocument(ctx context.Context, key *resourcepb if user.Spec.Login != "" { doc.Fields[USER_LOGIN] = user.Spec.Login } + doc.Fields[USER_LAST_SEEN_AT] = user.Status.LastSeenAt + doc.Fields[USER_ROLE] = user.Spec.Role return doc, nil } diff --git a/pkg/storage/unified/sql/data/resource_history_update_rv.sql b/pkg/storage/unified/sql/data/resource_history_update_rv.sql index 767338ddb34..266227b5317 100644 --- a/pkg/storage/unified/sql/data/resource_history_update_rv.sql +++ b/pkg/storage/unified/sql/data/resource_history_update_rv.sql @@ -5,6 +5,25 @@ SET {{ .Ident "resource_version" }} = ( WHEN {{ $.Ident "guid" }} = {{ $.Arg $guid }} THEN CAST({{ $.Arg $rv }} AS {{ if eq $.DialectName "postgres" }}BIGINT{{ else }}SIGNED{{ end }}) {{ end }} END +), {{ .Ident "key_path" }} = ( + CASE + {{ range $guid, $snowflakeRv := .GUIDToSnowflakeRV }} + WHEN {{ $.Ident "guid" }} = {{ $.Arg $guid }} THEN CONCAT( + 'unified', {{ $.SlashFunc }}, 'data', {{ $.SlashFunc }}, + {{ $.Ident "group" }}, {{ $.SlashFunc }}, + {{ $.Ident "resource" }}, {{ $.SlashFunc }}, + {{ $.Ident "namespace" }}, {{ $.SlashFunc }}, + {{ $.Ident "name" }}, {{ $.SlashFunc }}, + CAST({{ $.Arg $snowflakeRv }} AS {{ if eq $.DialectName "postgres" }}BIGINT{{ else }}SIGNED{{ end }}), + {{ $.TildeFunc }}, + CASE {{ $.Ident "action" }} + WHEN 1 THEN 'created' + WHEN 2 THEN 'updated' + WHEN 3 THEN 'deleted' + END, {{ $.TildeFunc }}, + COALESCE({{ $.Ident "folder" }}, '')) + {{ end }} + END ) WHERE {{ .Ident "guid" }} IN ( {{$first := true}} diff --git a/pkg/storage/unified/sql/db/migrations/resource_mig.go b/pkg/storage/unified/sql/db/migrations/resource_mig.go index c4db9b1dbb9..fbbfe32d4a6 100644 --- a/pkg/storage/unified/sql/db/migrations/resource_mig.go +++ b/pkg/storage/unified/sql/db/migrations/resource_mig.go @@ -198,5 +198,11 @@ func initResourceTables(mg *migrator.Migrator) string { } mg.AddMigration("create table "+resource_events_table.Name, migrator.NewAddTableMigration(resource_events_table)) + mg.AddMigration("Add IDX_resource_history_key_path index", migrator.NewAddIndexMigration(resource_history_table, &migrator.Index{ + Cols: []string{"key_path"}, + Type: migrator.IndexType, + Name: "IDX_resource_history_key_path", + })) + return marker } diff --git a/pkg/storage/unified/sql/queries.go b/pkg/storage/unified/sql/queries.go index e51cf943041..5b9a177e17c 100644 --- a/pkg/storage/unified/sql/queries.go +++ b/pkg/storage/unified/sql/queries.go @@ -369,13 +369,30 @@ func (r sqlResourceBlobQueryRequest) Validate() error { type sqlResourceUpdateRVRequest struct { sqltemplate.SQLTemplate - GUIDToRV map[string]int64 + GUIDToRV map[string]int64 + GUIDToSnowflakeRV map[string]int64 } func (r sqlResourceUpdateRVRequest) Validate() error { return nil // TODO } +func (r sqlResourceUpdateRVRequest) SlashFunc() string { + if r.DialectName() == "postgres" { + return "CHR(47)" + } + + return "CHAR(47)" +} + +func (r sqlResourceUpdateRVRequest) TildeFunc() string { + if r.DialectName() == "postgres" { + return "CHR(126)" + } + + return "CHAR(126)" +} + // resource_version table requests. type resourceVersionResponse struct { ResourceVersion int64 diff --git a/pkg/storage/unified/sql/rv_manager.go b/pkg/storage/unified/sql/rv_manager.go index 1232aa9c700..858345b1fc2 100644 --- a/pkg/storage/unified/sql/rv_manager.go +++ b/pkg/storage/unified/sql/rv_manager.go @@ -8,6 +8,7 @@ import ( "sync" "time" + "github.com/bwmarrin/snowflake" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "go.opentelemetry.io/otel/attribute" @@ -240,6 +241,7 @@ func (m *resourceVersionManager) execBatch(ctx context.Context, group, resource defer cancel() guidToRV := make(map[string]int64, len(batch)) + guidToSnowflakeRV := make(map[string]int64, len(batch)) guids := make([]string, len(batch)) // The GUIDs of the created resources in the same order as the batch rvs := make([]int64, len(batch)) // The RVs of the created resources in the same order as the batch @@ -285,6 +287,7 @@ func (m *resourceVersionManager) execBatch(ctx context.Context, group, resource // Allocate the RVs for i, guid := range guids { guidToRV[guid] = rv + guidToSnowflakeRV[guid] = snowflakeFromRv(rv) rvs[i] = rv rv++ } @@ -301,8 +304,9 @@ func (m *resourceVersionManager) execBatch(ctx context.Context, group, resource span.AddEvent("resource_versions_updated") if _, err := dbutil.Exec(ctx, tx, sqlResourceHistoryUpdateRV, sqlResourceUpdateRVRequest{ - SQLTemplate: sqltemplate.New(m.dialect), - GUIDToRV: guidToRV, + SQLTemplate: sqltemplate.New(m.dialect), + GUIDToRV: guidToRV, + GUIDToSnowflakeRV: guidToSnowflakeRV, }); err != nil { span.AddEvent("resource_history_update_rv_failed", trace.WithAttributes( attribute.String("error", err.Error()), @@ -340,6 +344,12 @@ func (m *resourceVersionManager) execBatch(ctx context.Context, group, resource } } +// takes a unix microsecond rv and transforms into a snowflake format. The timestamp is converted from microsecond to +// millisecond (the integer division) and the remainder is saved in the stepbits section. machine id is always 0 +func snowflakeFromRv(rv int64) int64 { + return (((rv / 1000) - snowflake.Epoch) << (snowflake.NodeBits + snowflake.StepBits)) + (rv % 1000) +} + // lock locks the resource version for the given key func (m *resourceVersionManager) lock(ctx context.Context, x db.ContextExecer, group, resource string) (nextRV int64, err error) { // 1. Lock the row and prevent concurrent updates until the transaction is committed diff --git a/pkg/storage/unified/sql/server.go b/pkg/storage/unified/sql/server.go index 6723a58dd29..84eda71ca20 100644 --- a/pkg/storage/unified/sql/server.go +++ b/pkg/storage/unified/sql/server.go @@ -97,22 +97,41 @@ func NewResourceServer(opts ServerOptions) (resource.ResourceServer, error) { return nil, err } - isHA := isHighAvailabilityEnabled(opts.Cfg.SectionWithEnvOverrides("database"), - opts.Cfg.SectionWithEnvOverrides("resource_api")) + if opts.Cfg.EnableSQLKVBackend { + sqlkv, err := resource.NewSQLKV(eDB) + if err != nil { + return nil, fmt.Errorf("error creating sqlkv: %s", err) + } - backend, err := NewBackend(BackendOptions{ - DBProvider: eDB, - Reg: opts.Reg, - IsHA: isHA, - storageMetrics: opts.StorageMetrics, - LastImportTimeMaxAge: opts.SearchOptions.MaxIndexAge, // No need to keep last_import_times older than max index age. - }) - if err != nil { - return nil, err + kvBackend, err := resource.NewKVStorageBackend(resource.KVBackendOptions{ + KvStore: sqlkv, + Tracer: opts.Tracer, + Reg: opts.Reg, + }) + if err != nil { + return nil, fmt.Errorf("error creating kv backend: %s", err) + } + + serverOptions.Backend = kvBackend + serverOptions.Diagnostics = kvBackend + } else { + isHA := isHighAvailabilityEnabled(opts.Cfg.SectionWithEnvOverrides("database"), + opts.Cfg.SectionWithEnvOverrides("resource_api")) + + backend, err := NewBackend(BackendOptions{ + DBProvider: eDB, + Reg: opts.Reg, + IsHA: isHA, + storageMetrics: opts.StorageMetrics, + LastImportTimeMaxAge: opts.SearchOptions.MaxIndexAge, // No need to keep last_import_times older than max index age. + }) + if err != nil { + return nil, err + } + serverOptions.Backend = backend + serverOptions.Diagnostics = backend + serverOptions.Lifecycle = backend } - serverOptions.Backend = backend - serverOptions.Diagnostics = backend - serverOptions.Lifecycle = backend } serverOptions.Search = opts.SearchOptions diff --git a/pkg/storage/unified/sql/test/benchmark_test.go b/pkg/storage/unified/sql/test/benchmark_test.go index f9665c83b7d..8bf65cbd6f7 100644 --- a/pkg/storage/unified/sql/test/benchmark_test.go +++ b/pkg/storage/unified/sql/test/benchmark_test.go @@ -15,5 +15,6 @@ func TestIntegrationBenchmarkSQLStorageBackend(t *testing.T) { if db.IsTestDbSQLite() { opts.Concurrency = 1 // to avoid SQLite database is locked error } - test.BenchmarkStorageBackend(t, newTestBackend(t, true, 2*time.Millisecond), opts) + backend, _ := newTestBackend(t, true, 2*time.Millisecond) + test.BenchmarkStorageBackend(t, backend, opts) } diff --git a/pkg/storage/unified/sql/test/integration_test.go b/pkg/storage/unified/sql/test/integration_test.go index cf45ee64d43..eaf78de0779 100644 --- a/pkg/storage/unified/sql/test/integration_test.go +++ b/pkg/storage/unified/sql/test/integration_test.go @@ -24,6 +24,7 @@ import ( "github.com/grafana/grafana/pkg/storage/unified/resourcepb" "github.com/grafana/grafana/pkg/storage/unified/search" "github.com/grafana/grafana/pkg/storage/unified/sql" + sqldb "github.com/grafana/grafana/pkg/storage/unified/sql/db" "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" unitest "github.com/grafana/grafana/pkg/storage/unified/testing" "github.com/grafana/grafana/pkg/tests/testsuite" @@ -38,7 +39,7 @@ var initMutex = &sync.Mutex{} // newTestBackend creates a fresh database and backend for a test. // It uses a mutex to ensure the entire initialization and migration // process is atomic and does not race with other parallel tests. -func newTestBackend(t *testing.T, isHA bool, simulatedNetworkLatency time.Duration) resource.StorageBackend { +func newTestBackend(t *testing.T, isHA bool, simulatedNetworkLatency time.Duration) (resource.StorageBackend, sqldb.DB) { // Lock to ensure the entire init block is atomic. initMutex.Lock() // Unlock once the function returns the initialized backend. @@ -61,7 +62,11 @@ func newTestBackend(t *testing.T, isHA bool, simulatedNetworkLatency time.Durati // Use a context with a reasonable timeout for migrations. err = backend.Init(testutil.NewTestContext(t, time.Now().Add(1*time.Minute))) require.NoError(t, err) - return backend + + sqlDB, err := eDB.Init(testutil.NewTestContext(t, time.Now().Add(1*time.Minute))) + require.NoError(t, err) + + return backend, sqlDB } func TestMain(m *testing.M) { @@ -73,7 +78,8 @@ func TestIntegrationStorageServer(t *testing.T) { t.Cleanup(db.CleanupTestDB) unitest.RunStorageServerTest(t, func(ctx context.Context) resource.StorageBackend { - return newTestBackend(t, true, 0) + backend, _ := newTestBackend(t, true, 0) + return backend }) } @@ -84,12 +90,31 @@ func TestIntegrationSQLStorageBackend(t *testing.T) { t.Run("IsHA (polling notifier)", func(t *testing.T) { unitest.RunStorageBackendTest(t, func(ctx context.Context) resource.StorageBackend { - return newTestBackend(t, true, 0) + backend, _ := newTestBackend(t, true, 0) + return backend }, nil) }) t.Run("NotHA (in process notifier)", func(t *testing.T) { unitest.RunStorageBackendTest(t, func(ctx context.Context) resource.StorageBackend { + backend, _ := newTestBackend(t, false, 0) + return backend + }, nil) + }) +} + +func TestIntegrationSQLStorageAndSQLKVCompatibilityTests(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + t.Cleanup(db.CleanupTestDB) + + t.Run("IsHA (polling notifier)", func(t *testing.T) { + unitest.RunSQLStorageBackendCompatibilityTest(t, func(ctx context.Context) (resource.StorageBackend, sqldb.DB) { + return newTestBackend(t, true, 0) + }, nil) + }) + + t.Run("NotHA (in process notifier)", func(t *testing.T) { + unitest.RunSQLStorageBackendCompatibilityTest(t, func(ctx context.Context) (resource.StorageBackend, sqldb.DB) { return newTestBackend(t, false, 0) }, nil) }) @@ -110,7 +135,7 @@ func TestIntegrationSearchAndStorage(t *testing.T) { t.Cleanup(search.Stop) // Create a new resource backend - storage := newTestBackend(t, false, 0) + storage, _ := newTestBackend(t, false, 0) require.NotNil(t, storage) // Run the shared storage and search tests diff --git a/pkg/storage/unified/sql/testdata/mysql--resource_history_update_rv-single path.sql b/pkg/storage/unified/sql/testdata/mysql--resource_history_update_rv-single path.sql index 6b07ff5e55b..62bb64c8300 100755 --- a/pkg/storage/unified/sql/testdata/mysql--resource_history_update_rv-single path.sql +++ b/pkg/storage/unified/sql/testdata/mysql--resource_history_update_rv-single path.sql @@ -4,6 +4,9 @@ SET `resource_version` = ( WHEN `guid` = 'guid1' THEN CAST(123 AS SIGNED) WHEN `guid` = 'guid2' THEN CAST(456 AS SIGNED) END +), `key_path` = ( + CASE + END ) WHERE `guid` IN ( 'guid1', 'guid2' diff --git a/pkg/storage/unified/sql/testdata/postgres--resource_history_update_rv-single path.sql b/pkg/storage/unified/sql/testdata/postgres--resource_history_update_rv-single path.sql index 85352e9ead4..6529fb1e4d5 100755 --- a/pkg/storage/unified/sql/testdata/postgres--resource_history_update_rv-single path.sql +++ b/pkg/storage/unified/sql/testdata/postgres--resource_history_update_rv-single path.sql @@ -4,6 +4,9 @@ SET "resource_version" = ( WHEN "guid" = 'guid1' THEN CAST(123 AS BIGINT) WHEN "guid" = 'guid2' THEN CAST(456 AS BIGINT) END +), "key_path" = ( + CASE + END ) WHERE "guid" IN ( 'guid1', 'guid2' diff --git a/pkg/storage/unified/sql/testdata/sqlite--resource_history_update_rv-single path.sql b/pkg/storage/unified/sql/testdata/sqlite--resource_history_update_rv-single path.sql index 9fb23fb3956..707fbad6cb8 100755 --- a/pkg/storage/unified/sql/testdata/sqlite--resource_history_update_rv-single path.sql +++ b/pkg/storage/unified/sql/testdata/sqlite--resource_history_update_rv-single path.sql @@ -4,6 +4,9 @@ SET "resource_version" = ( WHEN "guid" = 'guid1' THEN CAST(123 AS SIGNED) WHEN "guid" = 'guid2' THEN CAST(456 AS SIGNED) END +), "key_path" = ( + CASE + END ) WHERE "guid" IN ( 'guid1', 'guid2' diff --git a/pkg/storage/unified/testing/kv.go b/pkg/storage/unified/testing/kv.go index eab9aa9c845..fbdb8c70d20 100644 --- a/pkg/storage/unified/testing/kv.go +++ b/pkg/storage/unified/testing/kv.go @@ -28,6 +28,10 @@ const ( TestKVUnixTimestamp = "unix timestamp" TestKVBatchGet = "batch get operations" TestKVBatchDelete = "batch delete operations" + + // Use `eventsSection` as the section for the tests, as the sqlkv implementation + // needs a real section to determine which table to use. + testSection = "unified/events" ) // NewKVFunc is a function that creates a new KV instance for testing @@ -35,7 +39,8 @@ type NewKVFunc func(ctx context.Context) resource.KV // KVTestOptions configures which tests to run type KVTestOptions struct { - NSPrefix string // namespace prefix for isolation + SkipTests map[string]bool + NSPrefix string // namespace prefix for isolation } // GenerateRandomKVPrefix creates a random namespace prefix for test isolation @@ -72,23 +77,32 @@ func RunKVTest(t *testing.T, newKV NewKVFunc, opts *KVTestOptions) { } for _, tc := range cases { + if shouldSkip := opts.SkipTests[tc.name]; shouldSkip { + t.Logf("Skipping test: %s", tc.name) + continue + } + t.Run(tc.name, func(t *testing.T) { tc.fn(t, newKV(context.Background()), opts.NSPrefix) }) } } +func prefixKey(nsPrefix, key string) string { + return nsPrefix + "/" + key +} + func runTestKVGet(t *testing.T, kv resource.KV, nsPrefix string) { ctx := testutil.NewTestContext(t, time.Now().Add(30*time.Second)) - section := nsPrefix + "-get" t.Run("get existing key", func(t *testing.T) { // First save a key + existingKey := prefixKey(nsPrefix, "existing-key") testValue := "test value for get" - saveKVHelper(t, kv, ctx, section, "existing-key", strings.NewReader(testValue)) + saveKVHelper(t, kv, ctx, testSection, existingKey, strings.NewReader(testValue)) // Now get it - reader, err := kv.Get(ctx, section, "existing-key") + reader, err := kv.Get(ctx, testSection, existingKey) require.NoError(t, err) // Read the value @@ -102,16 +116,22 @@ func runTestKVGet(t *testing.T, kv resource.KV, nsPrefix string) { }) t.Run("get non-existent key", func(t *testing.T) { - _, err := kv.Get(ctx, section, "non-existent-key") + _, err := kv.Get(ctx, testSection, prefixKey(nsPrefix, "non-existent-key")) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) }) t.Run("get with empty section", func(t *testing.T) { - _, err := kv.Get(ctx, "", "some-key") + _, err := kv.Get(ctx, "", prefixKey(nsPrefix, "some-key")) assert.Error(t, err) assert.Contains(t, err.Error(), "section is required") }) + + t.Run("get with empty key", func(t *testing.T) { + _, err := kv.Get(ctx, testSection, "") + assert.Error(t, err) + assert.Contains(t, err.Error(), "key is required") + }) } func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { @@ -192,37 +212,43 @@ func runTestKVSave(t *testing.T, kv resource.KV, nsPrefix string) { func runTestKVDelete(t *testing.T, kv resource.KV, nsPrefix string) { ctx := testutil.NewTestContext(t, time.Now().Add(30*time.Second)) - section := nsPrefix + "-delete" t.Run("delete existing key", func(t *testing.T) { // First create a key - saveKVHelper(t, kv, ctx, section, "delete-key", strings.NewReader("delete me")) + deleteKey := prefixKey(nsPrefix, "delete-key") + saveKVHelper(t, kv, ctx, testSection, deleteKey, strings.NewReader("delete me")) // Verify it exists - _, err := kv.Get(ctx, section, "delete-key") + _, err := kv.Get(ctx, testSection, deleteKey) require.NoError(t, err) // Delete it - err = kv.Delete(ctx, section, "delete-key") + err = kv.Delete(ctx, testSection, deleteKey) require.NoError(t, err) // Verify it's gone - _, err = kv.Get(ctx, section, "delete-key") + _, err = kv.Get(ctx, testSection, deleteKey) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) }) t.Run("delete non-existent key", func(t *testing.T) { - err := kv.Delete(ctx, section, "non-existent-delete-key") + err := kv.Delete(ctx, testSection, prefixKey(nsPrefix, "non-existent-delete-key")) assert.Error(t, err) assert.Equal(t, resource.ErrNotFound, err) }) t.Run("delete with empty section", func(t *testing.T) { - err := kv.Delete(ctx, "", "some-key") + err := kv.Delete(ctx, "", prefixKey(nsPrefix, "some-key")) assert.Error(t, err) assert.Contains(t, err.Error(), "section is required") }) + + t.Run("delete with empty key", func(t *testing.T) { + err := kv.Delete(ctx, testSection, "") + assert.Error(t, err) + assert.Contains(t, err.Error(), "key is required") + }) } func runTestKVKeys(t *testing.T, kv resource.KV, nsPrefix string) { @@ -794,6 +820,19 @@ func runTestKVBatchDelete(t *testing.T, kv resource.KV, nsPrefix string) { // saveKVHelper is a helper function to save data to KV store using the new WriteCloser interface func saveKVHelper(t *testing.T, kv resource.KV, ctx context.Context, section, key string, value io.Reader) { t.Helper() + + // TODO: remove this check once the sqlkv implementation supports `Save`. + type testingSaver interface { + TestingSave(context.Context, string, []byte) error + } + + if saver, ok := kv.(testingSaver); ok { + blob, err := io.ReadAll(value) + require.NoError(t, err) + require.NoError(t, saver.TestingSave(ctx, key, blob)) + return + } + writer, err := kv.Save(ctx, section, key) require.NoError(t, err) _, err = io.Copy(writer, value) diff --git a/pkg/storage/unified/testing/kv_test.go b/pkg/storage/unified/testing/kv_test.go index 1e9b1a16c45..f6db1d2f1d8 100644 --- a/pkg/storage/unified/testing/kv_test.go +++ b/pkg/storage/unified/testing/kv_test.go @@ -7,7 +7,11 @@ import ( badger "github.com/dgraph-io/badger/v4" "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/storage/unified/resource" + "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" + "github.com/grafana/grafana/pkg/tests/testsuite" ) func TestBadgerKV(t *testing.T) { @@ -26,3 +30,31 @@ func TestBadgerKV(t *testing.T) { NSPrefix: "badger-kv-test", }) } + +func TestMain(m *testing.M) { + testsuite.Run(m) +} + +func TestSQLKV(t *testing.T) { + RunKVTest(t, func(ctx context.Context) resource.KV { + dbstore := db.InitTestDB(t) + eDB, err := dbimpl.ProvideResourceDB(dbstore, setting.NewCfg(), nil) + require.NoError(t, err) + + kv, err := resource.NewSQLKV(eDB) + require.NoError(t, err) + return kv + }, &KVTestOptions{ + NSPrefix: "sql-kv-test", + SkipTests: map[string]bool{ + TestKVSave: true, + TestKVKeys: true, + TestKVKeysWithLimits: true, + TestKVKeysWithSort: true, + TestKVConcurrent: true, + TestKVUnixTimestamp: true, + TestKVBatchGet: true, + TestKVBatchDelete: true, + }, + }) +} diff --git a/pkg/storage/unified/testing/storage_backend.go b/pkg/storage/unified/testing/storage_backend.go index ce36d8836bc..730efe418f6 100644 --- a/pkg/storage/unified/testing/storage_backend.go +++ b/pkg/storage/unified/testing/storage_backend.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/bwmarrin/snowflake" "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "github.com/stretchr/testify/assert" @@ -25,6 +26,7 @@ import ( "github.com/grafana/grafana/pkg/apimachinery/utils" "github.com/grafana/grafana/pkg/storage/unified/resource" "github.com/grafana/grafana/pkg/storage/unified/resourcepb" + sqldb "github.com/grafana/grafana/pkg/storage/unified/sql/db" "github.com/grafana/grafana/pkg/util/testutil" ) @@ -42,10 +44,14 @@ const ( TestCreateNewResource = "create new resource" TestGetResourceLastImportTime = "get resource last import time" TestOptimisticLocking = "optimistic locking on concurrent writes" + TestKeyPathGeneration = "key_path generation" ) type NewBackendFunc func(ctx context.Context) resource.StorageBackend +// NewBackendWithDBFunc creates a backend with database access for testing +type NewBackendWithDBFunc func(ctx context.Context) (resource.StorageBackend, sqldb.DB) + // TestOptions configures which tests to run type TestOptions struct { SkipTests map[string]bool // tests to skip @@ -100,6 +106,37 @@ func RunStorageBackendTest(t *testing.T, newBackend NewBackendFunc, opts *TestOp } } +func RunSQLStorageBackendCompatibilityTest(t *testing.T, newBackend NewBackendWithDBFunc, opts *TestOptions) { + if opts == nil { + opts = &TestOptions{} + } + + if opts.NSPrefix == "" { + opts.NSPrefix = GenerateRandomNSPrefix() + } + + t.Logf("Running tests with namespace prefix: %s", opts.NSPrefix) + + cases := []struct { + name string + fn func(*testing.T, resource.StorageBackend, string, sqldb.DB) + }{ + {TestKeyPathGeneration, runTestIntegrationBackendKeyPathGeneration}, + } + + for _, tc := range cases { + if shouldSkip := opts.SkipTests[tc.name]; shouldSkip { + t.Logf("Skipping test: %s", tc.name) + continue + } + + t.Run(tc.name, func(t *testing.T) { + backend, db := newBackend(context.Background()) + tc.fn(t, backend, opts.NSPrefix, db) + }) + } +} + func runTestIntegrationBackendHappyPath(t *testing.T, backend resource.StorageBackend, nsPrefix string) { ctx := types.WithAuthInfo(context.Background(), authn.NewAccessTokenAuthInfo(authn.Claims[authn.AccessTokenClaims]{ Claims: jwt.Claims{ @@ -1722,3 +1759,222 @@ func runTestIntegrationBackendOptimisticLocking(t *testing.T, backend resource.S require.LessOrEqual(t, successes, 1, "at most one create should succeed (errors: %v)", errorMessages) }) } + +func runTestIntegrationBackendKeyPathGeneration(t *testing.T, backend resource.StorageBackend, nsPrefix string, db sqldb.DB) { + ctx := testutil.NewDefaultTestContext(t) + + t.Run("Create resource", func(t *testing.T) { + // Create a test resource + key := &resourcepb.ResourceKey{ + Group: "playlist.grafana.app", + Resource: "playlists", + Namespace: nsPrefix + "-default", + Name: "test-playlist-crud", + } + + // Create the K8s unstructured object + testObj := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "playlist.grafana.app/v0alpha1", + "kind": "Playlist", + "metadata": map[string]interface{}{ + "name": "test-playlist-crud", + "namespace": nsPrefix + "-default", + "uid": "test-uid-crud-123", + }, + "spec": map[string]interface{}{ + "title": "My Test Playlist", + }, + }, + } + + // Get metadata accessor + metaAccessor, err := utils.MetaAccessor(testObj) + require.NoError(t, err) + + // Serialize to JSON + jsonBytes, err := testObj.MarshalJSON() + require.NoError(t, err) + + // Create WriteEvent + writeEvent := resource.WriteEvent{ + Type: resourcepb.WatchEvent_ADDED, + Key: key, + Value: jsonBytes, + Object: metaAccessor, + PreviousRV: 0, // Always 0 for new resources + GUID: "create-guid-crud-123", + } + + // Create the resource using WriteEvent + createRV, err := backend.WriteEvent(ctx, writeEvent) + require.NoError(t, err) + require.Greater(t, createRV, int64(0)) + + // Verify created resource key_path + verifyKeyPath(t, db, ctx, key, "created", createRV, "") + + t.Run("Update resource", func(t *testing.T) { + // Update the resource + testObj.Object["spec"] = map[string]interface{}{ + "title": "My Updated Playlist", + } + + updatedMetaAccessor, err := utils.MetaAccessor(testObj) + require.NoError(t, err) + + updatedJsonBytes, err := testObj.MarshalJSON() + require.NoError(t, err) + + updateEvent := resource.WriteEvent{ + Type: resourcepb.WatchEvent_MODIFIED, + Key: key, + Value: updatedJsonBytes, + Object: updatedMetaAccessor, + PreviousRV: createRV, + GUID: fmt.Sprintf("update-guid-%d", createRV), + } + + // Update the resource + updateRV, err := backend.WriteEvent(ctx, updateEvent) + require.NoError(t, err) + require.Greater(t, updateRV, createRV) + + // Verify updated resource key_path + verifyKeyPath(t, db, ctx, key, "updated", updateRV, "") + + t.Run("Delete resource", func(t *testing.T) { + deleteEvent := resource.WriteEvent{ + Type: resourcepb.WatchEvent_DELETED, + Key: key, + Value: updatedJsonBytes, // Keep the last known value + Object: updatedMetaAccessor, + PreviousRV: updateRV, + GUID: fmt.Sprintf("delete-guid-%d", updateRV), + } + + // Delete the resource + deleteRV, err := backend.WriteEvent(ctx, deleteEvent) + require.NoError(t, err) + require.Greater(t, deleteRV, updateRV) + + // Verify deleted resource key_path + verifyKeyPath(t, db, ctx, key, "deleted", deleteRV, "") + }) + }) + }) + + t.Run("Resource with folder", func(t *testing.T) { + // Create a resource in a folder + folderKey := &resourcepb.ResourceKey{ + Group: "dashboard.grafana.app", + Resource: "dashboards", + Namespace: nsPrefix + "-default", + Name: "my-dashboard", + } + + // Create dashboard object with folder + dashboardObj := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "dashboard.grafana.app/v0alpha1", + "kind": "Dashboard", + "metadata": map[string]interface{}{ + "name": "my-dashboard", + "namespace": nsPrefix + "-default", + "uid": "dash-uid-456", + "annotations": map[string]interface{}{ + "grafana.app/folder": "test-folder", + }, + }, + "spec": map[string]interface{}{ + "title": "My Dashboard", + }, + }, + } + + folderMetaAccessor, err := utils.MetaAccessor(dashboardObj) + require.NoError(t, err) + + folderJsonBytes, err := dashboardObj.MarshalJSON() + require.NoError(t, err) + + folderWriteEvent := resource.WriteEvent{ + Type: resourcepb.WatchEvent_ADDED, + Key: folderKey, + Value: folderJsonBytes, + Object: folderMetaAccessor, + PreviousRV: 0, + GUID: "folder-guid-456", + } + + // Create the dashboard in folder + folderRV, err := backend.WriteEvent(ctx, folderWriteEvent) + require.NoError(t, err) + require.Greater(t, folderRV, int64(0)) + + // Verify folder resource key_path includes folder + verifyKeyPath(t, db, ctx, folderKey, "created", folderRV, "test-folder") + }) +} + +// verifyKeyPath is a helper function to verify key_path generation +func verifyKeyPath(t *testing.T, db sqldb.DB, ctx context.Context, key *resourcepb.ResourceKey, action string, resourceVersion int64, expectedFolder string) { + var query string + if db.DriverName() == "postgres" { + query = "SELECT key_path, resource_version, action, folder FROM resource_history WHERE namespace = $1 AND name = $2 AND resource_version = $3" + } else { + query = "SELECT key_path, resource_version, action, folder FROM resource_history WHERE namespace = ? AND name = ? AND resource_version = ?" + } + rows, err := db.QueryContext(ctx, query, key.Namespace, key.Name, resourceVersion) + require.NoError(t, err) + + require.True(t, rows.Next()) + + var keyPath string + var actualRV int64 + var actualAction int + var actualFolder string + + err = rows.Scan(&keyPath, &actualRV, &actualAction, &actualFolder) + require.NoError(t, err) + err = rows.Close() + require.NoError(t, err) + + // Verify basic key_path format + require.Contains(t, keyPath, "unified/data/") + require.Contains(t, keyPath, key.Group) + require.Contains(t, keyPath, key.Resource) + require.Contains(t, keyPath, key.Namespace) + require.Contains(t, keyPath, key.Name) + + // Verify action suffix + require.Contains(t, keyPath, fmt.Sprintf("~%s~", action)) + + // Verify snowflake calculation + expectedSnowflake := (((resourceVersion / 1000) - snowflake.Epoch) << (snowflake.NodeBits + snowflake.StepBits)) + (resourceVersion % 1000) + require.Contains(t, keyPath, fmt.Sprintf("/%d~", expectedSnowflake), fmt.Sprintf("actual RV: %d", actualRV)) + + // Verify folder if specified + if expectedFolder != "" { + require.Equal(t, expectedFolder, actualFolder) + require.Contains(t, keyPath, expectedFolder) + } + + // Verify action code matches + var expectedActionCode int + switch action { + case "created": + expectedActionCode = 1 + case "updated": + expectedActionCode = 2 + case "deleted": + expectedActionCode = 3 + } + require.Equal(t, expectedActionCode, actualAction) + + t.Logf("Action: %s, RV: %d, Snowflake: %d", action, resourceVersion, expectedSnowflake) + t.Logf("Key_path: %s", keyPath) + if expectedFolder != "" { + t.Logf("Folder: %s", actualFolder) + } +} diff --git a/pkg/storage/unified/testing/storage_backend_test.go b/pkg/storage/unified/testing/storage_backend_test.go index 04f34e9102f..70e3b15aa7b 100644 --- a/pkg/storage/unified/testing/storage_backend_test.go +++ b/pkg/storage/unified/testing/storage_backend_test.go @@ -7,7 +7,11 @@ import ( badger "github.com/dgraph-io/badger/v4" "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/storage/unified/resource" + sqldb "github.com/grafana/grafana/pkg/storage/unified/sql/db" + "github.com/grafana/grafana/pkg/storage/unified/sql/db/dbimpl" ) func TestBadgerKVStorageBackend(t *testing.T) { @@ -25,7 +29,7 @@ func TestBadgerKVStorageBackend(t *testing.T) { require.NoError(t, err) return backend }, &TestOptions{ - NSPrefix: "kvstorage-test", + NSPrefix: "badgerkvstorage-test", SkipTests: map[string]bool{ // TODO: fix these tests and remove this skip TestBlobSupport: true, @@ -35,3 +39,50 @@ func TestBadgerKVStorageBackend(t *testing.T) { }, }) } + +func TestSQLKVStorageBackend(t *testing.T) { + newBackendFunc := func(ctx context.Context) (resource.StorageBackend, sqldb.DB) { + dbstore := db.InitTestDB(t) + eDB, err := dbimpl.ProvideResourceDB(dbstore, setting.NewCfg(), nil) + require.NoError(t, err) + kv, err := resource.NewSQLKV(eDB) + require.NoError(t, err) + kvOpts := resource.KVBackendOptions{ + KvStore: kv, + } + backend, err := resource.NewKVStorageBackend(kvOpts) + require.NoError(t, err) + db, err := eDB.Init(ctx) + require.NoError(t, err) + return backend, db + } + + RunStorageBackendTest(t, func(ctx context.Context) resource.StorageBackend { + backend, _ := newBackendFunc(ctx) + return backend + }, &TestOptions{ + NSPrefix: "sqlkvstorage-test", + SkipTests: map[string]bool{ + TestHappyPath: true, + TestWatchWriteEvents: true, + TestList: true, + TestBlobSupport: true, + TestGetResourceStats: true, + TestListHistory: true, + TestListHistoryErrorReporting: true, + TestListModifiedSince: true, + TestListTrash: true, + TestCreateNewResource: true, + TestGetResourceLastImportTime: true, + TestOptimisticLocking: true, + TestKeyPathGeneration: true, + }, + }) + + RunSQLStorageBackendCompatibilityTest(t, newBackendFunc, &TestOptions{ + NSPrefix: "sqlkvstorage-compatibility-test", + SkipTests: map[string]bool{ + TestKeyPathGeneration: true, + }, + }) +} diff --git a/pkg/tests/api/alerting/api_prometheus_test.go b/pkg/tests/api/alerting/api_prometheus_test.go index 61bc3195857..067372a3470 100644 --- a/pkg/tests/api/alerting/api_prometheus_test.go +++ b/pkg/tests/api/alerting/api_prometheus_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net/http" + "net/url" "sort" "testing" "time" @@ -364,8 +365,6 @@ func TestIntegrationPrometheusRules(t *testing.T) { func TestIntegrationPrometheusRulesPagination(t *testing.T) { testutil.SkipIntegrationTestInShortMode(t) - testinfra.SQLiteIntegrationTest(t) - dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{ DisableLegacyAlerting: true, EnableUnifiedAlerting: true, @@ -388,23 +387,30 @@ func TestIntegrationPrometheusRulesPagination(t *testing.T) { require.NoError(t, err) // Create 3 rule groups with different numbers of rules - // Group 1: 5 rules, Group 2: 3 rules, Group 3: 2 rules (total: 10 rules) + // Group 1: 5 rules with team=backend + // Group 2: 3 rules with team=frontend + // Group 3: 2 rules with team=platform for groupIdx := 1; groupIdx <= 3; groupIdx++ { var rulesCount int + var team string switch groupIdx { case 1: rulesCount = 5 + team = "backend" case 2: rulesCount = 3 + team = "frontend" case 3: rulesCount = 2 + team = "platform" } rules := make([]apimodels.PostableExtendedRuleNode, rulesCount) for i := 0; i < rulesCount; i++ { rules[i] = apimodels.PostableExtendedRuleNode{ ApiRuleNode: &apimodels.ApiRuleNode{ - For: &interval, + For: &interval, + Labels: map[string]string{"team": team}, }, GrafanaManagedAlert: &apimodels.PostableGrafanaRule{ Title: fmt.Sprintf("rule-%d-%d", groupIdx, i+1), @@ -514,6 +520,61 @@ func TestIntegrationPrometheusRulesPagination(t *testing.T) { require.Equal(t, http.StatusOK, resp.StatusCode) require.Len(t, result.Data.RuleGroups, 0, "should return no groups") }) + + t.Run("with rule_matcher filter returns only matching rules", func(t *testing.T) { + matcher := url.QueryEscape(`{"name":"team","value":"frontend","isRegex":false,"isEqual":true}`) + promRulesURL := fmt.Sprintf("http://grafana:password@%s/api/prometheus/grafana/api/v1/rules?rule_matcher=%s", grafanaListedAddr, matcher) + // nolint:gosec + resp, err := http.Get(promRulesURL) + require.NoError(t, err) + t.Cleanup(func() { + err := resp.Body.Close() + require.NoError(t, err) + }) + + var result apimodels.RuleResponse + err = json.NewDecoder(resp.Body).Decode(&result) + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode) + + // Should only return group-2 (team=frontend, 3 rules) + foundGroups := []string{} + total := 0 + for _, group := range result.Data.RuleGroups { + foundGroups = append(foundGroups, group.Name) + total += len(group.Rules) + } + require.Equal(t, []string{"group-2"}, foundGroups) + require.Equal(t, 3, total) + }) + + t.Run("with rule_matcher regex filter", func(t *testing.T) { + // Filter with regex team=~plat.* (should match group-3 with team=platform) + matcher := url.QueryEscape(`{"name":"team","value":"plat.*","isRegex":true,"isEqual":true}`) + promRulesURL := fmt.Sprintf("http://grafana:password@%s/api/prometheus/grafana/api/v1/rules?rule_matcher=%s", grafanaListedAddr, matcher) + // nolint:gosec + resp, err := http.Get(promRulesURL) + require.NoError(t, err) + t.Cleanup(func() { + err := resp.Body.Close() + require.NoError(t, err) + }) + + var result apimodels.RuleResponse + err = json.NewDecoder(resp.Body).Decode(&result) + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode) + + // Should only return group-3 (team=platform matches plat.*) + foundGroups := []string{} + total := 0 + for _, group := range result.Data.RuleGroups { + foundGroups = append(foundGroups, group.Name) + total += len(group.Rules) + } + require.Equal(t, []string{"group-3"}, foundGroups) + require.Equal(t, 2, total) + }) } func TestIntegrationPrometheusRulesFilterByDashboard(t *testing.T) { diff --git a/pkg/tests/api/alerting/test-data/alert-notifiers-v1-snapshot.json b/pkg/tests/api/alerting/test-data/alert-notifiers-v1-snapshot.json index 7bf5ff10535..b3dabb7cde2 100644 --- a/pkg/tests/api/alerting/test-data/alert-notifiers-v1-snapshot.json +++ b/pkg/tests/api/alerting/test-data/alert-notifiers-v1-snapshot.json @@ -82,6 +82,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "", @@ -208,6 +209,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "", @@ -352,6 +354,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "", @@ -451,6 +454,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -748,6 +752,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -910,6 +915,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -1194,6 +1200,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -1392,6 +1399,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -1793,6 +1801,7 @@ "is": "" }, "required": false, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -1820,6 +1829,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -2318,6 +2328,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -2610,6 +2621,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "token", @@ -2628,6 +2640,7 @@ "is": "" }, "required": false, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -2953,6 +2966,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -3303,6 +3317,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "", @@ -3393,6 +3408,7 @@ "is": "" }, "required": false, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -3474,6 +3490,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -3916,6 +3933,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -4114,6 +4132,7 @@ "is": "" }, "required": false, + "protected": true, "validationRule": "", "secure": false, "dependsOn": "", @@ -4201,6 +4220,7 @@ "is": "" }, "required": true, + "protected": true, "validationRule": "", "secure": true, "dependsOn": "secret", diff --git a/pkg/tests/apis/alerting/notifications/receivers/receiver_test.go b/pkg/tests/apis/alerting/notifications/receivers/receiver_test.go index 0f7b476ecad..5497c8f1685 100644 --- a/pkg/tests/apis/alerting/notifications/receivers/receiver_test.go +++ b/pkg/tests/apis/alerting/notifications/receivers/receiver_test.go @@ -143,7 +143,7 @@ func TestIntegrationResourcePermissions(t *testing.T) { adminClient := test_common.NewReceiverClient(t, admin) writeACMetadata := []string{"canWrite", "canDelete"} - allACMetadata := []string{"canWrite", "canDelete", "canReadSecrets", "canAdmin"} + allACMetadata := []string{"canWrite", "canDelete", "canReadSecrets", "canAdmin", "canModifyProtected"} mustID := func(user apis.User) int64 { id, err := user.Identity.GetInternalID() @@ -404,13 +404,14 @@ func TestIntegrationAccessControl(t *testing.T) { org1 := helper.Org1 type testCase struct { - user apis.User - canRead bool - canUpdate bool - canCreate bool - canDelete bool - canReadSecrets bool - canAdmin bool + user apis.User + canRead bool + canUpdate bool + canUpdateProtected bool + canCreate bool + canDelete bool + canReadSecrets bool + canAdmin bool } // region users unauthorized := helper.CreateUser("unauthorized", "Org1", org.RoleNone, []resourcepermissions.SetResourcePermissionCommand{}) @@ -473,20 +474,22 @@ func TestIntegrationAccessControl(t *testing.T) { testCases := []testCase{ { - user: unauthorized, - canRead: false, - canUpdate: false, - canCreate: false, - canDelete: false, + user: unauthorized, + canRead: false, + canUpdate: false, + canUpdateProtected: false, + canCreate: false, + canDelete: false, }, { - user: org1.Admin, - canRead: true, - canCreate: true, - canUpdate: true, - canDelete: true, - canAdmin: true, - canReadSecrets: true, + user: org1.Admin, + canRead: true, + canCreate: true, + canUpdate: true, + canUpdateProtected: true, + canDelete: true, + canAdmin: true, + canReadSecrets: true, }, { user: org1.Editor, @@ -535,22 +538,24 @@ func TestIntegrationAccessControl(t *testing.T) { canDelete: true, }, { - user: adminLikeUser, - canRead: true, - canCreate: true, - canUpdate: true, - canDelete: true, - canAdmin: true, - canReadSecrets: true, + user: adminLikeUser, + canRead: true, + canCreate: true, + canUpdate: true, + canUpdateProtected: true, + canDelete: true, + canAdmin: true, + canReadSecrets: true, }, { - user: adminLikeUserLongName, - canRead: true, - canCreate: true, - canUpdate: true, - canDelete: true, - canAdmin: true, - canReadSecrets: true, + user: adminLikeUserLongName, + canRead: true, + canCreate: true, + canUpdate: true, + canUpdateProtected: true, + canDelete: true, + canAdmin: true, + canReadSecrets: true, }, } @@ -609,6 +614,9 @@ func TestIntegrationAccessControl(t *testing.T) { if tc.canUpdate { expectedWithMetadata.SetAccessControl("canWrite") } + if tc.canUpdateProtected { + expectedWithMetadata.SetAccessControl("canModifyProtected") + } if tc.canDelete { expectedWithMetadata.SetAccessControl("canDelete") } @@ -672,6 +680,32 @@ func TestIntegrationAccessControl(t *testing.T) { require.Truef(t, errors.IsNotFound(err), "Should get NotFound error but got: %s", err) }) }) + + updatedExpected = expected.Copy().(*v0alpha1.Receiver) + updatedExpected.Spec.Integrations = []v0alpha1.ReceiverIntegration{ + createIntegration(t, "webhook"), + } + + expected, err = adminClient.Update(ctx, updatedExpected, v1.UpdateOptions{}) + require.NoErrorf(t, err, "Payload %s", string(d)) + require.NotNil(t, expected) + + updatedProtected := expected.Copy().(*v0alpha1.Receiver) + updatedProtected.Spec.Integrations[0].Settings["url"] = "http://localhost:8080/webhook" + + if tc.canUpdateProtected { + t.Run("should be able to update protected fields of the receiver", func(t *testing.T) { + updated, err := client.Update(ctx, updatedProtected, v1.UpdateOptions{}) + require.NoErrorf(t, err, "Payload %s", string(d)) + require.NotNil(t, updated) + expected = updated + }) + } else { + t.Run("should be forbidden to edit protected fields of the receiver", func(t *testing.T) { + _, err := client.Update(ctx, updatedProtected, v1.UpdateOptions{}) + require.Truef(t, errors.IsForbidden(err), "should get Forbidden error but got %s", err) + }) + } } else { t.Run("should be forbidden to update receiver", func(t *testing.T) { _, err := client.Update(ctx, updatedExpected, v1.UpdateOptions{}) @@ -684,6 +718,7 @@ func TestIntegrationAccessControl(t *testing.T) { require.Truef(t, errors.IsForbidden(err), "should get Forbidden error but got %s", err) }) }) + require.Falsef(t, tc.canUpdateProtected, "Invalid combination of assertions. CanUpdateProtected should be false") } deleteOptions := v1.DeleteOptions{Preconditions: &v1.Preconditions{ResourceVersion: util.Pointer(expected.ResourceVersion)}} @@ -1291,6 +1326,7 @@ func TestIntegrationCRUD(t *testing.T) { receiver.SetAccessControl("canDelete") receiver.SetAccessControl("canReadSecrets") receiver.SetAccessControl("canAdmin") + receiver.SetAccessControl("canModifyProtected") receiver.SetInUse(0, nil) receiver.SetCanUse(true) diff --git a/pkg/tests/apis/alerting/notifications/receivers/test-data/imported-expected-snapshot.json b/pkg/tests/apis/alerting/notifications/receivers/test-data/imported-expected-snapshot.json index 621f9c3af16..f092d8980f7 100644 --- a/pkg/tests/apis/alerting/notifications/receivers/test-data/imported-expected-snapshot.json +++ b/pkg/tests/apis/alerting/notifications/receivers/test-data/imported-expected-snapshot.json @@ -8,6 +8,7 @@ "annotations": { "grafana.com/access/canAdmin": "true", "grafana.com/access/canDelete": "true", + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/access/canWrite": "true", "grafana.com/canUse": "true", @@ -40,6 +41,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -61,6 +63,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -105,6 +108,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -153,6 +157,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -211,6 +216,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -256,6 +262,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -317,6 +324,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "1", @@ -388,6 +396,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -441,6 +450,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -525,6 +535,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -579,6 +590,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -625,6 +637,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -674,6 +687,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", @@ -722,6 +736,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "1", @@ -767,6 +782,7 @@ "kind": "Receiver", "metadata": { "annotations": { + "grafana.com/access/canModifyProtected": "true", "grafana.com/access/canReadSecrets": "true", "grafana.com/canUse": "false", "grafana.com/inUse/routes": "0", diff --git a/pkg/tests/apis/collections/stars_test.go b/pkg/tests/apis/collections/stars_test.go index fe841fb4851..573da05a00b 100644 --- a/pkg/tests/apis/collections/stars_test.go +++ b/pkg/tests/apis/collections/stars_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http" + "slices" "testing" "github.com/stretchr/testify/require" @@ -160,7 +161,7 @@ func TestIntegrationStars(t *testing.T) { { "group": "dashboard.grafana.app", "kind": "Dashboard", - "names": []string{"test-2", "aaa", "bbb"}, + "names": []string{"test-2", "aaa", "aaa", "bbb"}, }, }, }, @@ -174,13 +175,17 @@ func TestIntegrationStars(t *testing.T) { require.Equal(t, "dashboard.grafana.app", resources[0].Group) require.Equal(t, "Dashboard", resources[0].Kind) require.ElementsMatch(t, - []string{"aaa", "bbb", "test-2"}, // NOTE 2 stays, 3 removed, added aaa+bbb (and sorted!) + []string{"test-2", "aaa", "bbb"}, // keeps the requested order, removing duplicates resources[0].Names) rspObj, err = starsClient.Resource.Get(ctx, "user-"+starsClient.Args.User.Identity.GetIdentifier(), metav1.GetOptions{}) require.NoError(t, err) after = typed(t, rspObj, &collections.Stars{}) + + // FIXME: when we remove legacy support this should not sort! + slices.Sort(after.Spec.Resource[0].Names) + jj, err := json.MarshalIndent(after.Spec, "", " ") require.NoError(t, err) require.JSONEq(t, `{ diff --git a/pkg/tests/apis/config_test.go b/pkg/tests/apis/config_test.go index bf00affdfff..a9e8d87e0a0 100644 --- a/pkg/tests/apis/config_test.go +++ b/pkg/tests/apis/config_test.go @@ -15,19 +15,19 @@ const pluginsDiscoveryJSON = `[ "freshness": "Current", "resources": [ { - "resource": "pluginmetas", + "resource": "metas", "responseKind": { "group": "", - "kind": "PluginMeta", + "kind": "Meta", "version": "" }, "scope": "Namespaced", - "singularResource": "pluginmeta", + "singularResource": "meta", "subresources": [ { "responseKind": { "group": "", - "kind": "PluginMeta", + "kind": "Meta", "version": "" }, "subresource": "status", diff --git a/pkg/tests/apis/dashboard/dashboards_test.go b/pkg/tests/apis/dashboard/dashboards_test.go index 85f369c2ac6..5d5d04aa535 100644 --- a/pkg/tests/apis/dashboard/dashboards_test.go +++ b/pkg/tests/apis/dashboard/dashboards_test.go @@ -293,6 +293,199 @@ func TestIntegrationLegacySupport(t *testing.T) { require.Equal(t, dashboardV0.VERSION, rsp.Result.Meta.APIVersion) } +func TestIntegrationListPagination(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + gvr := schema.GroupVersionResource{ + Group: dashboardV0.GROUP, + Version: dashboardV0.VERSION, + Resource: "dashboards", + } + + // Test on modes with legacy + modes := []rest.DualWriterMode{rest.Mode1, rest.Mode2, rest.Mode3} + for _, mode := range modes { + t.Run(fmt.Sprintf("pagination with dual writer mode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + DisableAnonymous: true, + DisableDataMigrations: true, + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "dashboards.dashboard.grafana.app": { + DualWriterMode: mode, + }, + }, + }) + t.Cleanup(helper.Shutdown) + + ctx := context.Background() + client := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + GVR: gvr, + }) + + // Test 1: List with no dashboards + rsp, err := client.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err) + require.Len(t, rsp.Items, 0) + + // Create 5 dashboards to test pagination with small limits + const totalDashboards = 5 + createdNames := make([]string, 0, totalDashboards) + for i := 0; i < totalDashboards; i++ { + obj := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "spec": map[string]any{ + "title": fmt.Sprintf("Pagination test dashboard %d", i), + "schemaVersion": 42, + }, + }, + } + obj.SetGenerateName("pag-") + obj.SetAPIVersion(gvr.GroupVersion().String()) + obj.SetKind("Dashboard") + created, err := client.Resource.Create(ctx, obj, metav1.CreateOptions{}) + require.NoError(t, err) + createdNames = append(createdNames, created.GetName()) + } + + // Test 2: List all without limit - should return all dashboards + rsp, err = client.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err) + require.Len(t, rsp.Items, totalDashboards, "should return all %d dashboards", totalDashboards) + + // Test 3: List with small limit (2) - should paginate + const pageSize = 2 + allNames := make(map[string]bool) + continueToken := "" + pageCount := 0 + + for { + pageCount++ + listOpts := metav1.ListOptions{ + Limit: pageSize, + Continue: continueToken, + } + rsp, err = client.Resource.List(ctx, listOpts) + require.NoError(t, err) + + // Collect names from this page + for _, item := range rsp.Items { + name := item.GetName() + require.False(t, allNames[name], "duplicate item %s found across pages", name) + allNames[name] = true + } + + // Check if there's more pages + continueToken = rsp.GetContinue() + if continueToken == "" { + break + } + + // Safety check to prevent infinite loops + require.Less(t, pageCount, 5) + } + + // Verify we got all dashboards across all pages + require.Len(t, allNames, totalDashboards, "should have collected all %d dashboards across pages", totalDashboards) + + // Verify all created dashboards were found + for _, name := range createdNames { + require.True(t, allNames[name], "dashboard %s not found in paginated results", name) + } + }) + + t.Run(fmt.Sprintf("history pagination with dual writer mode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + DisableAnonymous: true, + DisableDataMigrations: true, + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "dashboards.dashboard.grafana.app": { + DualWriterMode: mode, + }, + }, + }) + t.Cleanup(helper.Shutdown) + + ctx := context.Background() + client := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + GVR: gvr, + }) + + // Create a dashboard + obj := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "spec": map[string]any{ + "title": "History pagination test dashboard", + "schemaVersion": 42, + }, + }, + } + obj.SetGenerateName("hist-") + obj.SetAPIVersion(gvr.GroupVersion().String()) + obj.SetKind("Dashboard") + created, err := client.Resource.Create(ctx, obj, metav1.CreateOptions{}) + require.NoError(t, err) + dashName := created.GetName() + + // Update the dashboard multiple times to create history entries + const totalVersions = 5 + for i := 1; i < totalVersions; i++ { + // Get latest version + current, err := client.Resource.Get(ctx, dashName, metav1.GetOptions{}) + require.NoError(t, err) + + // Update title + spec := current.Object["spec"].(map[string]interface{}) + spec["title"] = fmt.Sprintf("History pagination test dashboard v%d", i+1) + current.Object["spec"] = spec + + _, err = client.Resource.Update(ctx, current, metav1.UpdateOptions{}) + require.NoError(t, err) + } + + // Test: List history with pagination + labelSelector := utils.LabelKeyGetHistory + "=true" + fieldSelector := "metadata.name=" + dashName + + const pageSize int64 = 2 + allVersions := make([]string, 0) + continueToken := "" + pageCount := 0 + + for { + pageCount++ + listOpts := metav1.ListOptions{ + LabelSelector: labelSelector, + FieldSelector: fieldSelector, + Limit: pageSize, + Continue: continueToken, + } + rsp, err := client.Resource.List(ctx, listOpts) + require.NoError(t, err) + + // Collect resource versions from this page + for _, item := range rsp.Items { + rv := item.GetResourceVersion() + allVersions = append(allVersions, rv) + } + + // Check if there's more pages + continueToken = rsp.GetContinue() + if continueToken == "" { + break + } + + // Safety check to prevent infinite loops + require.Less(t, pageCount, 5) + } + + // Verify we got all history versions + require.Len(t, allVersions, totalVersions, "should have collected all %d history versions across pages", totalVersions) + }) + } +} + func TestIntegrationSearchTypeFiltering(t *testing.T) { testutil.SkipIntegrationTestInShortMode(t) diff --git a/pkg/tests/apis/folder/folders_test.go b/pkg/tests/apis/folder/folders_test.go index 43db6ff0932..1cc58c4bdbd 100644 --- a/pkg/tests/apis/folder/folders_test.go +++ b/pkg/tests/apis/folder/folders_test.go @@ -1879,6 +1879,14 @@ func TestIntegrationMoveNestedFolderToRootK8S(t *testing.T) { require.Equal(t, http.StatusOK, get.Response.StatusCode) require.Equal(t, "f2", get.Result.UID) require.Equal(t, "", get.Result.ParentUID) + + // Check that we can get the same folder using metadata.name selector + results, err := client.Resource.List(context.Background(), metav1.ListOptions{ + FieldSelector: "metadata.name=" + get.Result.UID, + }) + require.NoError(t, err) + require.Len(t, results.Items, 1) + require.Equal(t, "f2", results.Items[0].GetName()) } // Test deleting nested folders ensures postorder deletion diff --git a/pkg/tests/apis/iam/resource_permissions_integration_test.go b/pkg/tests/apis/iam/resource_permissions_integration_test.go new file mode 100644 index 00000000000..dbfa51750ad --- /dev/null +++ b/pkg/tests/apis/iam/resource_permissions_integration_test.go @@ -0,0 +1,625 @@ +package identity + +import ( + "context" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/apiserver/rest" + "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/tests/apis" + "github.com/grafana/grafana/pkg/tests/testinfra" + "github.com/grafana/grafana/pkg/util/testutil" +) + +var gvrResourcePermissions = schema.GroupVersionResource{ + Group: "iam.grafana.app", + Version: "v0alpha1", + Resource: "resourcepermissions", +} + +var gvrFolders = schema.GroupVersionResource{ + Group: "folder.grafana.app", + Version: "v1beta1", + Resource: "folders", +} + +var gvrDashboards = schema.GroupVersionResource{ + Group: "dashboard.grafana.app", + Version: "v1beta1", + Resource: "dashboards", +} + +type permission struct { + kind string + name string + verb string +} + +func newPermission(kind, name, verb string) permission { + return permission{ + kind: kind, + name: name, + verb: verb, + } +} + +func (p permission) ToMap() map[string]interface{} { + return map[string]interface{}{ + "kind": p.kind, + "name": p.name, + "verb": p.verb, + } +} + +func newPermissionMaps(permissions ...permission) []map[string]interface{} { + permissionsMaps := make([]map[string]interface{}, len(permissions)) + for i, permission := range permissions { + permissionsMaps[i] = permission.ToMap() + } + return permissionsMaps +} + +type k8sTestClients struct { + rpAdmin *apis.K8sResourceClient + rpEditor *apis.K8sResourceClient + rpViewer *apis.K8sResourceClient +} + +func newk8sTestHelperClients(helper *apis.K8sTestHelper) *k8sTestClients { + return &k8sTestClients{ + rpAdmin: helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + Namespace: helper.Namespacer(helper.Org1.OrgID), + GVR: gvrResourcePermissions, + }), + rpEditor: helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Editor, + Namespace: helper.Namespacer(helper.Org1.OrgID), + GVR: gvrResourcePermissions, + }), + rpViewer: helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Viewer, + Namespace: helper.Namespacer(helper.Org1.OrgID), + GVR: gvrResourcePermissions, + }), + } +} + +func TestIntegrationResourcePermissions(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + modes := []rest.DualWriterMode{rest.Mode0, rest.Mode1, rest.Mode2, rest.Mode3} + for _, mode := range modes { + if mode >= rest.Mode3 { + t.Skip("Skipping ResourcePermission tests for Mode3+ because default permissions are not written through the new APIs") + continue + } + t.Run(fmt.Sprintf("ResourcePermission CRUD with dual writer mode %d", mode), func(t *testing.T) { + // Turn off authorization cache so permission changes apply right away in tests + t.Setenv("GF_AUTHORIZATION_CACHE_TTL", "0s") + + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + AppModeProduction: false, + DisableAnonymous: true, + APIServerStorageType: "unified", + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "resourcepermissions.iam.grafana.app": { + DualWriterMode: mode, + }, + "folders.folder.grafana.app": { + DualWriterMode: mode, + }, + "dashboards.dashboard.grafana.app": { + DualWriterMode: mode, + }, + }, + EnableFeatureToggles: []string{ + featuremgmt.FlagKubernetesAuthzResourcePermissionApis, + // Prevents nested folders from having default permissions + featuremgmt.FlagKubernetesDashboards, + }, + }) + + // Work around the default permissions applied on root folders + // so we can test the ResourcePermission APIs without the default permissions interfering + parentFolder := createRootFolderWithoutDefaultPermissions(t, helper) + parentUID := parentFolder.GetName() + + clients := newk8sTestHelperClients(helper) + doResourcePermissionCRUDTests(t, helper, clients, parentUID) + doResourcePermissionAuthzTests(t, helper, clients, parentUID) + doResourcePermissionHierarchyTests(t, helper, clients, parentUID) + doResourcePermissionListFilteringTests(t, helper, clients, parentUID) + // TODO: Add tests for External JWT authentication + // doResourcePermissionAccessPolicyTests(t, helper) + }) + } +} + +func doResourcePermissionCRUDTests(t *testing.T, helper *apis.K8sTestHelper, clients *k8sTestClients, parentUID string) { + t.Run("should create/get/update/delete ResourcePermission using the new APIs", func(t *testing.T) { + ctx := context.Background() + + // Create ResourcePermission for the folder + permission := newPermission("ServiceAccount", helper.Org1.ViewerServiceAccount.UID, "view") + toCreate := createResourcePermissionObject(parentUID, gvrFolders.Group, gvrFolders.Resource, permission) + + created, err := clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, created) + + createdName := created.GetName() + require.NotEmpty(t, createdName) + + // Verify spec + spec := created.Object["spec"].(map[string]interface{}) + resource := spec["resource"].(map[string]interface{}) + require.Equal(t, gvrFolders.Group, resource["apiGroup"]) + require.Equal(t, gvrFolders.Resource, resource["resource"]) + require.Equal(t, parentUID, resource["name"]) + + // Get the ResourcePermission + fetched, err := clients.rpAdmin.Resource.Get(ctx, createdName, metav1.GetOptions{}) + require.NoError(t, err) + require.NotNil(t, fetched) + require.Equal(t, createdName, fetched.GetName()) + + // Update the ResourcePermission + fetched.Object["spec"].(map[string]interface{})["permissions"] = newPermissionMaps( + newPermission("User", helper.Org1.Viewer.Identity.GetIdentifier(), "edit"), + ) + updated, err := clients.rpAdmin.Resource.Update(ctx, fetched, metav1.UpdateOptions{}) + require.NoError(t, err) + require.NotNil(t, updated) + + updatedSpec := updated.Object["spec"].(map[string]interface{}) + permissions := updatedSpec["permissions"].([]interface{}) + require.Len(t, permissions, 1) + perm := permissions[0].(map[string]interface{}) + require.Equal(t, helper.Org1.Viewer.Identity.GetIdentifier(), perm["name"]) + require.Equal(t, "edit", perm["verb"]) + + // Delete should work + err = clients.rpAdmin.Resource.Delete(ctx, createdName, metav1.DeleteOptions{}) + require.NoError(t, err) + + _, err = clients.rpAdmin.Resource.Get(ctx, createdName, metav1.GetOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(404), statusErr.ErrStatus.Code) + }) + + t.Run("should return 404 for non-existent ResourcePermission", func(t *testing.T) { + ctx := context.Background() + + _, err := clients.rpAdmin.Resource.Get(ctx, "folder.grafana.app-folders-unknown", metav1.GetOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(404), statusErr.ErrStatus.Code) + }) +} + +func doResourcePermissionAuthzTests(t *testing.T, helper *apis.K8sTestHelper, clients *k8sTestClients, parentUID string) { + t.Run("admin can create/update/delete ResourcePermission", func(t *testing.T) { + ctx := context.Background() + + folder := createTestFolder(t, helper, helper.Org1.Admin, "test-folder-admin", parentUID) + folderUID := folder.GetName() + + permission := newPermission("User", helper.Org1.Admin.Identity.GetIdentifier(), "admin") + + toCreate := createResourcePermissionObject(folderUID, gvrFolders.Group, gvrFolders.Resource, permission) + created, err := clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, created) + + createdName := created.GetName() + + // Get the created object + fetched, err := clients.rpAdmin.Resource.Get(ctx, createdName, metav1.GetOptions{}) + require.NoError(t, err) + require.NotNil(t, fetched) + + // Update should work + permission = newPermission("Team", helper.Org1.Staff.UID, "edit") + fetched.Object["spec"].(map[string]interface{})["permissions"] = []interface{}{permission.ToMap()} + + _, err = clients.rpAdmin.Resource.Update(ctx, fetched, metav1.UpdateOptions{}) + require.NoError(t, err) + + // Delete should work + err = clients.rpAdmin.Resource.Delete(ctx, createdName, metav1.DeleteOptions{}) + require.NoError(t, err) + }) + + t.Run("editor cannot create ResourcePermission (insufficient permissions)", func(t *testing.T) { + ctx := context.Background() + + folder := createTestFolder(t, helper, helper.Org1.Admin, "test-folder-editor-deny", parentUID) + folderUID := folder.GetName() + + permission := newPermission("User", helper.Org1.Editor.Identity.GetIdentifier(), "admin") + toCreate := createResourcePermissionObject(folderUID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err := clients.rpEditor.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(403), statusErr.ErrStatus.Code) + }) + + t.Run("viewer cannot create ResourcePermission (insufficient permissions)", func(t *testing.T) { + ctx := context.Background() + + folder := createTestFolder(t, helper, helper.Org1.Admin, "test-folder-viewer-deny", parentUID) + folderUID := folder.GetName() + + permission := newPermission("User", helper.Org1.Viewer.Identity.GetIdentifier(), "admin") + toCreate := createResourcePermissionObject(folderUID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err := clients.rpViewer.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(403), statusErr.ErrStatus.Code) + }) + + t.Run("viewer can update ResourcePermission of folder they can admin", func(t *testing.T) { + ctx := context.Background() + + folder := createTestFolder(t, helper, helper.Org1.Admin, "test-folder-viewer-admin", parentUID) + folderUID := folder.GetName() + + // Grant admin permissions to the viewer + permission := newPermission("User", helper.Org1.Viewer.Identity.GetIdentifier(), "admin") + toCreate := createResourcePermissionObject(folderUID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err := clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + + // As a Viewer we should now be able to get and update the ResourcePermission of the folder + fetched, err := clients.rpViewer.Resource.Get(ctx, "folder.grafana.app-folders-"+folderUID, metav1.GetOptions{}) + require.NoError(t, err) + require.NotNil(t, fetched) + + // Update the ResourcePermission to grant editor permissions + fetched.Object["spec"].(map[string]interface{})["permissions"] = newPermissionMaps( + newPermission("BasicRole", "Editor", "edit"), + newPermission("User", helper.Org1.Viewer.Identity.GetIdentifier(), "admin"), + ) + + _, err = clients.rpViewer.Resource.Update(ctx, fetched, metav1.UpdateOptions{}) + require.NoError(t, err) + }) +} + +func doResourcePermissionHierarchyTests(t *testing.T, helper *apis.K8sTestHelper, clients *k8sTestClients, parentUID string) { + permission := newPermission("BasicRole", "Editor", "admin") + + t.Run("should respect folder hierarchy for folder permissions", func(t *testing.T) { + ctx := context.Background() + + sub1 := createTestFolder(t, helper, helper.Org1.Admin, "sub1-folder-hierarchy", parentUID) + sub1UID := sub1.GetName() + + sub2 := createTestFolder(t, helper, helper.Org1.Admin, "sub2-folder-hierarchy", sub1UID) + sub2UID := sub2.GetName() + + toCreate := createResourcePermissionObject(sub2UID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err := clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + + t.Run("editor can update ResourcePermission of sub2", func(t *testing.T) { + fetched, err := clients.rpEditor.Resource.Get(ctx, "folder.grafana.app-folders-"+sub2UID, metav1.GetOptions{}) + require.NoError(t, err) + + fetched.Object["spec"].(map[string]interface{})["permissions"] = newPermissionMaps( + newPermission("BasicRole", "Editor", "admin"), + newPermission("User", helper.Org1.Viewer.Identity.GetIdentifier(), "edit"), + ) + _, err = clients.rpEditor.Resource.Update(ctx, fetched, metav1.UpdateOptions{}) + require.NoError(t, err) + }) + t.Run("editor cannot create ResourcePermission of sub1", func(t *testing.T) { + toCreate := createResourcePermissionObject(sub1UID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err := clients.rpEditor.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(403), statusErr.ErrStatus.Code) + }) + + // Delete the ResourcePermission of sub2 + err = clients.rpAdmin.Resource.Delete(ctx, "folder.grafana.app-folders-"+sub2UID, metav1.DeleteOptions{}) + require.NoError(t, err) + + // Create a new ResourcePermission for sub2 + toCreate = createResourcePermissionObject(sub1UID, gvrFolders.Group, gvrFolders.Resource, permission) + _, err = clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + + t.Run("editor can create ResourcePermission of sub2 with parent folder permission", func(t *testing.T) { + toCreate := createResourcePermissionObject(sub2UID, gvrFolders.Group, gvrFolders.Resource, permission) + + _, err = clients.rpEditor.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + + fetched, err := clients.rpEditor.Resource.Get(ctx, "folder.grafana.app-folders-"+sub2UID, metav1.GetOptions{}) + require.NoError(t, err) + require.NotNil(t, fetched) + + permissions := fetched.Object["spec"].(map[string]interface{})["permissions"] + require.Len(t, permissions, 1) + }) + }) + + t.Run("should respect folder hierarchy for dashboard permissions", func(t *testing.T) { + ctx := context.Background() + + // Create folder and a nested dashboard + folder := createTestFolder(t, helper, helper.Org1.Admin, "sub1-dashboard-hierarchy", parentUID) + folderUID := folder.GetName() + + dashboard := createTestDashboard(t, helper, helper.Org1.Admin, "sub2-dashboard", folderUID) + dashboardUID := dashboard.GetName() + + // Verify dashboard has parent folder annotation + annotations := dashboard.GetAnnotations() + require.Equal(t, folderUID, annotations[utils.AnnoKeyFolder]) + + t.Run("editor cannot create ResourcePermission of dashboard without parent folder permission", func(t *testing.T) { + toCreate := createResourcePermissionObject(dashboardUID, gvrDashboards.Group, gvrDashboards.Resource, permission) + _, err := clients.rpEditor.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(403), statusErr.ErrStatus.Code) + }) + + // Admin creates ResourcePermission for parent folder + toCreate := createResourcePermissionObject(folderUID, gvrFolders.Group, gvrFolders.Resource, permission) + created, err := clients.rpAdmin.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, created) + + t.Run("editor can create ResourcePermission of dashboard with parent folder permission", func(t *testing.T) { + toCreate := createResourcePermissionObject(dashboardUID, gvrDashboards.Group, gvrDashboards.Resource, permission) + _, err := clients.rpEditor.Resource.Create(ctx, toCreate, metav1.CreateOptions{}) + require.NoError(t, err) + + fetched, err := clients.rpEditor.Resource.Get(ctx, "dashboard.grafana.app-dashboards-"+dashboardUID, metav1.GetOptions{}) + require.NoError(t, err) + require.NotNil(t, fetched) + + permissions := fetched.Object["spec"].(map[string]interface{})["permissions"] + require.Len(t, permissions, 1) + }) + }) +} + +func doResourcePermissionListFilteringTests(t *testing.T, helper *apis.K8sTestHelper, clients *k8sTestClients, parentUID string) { + viewerCanAdmin := newPermission("BasicRole", "Viewer", "admin") + viewerCanView := newPermission("BasicRole", "Viewer", "view") + editorCanAdmin := newPermission("BasicRole", "Editor", "admin") + + ctx := context.Background() + + // Create two folders + editorFolder := createTestFolder(t, helper, helper.Org1.Admin, "editor-only-folder", parentUID) + editorFolderUID := editorFolder.GetName() + + viewerFolder := createTestFolder(t, helper, helper.Org1.Admin, "viewer-only-folder", parentUID) + viewerFolderUID := viewerFolder.GetName() + + dashboardViewerCanAdmin := createTestDashboard(t, helper, helper.Org1.Admin, "dashboard-in-editor-folder-viewer-can-admin", editorFolderUID) + dashboardViewerCanAdminUID := dashboardViewerCanAdmin.GetName() + dashboardViewerCanView := createTestDashboard(t, helper, helper.Org1.Admin, "dashboard-in-editor-folder-viewer-can-view", editorFolderUID) + dashboardViewerCanViewUID := dashboardViewerCanView.GetName() + + // Grant admin permissions to the viewer on folder2 and dashboard1 + rp1 := createResourcePermissionObject(viewerFolderUID, gvrFolders.Group, gvrFolders.Resource, viewerCanAdmin) + _, err := clients.rpAdmin.Resource.Create(ctx, rp1, metav1.CreateOptions{}) + require.NoError(t, err) + rp2 := createResourcePermissionObject(dashboardViewerCanAdminUID, gvrDashboards.Group, gvrDashboards.Resource, viewerCanAdmin) + _, err = clients.rpAdmin.Resource.Create(ctx, rp2, metav1.CreateOptions{}) + require.NoError(t, err) + // Grant admin permissions to the editor on folder1 + rp3 := createResourcePermissionObject(editorFolderUID, gvrFolders.Group, gvrFolders.Resource, editorCanAdmin) + _, err = clients.rpAdmin.Resource.Create(ctx, rp3, metav1.CreateOptions{}) + require.NoError(t, err) + // Grant view permissions to the viewer on dashboard2 + rp4 := createResourcePermissionObject(dashboardViewerCanViewUID, gvrDashboards.Group, gvrDashboards.Resource, viewerCanView) + _, err = clients.rpAdmin.Resource.Create(ctx, rp4, metav1.CreateOptions{}) + require.NoError(t, err) + + t.Run("Admin can list all ResourcePermissions", func(t *testing.T) { + // Admin can list all ResourcePermissions + list, err := clients.rpAdmin.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err) + require.NotNil(t, list) + + // Check that all expected items are present (there may be more from other tests) + itemNames := getNamesFromList(list) + require.Contains(t, itemNames, rp1.GetName(), "Admin should see viewer folder permission") + require.Contains(t, itemNames, rp2.GetName(), "Admin should see dashboard viewer can admin permission") + require.Contains(t, itemNames, rp3.GetName(), "Admin should see editor folder permission") + require.Contains(t, itemNames, rp4.GetName(), "Admin should see dashboard viewer can view permission") + }) + + t.Run("Viewer can list ResourcePermissions of folder2 and dashboard1", func(t *testing.T) { + list, err := clients.rpViewer.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err) + require.NotNil(t, list) + + itemNames := getNamesFromList(list) + // Viewer should see permissions for resources they can admin + require.Contains(t, itemNames, rp1.GetName(), "Viewer should see viewer folder permission") + require.Contains(t, itemNames, rp2.GetName(), "Viewer should see dashboard viewer can admin permission") + + // Viewer should NOT see permissions for resources they cannot admin + require.NotContains(t, itemNames, rp3.GetName(), "Viewer should NOT see editor folder permission") + require.NotContains(t, itemNames, rp4.GetName(), "Viewer should NOT see dashboard viewer can view permission") + }) + t.Run("Editor can list ResourcePermissions of folder1 and its nested dashboards", func(t *testing.T) { + list, err := clients.rpEditor.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err) + require.NotNil(t, list) + + itemNames := getNamesFromList(list) + // Editor has admin on editorFolder, so they should see: + // - rp3 (editorFolder permission) + // - rp2 (dashboard in editorFolder with admin permission) + // - rp4 (dashboard in editorFolder with view permission) + require.Contains(t, itemNames, rp2.GetName(), "Editor should see dashboard admin permission in their folder") + require.Contains(t, itemNames, rp3.GetName(), "Editor should see their folder permission") + require.Contains(t, itemNames, rp4.GetName(), "Editor should see dashboard view permission in their folder") + + // Editor should NOT see permissions for viewerFolder + require.NotContains(t, itemNames, rp1.GetName(), "Editor should NOT see viewer-only folder permission") + }) +} + +// Helper functions + +func createTestFolder(t *testing.T, helper *apis.K8sTestHelper, user apis.User, title string, parentUID string) *unstructured.Unstructured { + t.Helper() + ctx := context.Background() + + folderClient := helper.GetResourceClient(apis.ResourceClientArgs{ + User: user, + Namespace: helper.Namespacer(user.Identity.GetOrgID()), + GVR: gvrFolders, + }) + metadata := map[string]interface{}{ + "generateName": "test-folder-", + "namespace": helper.Namespacer(user.Identity.GetOrgID()), + } + + if parentUID != "" { + metadata["annotations"] = map[string]interface{}{ + utils.AnnoKeyFolder: parentUID, + } + } + + folder := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "folder.grafana.app/v1beta1", + "kind": "Folder", + "metadata": metadata, + "spec": map[string]interface{}{ + "title": title, + }, + }, + } + + created, err := folderClient.Resource.Create(ctx, folder, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, created) + return created +} + +// Helper function to delete default permissions +func deleteDefaultPermissions(t *testing.T, client *apis.K8sResourceClient, resourceName string) { + ctx := context.Background() + // Delete the resource permission + err := client.Resource.Delete(ctx, resourceName, metav1.DeleteOptions{}) + require.NoError(t, err) + // Check if the resource permission is deleted + _, err = client.Resource.Get(ctx, resourceName, metav1.GetOptions{}) + require.Error(t, err) + var statusErr *errors.StatusError + require.ErrorAs(t, err, &statusErr) + require.Equal(t, int32(404), statusErr.ErrStatus.Code) +} + +// Helper function to create a root folder without default permissions +func createRootFolderWithoutDefaultPermissions(t *testing.T, helper *apis.K8sTestHelper) *unstructured.Unstructured { + t.Helper() + + // Create folder as admin + folder := createTestFolder(t, helper, helper.Org1.Admin, "root-without-permissions", "") + folderUID := folder.GetName() + + // Delete default permissions + rpClient := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + Namespace: helper.Namespacer(helper.Org1.OrgID), + GVR: gvrResourcePermissions, + }) + + // It would be better to create the folder without default permissions, but this is a workaround for the time being + deleteDefaultPermissions(t, rpClient, "folder.grafana.app-folders-"+folderUID) + + return folder +} + +func createTestDashboard(t *testing.T, helper *apis.K8sTestHelper, user apis.User, title, folderUID string) *unstructured.Unstructured { + t.Helper() + ctx := context.Background() + + dashboardClient := helper.GetResourceClient(apis.ResourceClientArgs{ + User: user, + Namespace: helper.Namespacer(user.Identity.GetOrgID()), + GVR: gvrDashboards, + }) + + dashboard := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "dashboard.grafana.app/v1beta1", + "kind": "Dashboard", + "metadata": map[string]interface{}{ + "generateName": "test-dashboard-", + "namespace": helper.Namespacer(user.Identity.GetOrgID()), + "annotations": map[string]interface{}{ + utils.AnnoKeyFolder: folderUID, + }, + }, + "spec": map[string]interface{}{ + "title": title, + }, + }, + } + + created, err := dashboardClient.Resource.Create(ctx, dashboard, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, created) + return created +} + +func createResourcePermissionObject(resourceName, apiGroup, resource string, permissions ...permission) *unstructured.Unstructured { + permissionMaps := newPermissionMaps(permissions...) + return &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": iamv0.GROUP + "/" + iamv0.VERSION, + "kind": "ResourcePermission", + "metadata": map[string]interface{}{ + "name": apiGroup + "-" + resource + "-" + resourceName, + }, + "spec": map[string]interface{}{ + "resource": map[string]interface{}{ + "apiGroup": apiGroup, + "resource": resource, + "name": resourceName, + }, + "permissions": permissionMaps, + }, + }, + } +} + +func getNamesFromList(list *unstructured.UnstructuredList) []string { + names := make([]string, len(list.Items)) + for i, item := range list.Items { + names[i] = item.GetName() + } + return names +} diff --git a/pkg/tests/apis/iam/user_search_integration_test.go b/pkg/tests/apis/iam/user_search_integration_test.go new file mode 100644 index 00000000000..1f689b701b0 --- /dev/null +++ b/pkg/tests/apis/iam/user_search_integration_test.go @@ -0,0 +1,568 @@ +package identity + +import ( + "context" + "fmt" + "net/url" + "sort" + "testing" + "time" + + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + + iamv0 "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1" + "github.com/grafana/grafana/pkg/apiserver/rest" + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/tests/apis" + "github.com/grafana/grafana/pkg/tests/testinfra" + "github.com/grafana/grafana/pkg/util/testutil" +) + +func TestIntegrationUserSearch(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + modes := []rest.DualWriterMode{rest.Mode0, rest.Mode1, rest.Mode2, rest.Mode3, rest.Mode4, rest.Mode5} + for _, mode := range modes { + t.Run(fmt.Sprintf("DualWriterMode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + AppModeProduction: false, + DisableAnonymous: true, + APIServerStorageType: "unified", + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "users.iam.grafana.app": { + DualWriterMode: mode, + }, + }, + EnableFeatureToggles: []string{ + featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, + featuremgmt.FlagKubernetesAuthnMutation, + }, + UnifiedStorageEnableSearch: true, + }) + + t.Cleanup(func() { + helper.Shutdown() + }) + + setupUsers(t, helper) + + t.Run("search by title", func(t *testing.T) { + res := searchUsers(t, helper, "Alice") + require.Len(t, res.Hits, 1) + require.Equal(t, "TestUser Alice", res.Hits[0].Title) + }) + + t.Run("search by login", func(t *testing.T) { + res := searchUsers(t, helper, "bob") + require.Len(t, res.Hits, 1) + require.Equal(t, "bob", res.Hits[0].Login) + }) + + t.Run("search by email", func(t *testing.T) { + res := searchUsers(t, helper, "charlie@example.com") + require.Len(t, res.Hits, 1) + require.Equal(t, "charlie@example.com", res.Hits[0].Email) + }) + }) + } +} + +func TestIntegrationUserSearch_WithSorting(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + modes := []rest.DualWriterMode{rest.Mode0, rest.Mode1, rest.Mode2, rest.Mode3, rest.Mode4, rest.Mode5} + for _, mode := range modes { + t.Run(fmt.Sprintf("DualWriterMode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + AppModeProduction: false, + DisableAnonymous: true, + APIServerStorageType: "unified", + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "users.iam.grafana.app": { + DualWriterMode: mode, + }, + }, + EnableFeatureToggles: []string{ + featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, + featuremgmt.FlagKubernetesAuthnMutation, + }, + UnifiedStorageEnableSearch: true, + }) + + t.Cleanup(func() { + helper.Shutdown() + }) + + setupUsers(t, helper) + + tests := []struct { + field string + extractor func(iamv0.UserHit) string + expected []string + }{ + { + field: "title", + extractor: func(h iamv0.UserHit) string { return h.Title }, + expected: []string{"TestUser Alice", "TestUser Bob", "TestUser Charlie", "TestUser Editor", "TestUser Viewer"}, + }, + { + field: "login", + extractor: func(h iamv0.UserHit) string { return h.Login }, + expected: []string{"alice", "bob", "charlie", "testuser-editor", "testuser-viewer"}, + }, + { + field: "email", + extractor: func(h iamv0.UserHit) string { return h.Email }, + expected: []string{"alice@example.com", "bob@example.com", "charlie@example.com", "testuser-editor@example.com", "testuser-viewer@example.com"}, + }, + } + + for _, tc := range tests { + t.Run("sort by "+tc.field, func(t *testing.T) { + // ASC + res := searchUsersWithSort(t, helper, "TestUser", tc.field) + require.GreaterOrEqual(t, len(res.Hits), 5) + verifyOrder(t, res.Hits, tc.expected, tc.extractor) + + // DESC + res = searchUsersWithSort(t, helper, "TestUser", "-"+tc.field) + require.GreaterOrEqual(t, len(res.Hits), 5) + + // Reverse expected + reversed := make([]string, len(tc.expected)) + copy(reversed, tc.expected) + sort.Sort(sort.Reverse(sort.StringSlice(reversed))) + verifyOrder(t, res.Hits, reversed, tc.extractor) + }) + } + + t.Run("sort by lastSeenAt", func(t *testing.T) { + if mode >= rest.Mode3 { + t.Skip("Skipping lastSeenAt sort test for Mode >= 3: API does not persist status.lastSeenAt") + } + // Populate lastSeenAt + // Alice: 30 minutes ago + // Bob: 1 minute ago + // Charlie: 2 hours ago + // Editor: 40 minutes ago + // Viewer: 1h 30 mins ago + now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) + updateLastSeenAt(t, helper, "alice", now.Add(-30*time.Minute), mode) + updateLastSeenAt(t, helper, "bob", now.Add(-1*time.Minute), mode) + updateLastSeenAt(t, helper, "charlie", now.Add(-2*time.Hour), mode) + updateLastSeenAt(t, helper, "testuser-editor", now.Add(-40*time.Minute), mode) + updateLastSeenAt(t, helper, "testuser-viewer", now.Add(-90*time.Minute), mode) + + // lastSeenAt ASC means oldest date first to match legacy behavior + res := searchUsersWithSort(t, helper, "TestUser", "lastSeenAt") + require.GreaterOrEqual(t, len(res.Hits), 5) + verifyOrder(t, res.Hits, []string{"charlie", "testuser-viewer", "testuser-editor", "alice", "bob"}, func(h iamv0.UserHit) string { return h.Login }) + + res = searchUsersWithSort(t, helper, "TestUser", "-lastSeenAt") + require.GreaterOrEqual(t, len(res.Hits), 5) + verifyOrder(t, res.Hits, []string{"bob", "alice", "testuser-editor", "testuser-viewer", "charlie"}, func(h iamv0.UserHit) string { return h.Login }) + }) + }) + } +} + +func TestIntegrationUserSearch_SortCompareLegacy(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + modes := []rest.DualWriterMode{rest.Mode2} + for _, mode := range modes { + t.Run(fmt.Sprintf("DualWriterMode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + AppModeProduction: false, + DisableAnonymous: true, + APIServerStorageType: "unified", + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "users.iam.grafana.app": { + DualWriterMode: mode, + }, + }, + EnableFeatureToggles: []string{ + featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, + featuremgmt.FlagKubernetesAuthnMutation, + }, + UnifiedStorageEnableSearch: true, + }) + + t.Cleanup(func() { + helper.Shutdown() + }) + + setupUsers(t, helper) + + // Populate lastSeenAt for sorting comparison + now := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) + updateLastSeenAt(t, helper, "alice", now.Add(-30*time.Minute), mode) + updateLastSeenAt(t, helper, "bob", now.Add(-1*time.Minute), mode) + updateLastSeenAt(t, helper, "charlie", now.Add(-2*time.Hour), mode) + updateLastSeenAt(t, helper, "testuser-editor", now.Add(-40*time.Minute), mode) + updateLastSeenAt(t, helper, "testuser-viewer", now.Add(-90*time.Minute), mode) + + fields := []string{"login", "email", "name", "lastSeenAt"} + for _, field := range fields { + for _, order := range []string{"asc", "desc"} { + t.Run(fmt.Sprintf("compare %s %s", field, order), func(t *testing.T) { + // Legacy API uses "name" for Name/Title, "login" for Login, "email" for Email. + // "lastSeenAt" maps to "lastSeenAtAge" in legacy. + legacySort := field + if field == "lastSeenAt" { + legacySort = "lastSeenAtAge" + } + legacySort += "-" + order + + newSort := field + if order == "desc" { + newSort = "-" + field + } + + legacyRes := searchUsersLegacy(t, helper, "TestUser", legacySort) + newRes := searchUsersWithSort(t, helper, "TestUser", newSort) + + require.Equal(t, len(legacyRes), len(newRes.Hits)) + for i := range legacyRes { + require.Equal(t, legacyRes[i].Login, newRes.Hits[i].Login, "Mismatch at index %d for sort %s", i, newSort) + } + }) + } + } + }) + } +} + +func TestIntegrationUserSearch_Paging(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + modes := []rest.DualWriterMode{rest.Mode0, rest.Mode1, rest.Mode2, rest.Mode3, rest.Mode4, rest.Mode5} + for _, mode := range modes { + t.Run(fmt.Sprintf("DualWriterMode %d", mode), func(t *testing.T) { + helper := apis.NewK8sTestHelper(t, testinfra.GrafanaOpts{ + AppModeProduction: false, + DisableAnonymous: true, + APIServerStorageType: "unified", + UnifiedStorageConfig: map[string]setting.UnifiedStorageConfig{ + "users.iam.grafana.app": { + DualWriterMode: mode, + }, + }, + EnableFeatureToggles: []string{ + featuremgmt.FlagGrafanaAPIServerWithExperimentalAPIs, + featuremgmt.FlagKubernetesAuthnMutation, + }, + UnifiedStorageEnableSearch: true, + }) + + t.Cleanup(func() { + helper.Shutdown() + }) + + setupUsers(t, helper) + + t.Run("paging with page and limit", func(t *testing.T) { + // There are 5 users matching "TestUser" + query := "TestUser" + + // Page 1, Limit 2 + res1 := searchUsersWithPaging(t, helper, query, 1, 2) + require.Equal(t, int64(5), res1.TotalHits) + require.Len(t, res1.Hits, 2) + + // Page 2, Limit 2 + res2 := searchUsersWithPaging(t, helper, query, 2, 2) + require.Equal(t, int64(5), res2.TotalHits) + require.Len(t, res2.Hits, 2) + + // Page 3, Limit 2 + res3 := searchUsersWithPaging(t, helper, query, 3, 2) + require.Equal(t, int64(5), res3.TotalHits) + require.Len(t, res3.Hits, 1) + + seen := make(map[string]bool) + for _, h := range res1.Hits { + seen[h.Login] = true + } + for _, h := range res2.Hits { + require.False(t, seen[h.Login], "User %s seen in page 1 and 2", h.Login) + seen[h.Login] = true + } + for _, h := range res3.Hits { + require.False(t, seen[h.Login], "User %s seen in previous pages", h.Login) + seen[h.Login] = true + } + require.Len(t, seen, 5) + }) + + t.Run("paging with offset and limit", func(t *testing.T) { + // There are 5 users matching "TestUser" + query := "TestUser" + + // Offset 0, Limit 2 (equivalent to Page 1) + res1 := searchUsersWithOffset(t, helper, query, 0, 2) + require.Equal(t, int64(5), res1.TotalHits) + require.Len(t, res1.Hits, 2) + + // Offset 2, Limit 2 (equivalent to Page 2) + res2 := searchUsersWithOffset(t, helper, query, 2, 2) + require.Equal(t, int64(5), res2.TotalHits) + require.Len(t, res2.Hits, 2) + + // Offset 4, Limit 2 (equivalent to Page 3) + res3 := searchUsersWithOffset(t, helper, query, 4, 2) + require.Equal(t, int64(5), res3.TotalHits) + require.Len(t, res3.Hits, 1) + + // Verify uniqueness + seen := make(map[string]bool) + for _, h := range res1.Hits { + seen[h.Login] = true + } + for _, h := range res2.Hits { + require.False(t, seen[h.Login], "User %s seen in offset 0 and 2", h.Login) + seen[h.Login] = true + } + for _, h := range res3.Hits { + require.False(t, seen[h.Login], "User %s seen in previous offsets", h.Login) + seen[h.Login] = true + } + require.Len(t, seen, 5) + }) + }) + } +} + +func setupUsers(t *testing.T, helper *apis.K8sTestHelper) { + ctx := context.Background() + userClient := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + Namespace: helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()), + GVR: gvrUsers, + }) + + users := []iamv0.User{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "testuser-editor", + }, + Spec: iamv0.UserSpec{ + Title: "TestUser Editor", + Login: "testuser-editor", + Email: "testuser-editor@example.com", + Role: "Editor", + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "testuser-viewer", + }, + Spec: iamv0.UserSpec{ + Title: "TestUser Viewer", + Login: "testuser-viewer", + Email: "testuser-viewer@example.com", + Role: "Viewer", + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "alice", + }, + Spec: iamv0.UserSpec{ + Title: "TestUser Alice", + Login: "alice", + Email: "alice@example.com", + Role: "Viewer", + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "bob", + }, + Spec: iamv0.UserSpec{ + Title: "TestUser Bob", + Login: "bob", + Email: "bob@example.com", + Role: "Viewer", + }, + }, + { + ObjectMeta: metav1.ObjectMeta{ + Name: "charlie", + }, + Spec: iamv0.UserSpec{ + Title: "TestUser Charlie", + Login: "charlie", + Email: "charlie@example.com", + Role: "Viewer", + }, + }, + } + + for _, u := range users { + uMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&u) + require.NoError(t, err) + _, err = userClient.Resource.Create(ctx, &unstructured.Unstructured{Object: uMap}, metav1.CreateOptions{}) + require.NoError(t, err) + } + + // Wait for indexing + time.Sleep(2 * time.Second) +} + +func searchUsers(t *testing.T, helper *apis.K8sTestHelper, query string) *iamv0.GetSearchUsers { + return searchUsersWithSort(t, helper, query, "") +} + +func searchUsersWithSort(t *testing.T, helper *apis.K8sTestHelper, query string, sort string) *iamv0.GetSearchUsers { + q := url.Values{} + q.Set("query", query) + if sort != "" { + q.Set("sort", sort) + } + q.Set("limit", "100") + + path := fmt.Sprintf("/apis/iam.grafana.app/v0alpha1/namespaces/default/searchUsers?%s", q.Encode()) + + res := &iamv0.GetSearchUsers{} + rsp := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, res) + + require.Equal(t, 200, rsp.Response.StatusCode) + return res +} + +func searchUsersWithPaging(t *testing.T, helper *apis.K8sTestHelper, query string, page, limit int) *iamv0.GetSearchUsers { + q := url.Values{} + q.Set("query", query) + q.Set("page", fmt.Sprintf("%d", page)) + q.Set("limit", fmt.Sprintf("%d", limit)) + // Sort by login to ensure deterministic paging + q.Set("sort", "login") + + path := fmt.Sprintf("/apis/iam.grafana.app/v0alpha1/namespaces/default/searchUsers?%s", q.Encode()) + + res := &iamv0.GetSearchUsers{} + rsp := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, res) + + require.Equal(t, 200, rsp.Response.StatusCode) + return res +} + +func searchUsersWithOffset(t *testing.T, helper *apis.K8sTestHelper, query string, offset, limit int) *iamv0.GetSearchUsers { + q := url.Values{} + q.Set("query", query) + q.Set("offset", fmt.Sprintf("%d", offset)) + q.Set("limit", fmt.Sprintf("%d", limit)) + // Sort by login to ensure deterministic paging + q.Set("sort", "login") + + path := fmt.Sprintf("/apis/iam.grafana.app/v0alpha1/namespaces/default/searchUsers?%s", q.Encode()) + + res := &iamv0.GetSearchUsers{} + rsp := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, res) + + require.Equal(t, 200, rsp.Response.StatusCode) + return res +} + +type LegacyUserSearchHit struct { + UserId int64 `json:"userId"` + Name string `json:"name"` + Login string `json:"login"` + Email string `json:"email"` +} + +func searchUsersLegacy(t *testing.T, helper *apis.K8sTestHelper, query string, sort string) []LegacyUserSearchHit { + q := url.Values{} + q.Set("query", query) + + if sort != "" { + q.Set("sort", sort) + } + q.Set("perpage", "100") + q.Set("page", "1") + + path := fmt.Sprintf("/api/org/users/search?%s", q.Encode()) + + var res struct { + OrgUsers []LegacyUserSearchHit `json:"orgUsers"` + } + + rsp := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, &res) + + require.Equal(t, 200, rsp.Response.StatusCode) + return res.OrgUsers +} + +// verifyOrder checks that the extracted values from hits are in the expected order. +// It filters hits to only include those with expected values, because search returns more results than just the test users. +// Like other users in the system that have been created by the test framework. +func verifyOrder(t *testing.T, hits []iamv0.UserHit, expectedValues []string, extractor func(iamv0.UserHit) string) { + // Filter hits to only include expected values + var actualValues []string + expectedSet := make(map[string]bool) + for _, v := range expectedValues { + expectedSet[v] = true + } + + for _, h := range hits { + val := extractor(h) + if expectedSet[val] { + actualValues = append(actualValues, val) + } + } + + require.Equal(t, expectedValues, actualValues) +} + +func updateLastSeenAt(t *testing.T, helper *apis.K8sTestHelper, login string, lastSeen time.Time, mode rest.DualWriterMode) { + if mode < rest.Mode3 { + err := helper.GetEnv().SQLStore.WithDbSession(context.Background(), func(sess *db.Session) error { + _, err := sess.Table("user").Where("login = ?", login).Update(map[string]interface{}{ + "last_seen_at": lastSeen, + }) + return err + }) + require.NoError(t, err) + } + + // Use the new APIs to update the user resource status in Mode3+ + if mode >= rest.Mode3 { + ctx := context.Background() + userClient := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + Namespace: helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()), + GVR: gvrUsers, + }) + + u, err := userClient.Resource.Get(ctx, login, metav1.GetOptions{}) + require.NoError(t, err) + + err = unstructured.SetNestedField(u.Object, lastSeen.Unix(), "status", "lastSeenAt") + require.NoError(t, err) + + _, err = userClient.Resource.Update(ctx, u, metav1.UpdateOptions{}) + require.NoError(t, err) + } +} diff --git a/pkg/tests/apis/openapi_snapshots/iam.grafana.app-v0alpha1.json b/pkg/tests/apis/openapi_snapshots/iam.grafana.app-v0alpha1.json index ea0e4039581..dab9f3cd8b1 100644 --- a/pkg/tests/apis/openapi_snapshots/iam.grafana.app-v0alpha1.json +++ b/pkg/tests/apis/openapi_snapshots/iam.grafana.app-v0alpha1.json @@ -1021,6 +1021,156 @@ } } }, + "/apis/iam.grafana.app/v0alpha1/namespaces/{namespace}/searchUsers": { + "get": { + "tags": [ + "Search" + ], + "description": "User search", + "operationId": "getSearchUsers", + "parameters": [ + { + "name": "namespace", + "in": "path", + "description": "workspace", + "required": true, + "schema": { + "type": "string" + }, + "example": "default" + }, + { + "name": "query", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "number of results to return", + "schema": { + "type": "integer", + "format": "int64" + }, + "example": 30 + }, + { + "name": "page", + "in": "query", + "description": "page number (starting from 1)", + "schema": { + "type": "integer", + "format": "int64" + }, + "example": 1 + }, + { + "name": "offset", + "in": "query", + "description": "number of results to skip", + "schema": { + "type": "integer", + "format": "int64" + }, + "example": 0 + }, + { + "name": "sort", + "in": "query", + "description": "sortable field", + "schema": { + "type": "string" + }, + "examples": { + "": { + "summary": "default sorting" + }, + "-email": { + "summary": "email descending", + "value": "-email" + }, + "-lastSeenAt": { + "summary": "last seen at descending", + "value": "-lastSeenAt" + }, + "-login": { + "summary": "login descending", + "value": "-login" + }, + "-title": { + "summary": "title descending", + "value": "-title" + }, + "email": { + "summary": "email ascending", + "value": "email" + }, + "lastSeenAt": { + "summary": "last seen at ascending", + "value": "lastSeenAt" + }, + "login": { + "summary": "login ascending", + "value": "login" + }, + "title": { + "summary": "title ascending", + "value": "title" + } + } + } + ], + "responses": { + "default": { + "description": "Default OK response", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "offset", + "totalHits", + "hits", + "queryCost", + "maxScore" + ], + "properties": { + "hits": { + "type": "array", + "items": { + "default": {} + } + }, + "maxScore": { + "type": "number", + "format": "double", + "default": 0 + }, + "offset": { + "type": "integer", + "format": "int64", + "default": 0 + }, + "queryCost": { + "type": "number", + "format": "double", + "default": 0 + }, + "totalHits": { + "type": "integer", + "format": "int64", + "default": 0 + } + } + } + } + } + } + } + } + }, "/apis/iam.grafana.app/v0alpha1/namespaces/{namespace}/serviceaccounts": { "get": { "tags": [ @@ -5614,7 +5764,8 @@ "type": "object", "required": [ "metadata", - "spec" + "spec", + "status" ], "properties": { "apiVersion": { @@ -5641,6 +5792,14 @@ "$ref": "#/components/schemas/com.github.grafana.grafana.apps.iam.pkg.apis.iam.v0alpha1.UserSpec" } ] + }, + "status": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.iam.pkg.apis.iam.v0alpha1.UserStatus" + } + ] } }, "x-kubernetes-group-version-kind": [ @@ -5741,6 +5900,19 @@ } } }, + "com.github.grafana.grafana.apps.iam.pkg.apis.iam.v0alpha1.UserStatus": { + "type": "object", + "required": [ + "lastSeenAt" + ], + "properties": { + "lastSeenAt": { + "type": "integer", + "format": "int64", + "default": 0 + } + } + }, "com.github.grafana.grafana.apps.iam.pkg.apis.iam.v0alpha1.VersionsV0alpha1Kinds7RoutesGroupsGETResponseExternalGroupMapping": { "type": "object", "required": [ @@ -6566,6 +6738,44 @@ } } }, + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GetSearchUsers": { + "type": "object", + "required": [ + "offset", + "totalHits", + "hits", + "queryCost", + "maxScore" + ], + "properties": { + "hits": { + "type": "array", + "items": { + "default": {} + } + }, + "maxScore": { + "type": "number", + "format": "double", + "default": 0 + }, + "offset": { + "type": "integer", + "format": "int64", + "default": 0 + }, + "queryCost": { + "type": "number", + "format": "double", + "default": 0 + }, + "totalHits": { + "type": "integer", + "format": "int64", + "default": 0 + } + } + }, "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.GlobalRole": { "type": "object", "required": [ @@ -7760,7 +7970,8 @@ "type": "object", "required": [ "metadata", - "spec" + "spec", + "status" ], "properties": { "apiVersion": { @@ -7777,6 +7988,63 @@ "spec": { "description": "Spec is the spec of the User", "default": {} + }, + "status": { + "default": {} + } + } + }, + "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserHit": { + "type": "object", + "required": [ + "name", + "title", + "login", + "email", + "role", + "lastSeenAt", + "lastSeenAtAge", + "provisioned", + "score" + ], + "properties": { + "email": { + "type": "string", + "default": "" + }, + "lastSeenAt": { + "type": "integer", + "format": "int64", + "default": 0 + }, + "lastSeenAtAge": { + "type": "string", + "default": "" + }, + "login": { + "type": "string", + "default": "" + }, + "name": { + "type": "string", + "default": "" + }, + "provisioned": { + "type": "boolean", + "default": false + }, + "role": { + "type": "string", + "default": "" + }, + "score": { + "type": "number", + "format": "double", + "default": 0 + }, + "title": { + "type": "string", + "default": "" } } }, @@ -7854,51 +8122,15 @@ } }, "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserStatus": { - "type": "object", - "properties": { - "additionalFields": { - "description": "additionalFields is reserved for future use", - "type": "object", - "additionalProperties": { - "type": "object" - } - }, - "operatorStates": { - "description": "operatorStates is a map of operator ID to operator state evaluations. Any operator which consumes this kind SHOULD add its state evaluation information to this field.", - "type": "object", - "additionalProperties": { - "default": {} - } - } - } - }, - "github.com/grafana/grafana/apps/iam/pkg/apis/iam/v0alpha1.UserstatusOperatorState": { "type": "object", "required": [ - "lastEvaluation", - "state" + "lastSeenAt" ], "properties": { - "descriptiveState": { - "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", - "type": "string" - }, - "details": { - "description": "details contains any extra information that is operator-specific", - "type": "object", - "additionalProperties": { - "type": "object" - } - }, - "lastEvaluation": { - "description": "lastEvaluation is the ResourceVersion last evaluated", - "type": "string", - "default": "" - }, - "state": { - "description": "state describes the state of the lastEvaluation. It is limited to three possible states for machine evaluation.", - "type": "string", - "default": "" + "lastSeenAt": { + "type": "integer", + "format": "int64", + "default": 0 } } }, diff --git a/pkg/tests/apis/openapi_snapshots/logsdrilldown.grafana.app-v1alpha1.json b/pkg/tests/apis/openapi_snapshots/logsdrilldown.grafana.app-v1alpha1.json index 25d6cd87807..93be607fd41 100644 --- a/pkg/tests/apis/openapi_snapshots/logsdrilldown.grafana.app-v1alpha1.json +++ b/pkg/tests/apis/openapi_snapshots/logsdrilldown.grafana.app-v1alpha1.json @@ -35,6 +35,1126 @@ } } }, + "/apis/logsdrilldown.grafana.app/v1alpha1/namespaces/{namespace}/logsdrilldowndefaultcolumns": { + "get": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "list or watch objects of kind LogsDrilldownDefaultColumns", + "operationId": "listLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "allowWatchBookmarks", + "in": "query", + "description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "continue", + "in": "query", + "description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "labelSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "limit", + "in": "query", + "description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "resourceVersion", + "in": "query", + "description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersionMatch", + "in": "query", + "description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "sendInitialEvents", + "in": "query", + "description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "timeoutSeconds", + "in": "query", + "description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "watch", + "in": "query", + "description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList" + } + }, + "application/json;stream=watch": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList" + } + }, + "application/vnd.kubernetes.protobuf;stream=watch": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList" + } + } + } + } + }, + "x-kubernetes-action": "list", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "post": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "create LogsDrilldownDefaultColumns", + "operationId": "createLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "202": { + "description": "Accepted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "post", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "delete": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "delete collection of LogsDrilldownDefaultColumns", + "operationId": "deletecollectionLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "continue", + "in": "query", + "description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "gracePeriodSeconds", + "in": "query", + "description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "ignoreStoreReadErrorWithClusterBreakingPotential", + "in": "query", + "description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "labelSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "limit", + "in": "query", + "description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "orphanDependents", + "in": "query", + "description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "propagationPolicy", + "in": "query", + "description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersion", + "in": "query", + "description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersionMatch", + "in": "query", + "description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "sendInitialEvents", + "in": "query", + "description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "timeoutSeconds", + "in": "query", + "description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", + "schema": { + "type": "integer", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + } + }, + "x-kubernetes-action": "deletecollection", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "parameters": [ + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, + "/apis/logsdrilldown.grafana.app/v1alpha1/namespaces/{namespace}/logsdrilldowndefaultcolumns/{name}": { + "get": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "read the specified LogsDrilldownDefaultColumns", + "operationId": "getLogsDrilldownDefaultColumns", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "get", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "put": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "replace the specified LogsDrilldownDefaultColumns", + "operationId": "replaceLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "put", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "delete": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "delete LogsDrilldownDefaultColumns", + "operationId": "deleteLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "gracePeriodSeconds", + "in": "query", + "description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "ignoreStoreReadErrorWithClusterBreakingPotential", + "in": "query", + "description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "orphanDependents", + "in": "query", + "description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "propagationPolicy", + "in": "query", + "description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + }, + "202": { + "description": "Accepted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + } + }, + "x-kubernetes-action": "delete", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "patch": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "partially update the specified LogsDrilldownDefaultColumns", + "operationId": "updateLogsDrilldownDefaultColumns", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "force", + "in": "query", + "description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/apply-patch+yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/strategic-merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "patch", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "parameters": [ + { + "name": "name", + "in": "path", + "description": "name of the LogsDrilldownDefaultColumns", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, + "/apis/logsdrilldown.grafana.app/v1alpha1/namespaces/{namespace}/logsdrilldowndefaultcolumns/{name}/status": { + "get": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "read status of the specified LogsDrilldownDefaultColumns", + "operationId": "getLogsDrilldownDefaultColumnsStatus", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "get", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "put": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "replace status of the specified LogsDrilldownDefaultColumns", + "operationId": "replaceLogsDrilldownDefaultColumnsStatus", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "put", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "patch": { + "tags": [ + "LogsDrilldownDefaultColumns" + ], + "description": "partially update status of the specified LogsDrilldownDefaultColumns", + "operationId": "updateLogsDrilldownDefaultColumnsStatus", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "force", + "in": "query", + "description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/apply-patch+yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/strategic-merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + } + } + } + }, + "x-kubernetes-action": "patch", + "x-kubernetes-group-version-kind": { + "group": "logsdrilldown.grafana.app", + "version": "v1alpha1", + "kind": "LogsDrilldownDefaultColumns" + } + }, + "parameters": [ + { + "name": "name", + "in": "path", + "description": "name of the LogsDrilldownDefaultColumns", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, "/apis/logsdrilldown.grafana.app/v1alpha1/namespaces/{namespace}/logsdrilldowndefaults": { "get": { "tags": [ @@ -2318,6 +3438,204 @@ } ] }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns": { + "type": "object", + "required": [ + "kind", + "apiVersion", + "metadata", + "spec" + ], + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" + } + ] + }, + "spec": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsSpec" + }, + "status": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsStatus" + } + }, + "x-kubernetes-group-version-kind": [ + { + "group": "logsdrilldown.grafana.app", + "kind": "LogsDrilldownDefaultColumns", + "version": "v1alpha1" + } + ] + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsList": { + "type": "object", + "required": [ + "metadata", + "items" + ], + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "type": "array", + "items": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumns" + } + ] + } + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" + } + ] + } + }, + "x-kubernetes-group-version-kind": [ + { + "group": "logsdrilldown.grafana.app", + "kind": "LogsDrilldownDefaultColumnsList", + "version": "v1alpha1" + } + ] + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel": { + "type": "object", + "required": [ + "key", + "value" + ], + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + }, + "additionalProperties": false + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels": { + "type": "array", + "items": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsLabel" + } + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord": { + "type": "object", + "required": [ + "columns", + "labels" + ], + "properties": { + "columns": { + "type": "array", + "items": { + "type": "string" + } + }, + "labels": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsLabels" + } + }, + "additionalProperties": false + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords": { + "type": "array", + "items": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsRecord" + } + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsOperatorState": { + "type": "object", + "required": [ + "lastEvaluation", + "state" + ], + "properties": { + "descriptiveState": { + "description": "descriptiveState is an optional more descriptive state field which has no requirements on format", + "type": "string" + }, + "details": { + "description": "details contains any extra information that is operator-specific", + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {} + } + }, + "lastEvaluation": { + "description": "lastEvaluation is the ResourceVersion last evaluated", + "type": "string" + }, + "state": { + "description": "state describes the state of the lastEvaluation.\nIt is limited to three possible states for machine evaluation.", + "type": "string", + "enum": [ + "success", + "in_progress", + "failed" + ] + } + }, + "additionalProperties": false + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsSpec": { + "type": "object", + "required": [ + "records" + ], + "properties": { + "records": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsLogsDefaultColumnsRecords" + } + }, + "additionalProperties": false + }, + "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsStatus": { + "type": "object", + "properties": { + "additionalFields": { + "description": "additionalFields is reserved for future use", + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {} + } + }, + "operatorStates": { + "description": "operatorStates is a map of operator ID to operator state evaluations.\nAny operator which consumes this kind SHOULD add its state evaluation information to this field.", + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaultColumnsOperatorState" + } + } + }, + "additionalProperties": false + }, "com.github.grafana.grafana.apps.logsdrilldown.pkg.apis.logsdrilldown.v1alpha1.LogsDrilldownDefaults": { "type": "object", "required": [ diff --git a/pkg/tests/apis/openapi_snapshots/provisioning.grafana.app-v0alpha1.json b/pkg/tests/apis/openapi_snapshots/provisioning.grafana.app-v0alpha1.json index f99b8f60738..8952906ac29 100644 --- a/pkg/tests/apis/openapi_snapshots/provisioning.grafana.app-v0alpha1.json +++ b/pkg/tests/apis/openapi_snapshots/provisioning.grafana.app-v0alpha1.json @@ -36,6 +36,1126 @@ } } }, + "/apis/provisioning.grafana.app/v0alpha1/namespaces/{namespace}/connections": { + "get": { + "tags": [ + "Connection" + ], + "description": "list or watch objects of kind Connection", + "operationId": "listConnection", + "parameters": [ + { + "name": "allowWatchBookmarks", + "in": "query", + "description": "allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "continue", + "in": "query", + "description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "labelSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "limit", + "in": "query", + "description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "resourceVersion", + "in": "query", + "description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersionMatch", + "in": "query", + "description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "sendInitialEvents", + "in": "query", + "description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "timeoutSeconds", + "in": "query", + "description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "watch", + "in": "query", + "description": "Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList" + } + }, + "application/json;stream=watch": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList" + } + }, + "application/vnd.kubernetes.protobuf;stream=watch": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList" + } + } + } + } + }, + "x-kubernetes-action": "list", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "post": { + "tags": [ + "Connection" + ], + "description": "create a Connection", + "operationId": "createConnection", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "202": { + "description": "Accepted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "post", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "delete": { + "tags": [ + "Connection" + ], + "description": "delete collection of Connection", + "operationId": "deletecollectionConnection", + "parameters": [ + { + "name": "continue", + "in": "query", + "description": "The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\".\n\nThis field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their fields. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "gracePeriodSeconds", + "in": "query", + "description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "ignoreStoreReadErrorWithClusterBreakingPotential", + "in": "query", + "description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "labelSelector", + "in": "query", + "description": "A selector to restrict the list of returned objects by their labels. Defaults to everything.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "limit", + "in": "query", + "description": "limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true.\n\nThe server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "orphanDependents", + "in": "query", + "description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "propagationPolicy", + "in": "query", + "description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersion", + "in": "query", + "description": "resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "resourceVersionMatch", + "in": "query", + "description": "resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details.\n\nDefaults to unset", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "sendInitialEvents", + "in": "query", + "description": "`sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched.\n\nWhen `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan\n is interpreted as \"data at least as new as the provided `resourceVersion`\"\n and the bookmark event is send when the state is synced\n to a `resourceVersion` at least as fresh as the one provided by the ListOptions.\n If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the\n bookmark event is send when the state is synced at least to the moment\n when request started being processed.\n- `resourceVersionMatch` set to any other value or unset\n Invalid error is returned.\n\nDefaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "timeoutSeconds", + "in": "query", + "description": "Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.", + "schema": { + "type": "integer", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + } + }, + "x-kubernetes-action": "deletecollection", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "parameters": [ + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, + "/apis/provisioning.grafana.app/v0alpha1/namespaces/{namespace}/connections/{name}": { + "get": { + "tags": [ + "Connection" + ], + "description": "read the specified Connection", + "operationId": "getConnection", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "get", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "put": { + "tags": [ + "Connection" + ], + "description": "replace the specified Connection", + "operationId": "replaceConnection", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "put", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "delete": { + "tags": [ + "Connection" + ], + "description": "delete a Connection", + "operationId": "deleteConnection", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "gracePeriodSeconds", + "in": "query", + "description": "The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.", + "schema": { + "type": "integer", + "uniqueItems": true + } + }, + { + "name": "ignoreStoreReadErrorWithClusterBreakingPotential", + "in": "query", + "description": "if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "orphanDependents", + "in": "query", + "description": "Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + }, + { + "name": "propagationPolicy", + "in": "query", + "description": "Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + }, + "202": { + "description": "Accepted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Status" + } + } + } + } + }, + "x-kubernetes-action": "delete", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "patch": { + "tags": [ + "Connection" + ], + "description": "partially update the specified Connection", + "operationId": "updateConnection", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "force", + "in": "query", + "description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/apply-patch+yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/strategic-merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "patch", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "parameters": [ + { + "name": "name", + "in": "path", + "description": "name of the Connection", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, + "/apis/provisioning.grafana.app/v0alpha1/namespaces/{namespace}/connections/{name}/status": { + "get": { + "tags": [ + "Connection" + ], + "description": "read status of the specified Connection", + "operationId": "getConnectionStatus", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "get", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "put": { + "tags": [ + "Connection" + ], + "description": "replace status of the specified Connection", + "operationId": "replaceConnectionStatus", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "put", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "patch": { + "tags": [ + "Connection" + ], + "description": "partially update status of the specified Connection", + "operationId": "updateConnectionStatus", + "parameters": [ + { + "name": "dryRun", + "in": "query", + "description": "When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldManager", + "in": "query", + "description": "fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "fieldValidation", + "in": "query", + "description": "fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.", + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "force", + "in": "query", + "description": "Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.", + "schema": { + "type": "boolean", + "uniqueItems": true + } + } + ], + "requestBody": { + "content": { + "application/apply-patch+yaml": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/json-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + }, + "application/strategic-merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.Patch" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/vnd.kubernetes.protobuf": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + }, + "application/yaml": { + "schema": { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + } + } + } + }, + "x-kubernetes-action": "patch", + "x-kubernetes-group-version-kind": { + "group": "provisioning.grafana.app", + "version": "v0alpha1", + "kind": "Connection" + } + }, + "parameters": [ + { + "name": "name", + "in": "path", + "description": "name of the Connection", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "namespace", + "in": "path", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "schema": { + "type": "string", + "uniqueItems": true + } + }, + { + "name": "pretty", + "in": "query", + "description": "If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget).", + "schema": { + "type": "string", + "uniqueItems": true + } + } + ] + }, "/apis/provisioning.grafana.app/v0alpha1/namespaces/{namespace}/jobs": { "get": { "tags": [ @@ -3198,6 +4318,19 @@ } } }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.BitbucketConnectionConfig": { + "type": "object", + "required": [ + "clientID" + ], + "properties": { + "clientID": { + "description": "App client ID", + "type": "string", + "default": "" + } + } + }, "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.BitbucketRepositoryConfig": { "type": "object", "required": [ @@ -3223,6 +4356,227 @@ } } }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection": { + "description": "When this code is changed, make sure to update the code generation. As of writing, this can be done via the hack dir in the root of the repo: ./hack/update-codegen.sh provisioning If you've opened the generated files in this dir at some point in VSCode, you may also have to re-open them to clear errors.", + "type": "object", + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" + } + ] + }, + "secure": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionSecure" + } + ] + }, + "spec": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionSpec" + } + ] + }, + "status": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionStatus" + } + ] + } + }, + "x-kubernetes-group-version-kind": [ + { + "group": "provisioning.grafana.app", + "kind": "Connection", + "version": "v0alpha1" + } + ] + }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionInfo": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string", + "default": "" + } + } + }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionList": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "apiVersion": { + "description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + "type": "string" + }, + "items": { + "type": "array", + "items": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.Connection" + } + ] + }, + "x-kubernetes-list-type": "atomic" + }, + "kind": { + "description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + "type": "string" + }, + "metadata": { + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" + } + ] + } + }, + "x-kubernetes-group-version-kind": [ + { + "group": "provisioning.grafana.app", + "kind": "ConnectionList", + "version": "v0alpha1" + } + ] + }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionSecure": { + "type": "object", + "properties": { + "clientSecret": { + "description": "ClientSecret is the reference to the secret used for other providers authentication, and Github on-behalf-of authentication. This value is stored securely and cannot be read back", + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apimachinery.apis.common.v0alpha1.InlineSecureValue" + } + ] + }, + "privateKey": { + "description": "PrivateKey is the reference to the private key used for GitHub App authentication. This value is stored securely and cannot be read back", + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apimachinery.apis.common.v0alpha1.InlineSecureValue" + } + ] + }, + "webhook": { + "description": "Token is the reference of the token used to act as the Connection. This value is stored securely and cannot be read back", + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.pkg.apimachinery.apis.common.v0alpha1.InlineSecureValue" + } + ] + } + } + }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionSpec": { + "type": "object", + "required": [ + "type" + ], + "properties": { + "bitbucket": { + "description": "Bitbucket connection configuration Only applicable when provider is \"bitbucket\"", + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.BitbucketConnectionConfig" + } + ] + }, + "github": { + "description": "GitHub connection configuration Only applicable when provider is \"github\"", + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.GitHubConnectionConfig" + } + ] + }, + "gitlab": { + "description": "Gitlab connection configuration Only applicable when provider is \"gitlab\"", + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.GitlabConnectionConfig" + } + ] + }, + "type": { + "description": "The connection provider type\n\nPossible enum values:\n - `\"bitbucket\"`\n - `\"github\"`\n - `\"gitlab\"`", + "type": "string", + "default": "", + "enum": [ + "bitbucket", + "github", + "gitlab" + ] + }, + "url": { + "description": "The connection URL", + "type": "string" + } + } + }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionStatus": { + "description": "The status of a Connection. This is expected never to be created by a kubectl call or similar, and is expected to rarely (if ever) be edited manually.", + "type": "object", + "required": [ + "observedGeneration", + "state", + "health" + ], + "properties": { + "health": { + "description": "The connection health status", + "default": {}, + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.HealthStatus" + } + ] + }, + "observedGeneration": { + "description": "The generation of the spec last time reconciliation ran", + "type": "integer", + "format": "int64", + "default": 0 + }, + "state": { + "description": "Connection state\n\nPossible enum values:\n - `\"connected\"`\n - `\"disconnected\"`", + "type": "string", + "default": "", + "enum": [ + "connected", + "disconnected" + ] + } + } + }, "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.DeleteJobOptions": { "type": "object", "properties": { @@ -3344,6 +4698,25 @@ } } }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.GitHubConnectionConfig": { + "type": "object", + "required": [ + "appID", + "installationID" + ], + "properties": { + "appID": { + "description": "GitHub App ID", + "type": "string", + "default": "" + }, + "installationID": { + "description": "GitHub App installation ID", + "type": "string", + "default": "" + } + } + }, "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.GitHubRepositoryConfig": { "type": "object", "required": [ @@ -3415,6 +4788,19 @@ } } }, + "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.GitlabConnectionConfig": { + "type": "object", + "required": [ + "clientID" + ], + "properties": { + "clientID": { + "description": "App client ID", + "type": "string", + "default": "" + } + } + }, "com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.HealthStatus": { "type": "object", "required": [ @@ -3696,7 +5082,7 @@ "format": "int64" }, "errors": { - "description": "Report errors for this resource type This may not be an exhaustive list and recommend looking at the logs for more info", + "description": "Report errors/warnings for this resource type This may not be an exhaustive list and recommend looking at the logs for more info", "type": "array", "items": { "type": "string", @@ -3722,6 +5108,18 @@ "type": "integer", "format": "int64" }, + "warning": { + "description": "The error count", + "type": "integer", + "format": "int64" + }, + "warnings": { + "type": "array", + "items": { + "type": "string", + "default": "" + } + }, "write": { "type": "integer", "format": "int64" @@ -3849,6 +5247,13 @@ "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.RepositoryURLs" } ] + }, + "warnings": { + "type": "array", + "items": { + "type": "string", + "default": "" + } } } }, @@ -4132,6 +5537,14 @@ } ] }, + "connection": { + "description": "The connection the repository references. This means the Repository is interacting with git via a Connection.", + "allOf": [ + { + "$ref": "#/components/schemas/com.github.grafana.grafana.apps.provisioning.pkg.apis.provisioning.v0alpha1.ConnectionInfo" + } + ] + }, "description": { "description": "Repository description", "type": "string" diff --git a/pkg/tests/apis/plugins/discovery_test.go b/pkg/tests/apis/plugins/discovery_test.go index a6e507a630b..5e211cc45a1 100644 --- a/pkg/tests/apis/plugins/discovery_test.go +++ b/pkg/tests/apis/plugins/discovery_test.go @@ -21,19 +21,19 @@ func TestIntegrationPluginsIntegrationDiscovery(t *testing.T) { "freshness": "Current", "resources": [ { - "resource": "pluginmetas", + "resource": "metas", "responseKind": { "group": "", - "kind": "PluginMeta", + "kind": "Meta", "version": "" }, "scope": "Namespaced", - "singularResource": "pluginmeta", + "singularResource": "meta", "subresources": [ { "responseKind": { "group": "", - "kind": "PluginMeta", + "kind": "Meta", "version": "" }, "subresource": "status", diff --git a/pkg/tests/apis/plugins/pluginmeta_test.go b/pkg/tests/apis/plugins/metas_test.go similarity index 52% rename from pkg/tests/apis/plugins/pluginmeta_test.go rename to pkg/tests/apis/plugins/metas_test.go index af70f02a6f8..c240d3fb91d 100644 --- a/pkg/tests/apis/plugins/pluginmeta_test.go +++ b/pkg/tests/apis/plugins/metas_test.go @@ -15,6 +15,72 @@ import ( func TestIntegrationPluginMeta(t *testing.T) { testutil.SkipIntegrationTestInShortMode(t) + t.Run("list plugin metas", func(t *testing.T) { + helper := setupHelper(t) + ctx := context.Background() + client := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + GVR: gvrPlugins, + }) + + plugin1Name := "test-plugin-metas-1" + plugin1 := helper.LoadYAMLOrJSON(fmt.Sprintf(`{ + "apiVersion": "plugins.grafana.app/v0alpha1", + "kind": "Plugin", + "metadata": {"name": "%s"}, + "spec": {"id": "grafana-piechart-panel", "version": "1.0.0"} + }`, plugin1Name)) + _, err := client.Resource.Create(ctx, plugin1, metav1.CreateOptions{}) + require.NoError(t, err) + + plugin2Name := "test-plugin-metas-2" + plugin2 := helper.LoadYAMLOrJSON(fmt.Sprintf(`{ + "apiVersion": "plugins.grafana.app/v0alpha1", + "kind": "Plugin", + "metadata": {"name": "%s"}, + "spec": {"id": "grafana-clock-panel", "version": "1.0.0"} + }`, plugin2Name)) + _, err = client.Resource.Create(ctx, plugin2, metav1.CreateOptions{}) + require.NoError(t, err) + + namespace := helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()) + path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/metas", namespace) + response := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, &pluginsv0alpha1.MetaList{}) + + require.NotNil(t, response.Result) + require.NotNil(t, response.Result.Items) + require.GreaterOrEqual(t, len(response.Result.Items), 2) + + foundIDs := make(map[string]bool) + for _, item := range response.Result.Items { + require.NotNil(t, item.Spec.PluginJSON) + foundIDs[item.Spec.PluginJSON.Id] = true + require.NotEmpty(t, item.Spec.PluginJSON.Id) + require.NotEmpty(t, item.Spec.PluginJSON.Type) + require.NotEmpty(t, item.Spec.PluginJSON.Name) + } + require.True(t, foundIDs["grafana-piechart-panel"]) + require.True(t, foundIDs["grafana-clock-panel"]) + }) + + t.Run("list plugin metas with no plugins", func(t *testing.T) { + helper := setupHelper(t) + namespace := helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()) + path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/metas", namespace) + response := apis.DoRequest(helper, apis.RequestParams{ + User: helper.Org1.Admin, + Method: "GET", + Path: path, + }, &pluginsv0alpha1.MetaList{}) + + require.NotNil(t, response.Result) + require.NotNil(t, response.Result.Items) + require.GreaterOrEqual(t, len(response.Result.Items), 0) + }) t.Run("get plugin meta", func(t *testing.T) { helper := setupHelper(t) @@ -35,12 +101,12 @@ func TestIntegrationPluginMeta(t *testing.T) { require.NoError(t, err) namespace := helper.Org1.Admin.Identity.GetNamespace() - path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/pluginmetas/%s", namespace, pluginName) + path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/metas/%s", namespace, pluginName) response := apis.DoRequest(helper, apis.RequestParams{ User: helper.Org1.Admin, Method: "GET", Path: path, - }, &pluginsv0alpha1.PluginMeta{}) + }, &pluginsv0alpha1.Meta{}) require.NotNil(t, response.Result) require.NotNil(t, response.Result.Spec.PluginJSON) @@ -52,12 +118,12 @@ func TestIntegrationPluginMeta(t *testing.T) { t.Run("get plugin meta for non-existent plugin", func(t *testing.T) { helper := setupHelper(t) namespace := helper.Org1.Admin.Identity.GetNamespace() - path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/pluginmetas/non-existent-plugin", namespace) + path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/metas/non-existent-plugin", namespace) response := apis.DoRequest(helper, apis.RequestParams{ User: helper.Org1.Admin, Method: "GET", Path: path, - }, &pluginsv0alpha1.PluginMeta{}) + }, &pluginsv0alpha1.Meta{}) require.NotNil(t, response.Status) require.Equal(t, int32(404), response.Status.Code) @@ -82,12 +148,12 @@ func TestIntegrationPluginMeta(t *testing.T) { require.NoError(t, err) namespace := helper.Org1.Admin.Identity.GetNamespace() - path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/pluginmetas/%s", namespace, pluginName) + path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/metas/%s", namespace, pluginName) response := apis.DoRequest(helper, apis.RequestParams{ User: helper.Org1.Admin, Method: "GET", Path: path, - }, &pluginsv0alpha1.PluginMeta{}) + }, &pluginsv0alpha1.Meta{}) require.NotNil(t, response.Status) require.Equal(t, int32(404), response.Status.Code) diff --git a/pkg/tests/apis/plugins/pluginmetas_test.go b/pkg/tests/apis/plugins/pluginmetas_test.go deleted file mode 100644 index 1ffe8d35a50..00000000000 --- a/pkg/tests/apis/plugins/pluginmetas_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package plugins - -import ( - "context" - "fmt" - "testing" - - "github.com/stretchr/testify/require" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - pluginsv0alpha1 "github.com/grafana/grafana/apps/plugins/pkg/apis/plugins/v0alpha1" - "github.com/grafana/grafana/pkg/tests/apis" - "github.com/grafana/grafana/pkg/util/testutil" -) - -func TestIntegrationPluginMetas(t *testing.T) { - testutil.SkipIntegrationTestInShortMode(t) - - t.Run("list plugin metas", func(t *testing.T) { - helper := setupHelper(t) - ctx := context.Background() - client := helper.GetResourceClient(apis.ResourceClientArgs{ - User: helper.Org1.Admin, - GVR: gvrPlugins, - }) - - plugin1Name := "test-plugin-metas-1" - plugin1 := helper.LoadYAMLOrJSON(fmt.Sprintf(`{ - "apiVersion": "plugins.grafana.app/v0alpha1", - "kind": "Plugin", - "metadata": {"name": "%s"}, - "spec": {"id": "grafana-piechart-panel", "version": "1.0.0"} - }`, plugin1Name)) - _, err := client.Resource.Create(ctx, plugin1, metav1.CreateOptions{}) - require.NoError(t, err) - - plugin2Name := "test-plugin-metas-2" - plugin2 := helper.LoadYAMLOrJSON(fmt.Sprintf(`{ - "apiVersion": "plugins.grafana.app/v0alpha1", - "kind": "Plugin", - "metadata": {"name": "%s"}, - "spec": {"id": "grafana-clock-panel", "version": "1.0.0"} - }`, plugin2Name)) - _, err = client.Resource.Create(ctx, plugin2, metav1.CreateOptions{}) - require.NoError(t, err) - - namespace := helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()) - path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/pluginmetas", namespace) - response := apis.DoRequest(helper, apis.RequestParams{ - User: helper.Org1.Admin, - Method: "GET", - Path: path, - }, &pluginsv0alpha1.PluginMetaList{}) - - require.NotNil(t, response.Result) - require.NotNil(t, response.Result.Items) - require.GreaterOrEqual(t, len(response.Result.Items), 2) - - foundIDs := make(map[string]bool) - for _, item := range response.Result.Items { - require.NotNil(t, item.Spec.PluginJSON) - foundIDs[item.Spec.PluginJSON.Id] = true - require.NotEmpty(t, item.Spec.PluginJSON.Id) - require.NotEmpty(t, item.Spec.PluginJSON.Type) - require.NotEmpty(t, item.Spec.PluginJSON.Name) - } - require.True(t, foundIDs["grafana-piechart-panel"]) - require.True(t, foundIDs["grafana-clock-panel"]) - }) - - t.Run("list plugin metas with no plugins", func(t *testing.T) { - helper := setupHelper(t) - namespace := helper.Namespacer(helper.Org1.Admin.Identity.GetOrgID()) - path := fmt.Sprintf("/apis/plugins.grafana.app/v0alpha1/namespaces/%s/pluginmetas", namespace) - response := apis.DoRequest(helper, apis.RequestParams{ - User: helper.Org1.Admin, - Method: "GET", - Path: path, - }, &pluginsv0alpha1.PluginMetaList{}) - - require.NotNil(t, response.Result) - require.NotNil(t, response.Result.Items) - require.GreaterOrEqual(t, len(response.Result.Items), 0) - }) -} diff --git a/pkg/tests/apis/plugins/plugininstalls_test.go b/pkg/tests/apis/plugins/plugins_test.go similarity index 100% rename from pkg/tests/apis/plugins/plugininstalls_test.go rename to pkg/tests/apis/plugins/plugins_test.go diff --git a/pkg/tests/apis/provisioning/connection_test.go b/pkg/tests/apis/provisioning/connection_test.go new file mode 100644 index 00000000000..ea28ac88359 --- /dev/null +++ b/pkg/tests/apis/provisioning/connection_test.go @@ -0,0 +1,413 @@ +package provisioning + +import ( + "context" + "errors" + "testing" + + "github.com/grafana/grafana/pkg/util/testutil" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +func TestIntegrationProvisioning_ConnectionCRUDL(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + createOptions := metav1.CreateOptions{FieldValidation: "Strict"} + ctx := context.Background() + + t.Run("should perform CRUDL requests on connection", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "123456", + "installationID": "454545", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + // CREATE + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.NoError(t, err, "failed to create resource") + + // READ + output, err := helper.Connections.Resource.Get(ctx, "connection", metav1.GetOptions{}) + require.NoError(t, err, "failed to read back resource") + assert.Equal(t, "connection", output.GetName(), "name should be equal") + assert.Equal(t, "default", output.GetNamespace(), "namespace should be equal") + spec := output.Object["spec"].(map[string]any) + assert.Equal(t, "github", spec["type"], "type should be equal") + assert.Equal(t, "https://github.com/settings/installations/454545", spec["url"], "url should be equal") + require.Contains(t, spec, "github") + githubInfo := spec["github"].(map[string]any) + assert.Equal(t, "123456", githubInfo["appID"], "appID should be equal") + assert.Equal(t, "454545", githubInfo["installationID"], "installationID should be equal") + require.Contains(t, output.Object, "secure", "object should contain secure") + assert.Contains(t, output.Object["secure"], "privateKey", "secure should contain PrivateKey") + + // LIST + list, err := helper.Connections.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err, "failed to list resource") + assert.Equal(t, 1, len(list.Items), "should have one connection") + assert.Equal(t, "connection", list.Items[0].GetName(), "name should be equal") + + // UPDATE + updatedConnection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "456789", + "installationID": "454545", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + res, err := helper.Connections.Resource.Update(ctx, updatedConnection, metav1.UpdateOptions{}) + require.NoError(t, err, "failed to update resource") + spec = res.Object["spec"].(map[string]any) + require.Contains(t, spec, "github") + githubInfo = spec["github"].(map[string]any) + assert.Equal(t, "456789", githubInfo["appID"], "appID should be updated") + + // DELETE + require.NoError(t, helper.Connections.Resource.Delete(ctx, "connection", metav1.DeleteOptions{}), "failed to delete resource") + list, err = helper.Connections.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err, "failed to list resources") + assert.Equal(t, 0, len(list.Items), "should have no connections") + }) + + t.Run("viewer can't create or get connection", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "123456", + "installationID": "454545", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + + result := helper.ViewerREST.Post(). + Namespace("default"). + Resource("connections"). + Body(connection). + Do(t.Context()) + + require.NotNil(t, result.Error()) + err := &k8serrors.StatusError{} + require.True(t, errors.As(result.Error(), &err)) + assert.Equal(t, metav1.StatusReasonForbidden, err.Status().Reason) + assert.Contains(t, err.Status().Message, "User \"viewer\" cannot create resource \"connections\"") + assert.Contains(t, err.Status().Message, "admin role is required") + + result = helper.ViewerREST.Get(). + Namespace("default"). + Resource("connections"). + Name("connection"). + Do(t.Context()) + require.NotNil(t, result.Error()) + err = &k8serrors.StatusError{} + require.True(t, errors.As(result.Error(), &err)) + assert.Equal(t, metav1.StatusReasonForbidden, err.Status().Reason) + assert.Contains(t, err.Status().Message, "User \"viewer\" cannot get resource \"connections\"") + assert.Contains(t, err.Status().Message, "admin role is required") + }) +} + +func TestIntegrationProvisioning_ConnectionValidation(t *testing.T) { + helper := runGrafana(t) + createOptions := metav1.CreateOptions{FieldValidation: "Strict"} + ctx := context.Background() + + t.Run("should fail when type is empty", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "", + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "type must be specified") + }) + + t.Run("should fail when type is invalid", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "some-invalid-type", + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "spec.type: Unsupported value: \"some-invalid-type\"") + }) + + t.Run("should fail when type is github but 'github' field is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "github info must be specified for GitHub connection") + }) + + t.Run("should fail when type is github but private key is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "123456", + "installationID": "454545", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "privateKey must be specified for GitHub connection") + }) + + t.Run("should fail when type is github but a client Secret is specified", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "github", + "github": map[string]any{ + "appID": "123456", + "installationID": "454545", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + "clientSecret": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "clientSecret is forbidden in GitHub connection") + }) + + t.Run("should fail when type is bitbucket but 'bitbucket' field is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "bitbucket", + }, + "secure": map[string]any{ + "clientSecret": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "bitbucket info must be specified in Bitbucket connection") + }) + + t.Run("should fail when type is bitbucket but client secret is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "bitbucket", + "bitbucket": map[string]any{ + "clientID": "123456", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "clientSecret must be specified for Bitbucket connection") + }) + + t.Run("should fail when type is bitbucket but a private key is specified", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "bitbucket", + "bitbucket": map[string]any{ + "clientID": "123456", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + "clientSecret": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "privateKey is forbidden in Bitbucket connection") + }) + + t.Run("should fail when type is gitlab but 'gitlab' field is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "gitlab", + }, + "secure": map[string]any{ + "clientSecret": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "gitlab info must be specified in Gitlab connection") + }) + + t.Run("should fail when type is gitlab but client secret is not there", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "gitlab", + "gitlab": map[string]any{ + "clientID": "123456", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "clientSecret must be specified for Gitlab connection") + }) + + t.Run("should fail when type is gitlab but a private key is specified", func(t *testing.T) { + connection := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "provisioning.grafana.app/v0alpha1", + "kind": "Connection", + "metadata": map[string]any{ + "name": "connection", + "namespace": "default", + }, + "spec": map[string]any{ + "type": "gitlab", + "gitlab": map[string]any{ + "clientID": "123456", + }, + }, + "secure": map[string]any{ + "privateKey": map[string]any{ + "create": "someSecret", + }, + "clientSecret": map[string]any{ + "create": "someSecret", + }, + }, + }} + _, err := helper.Connections.Resource.Create(ctx, connection, createOptions) + require.Error(t, err, "failed to create resource") + assert.Contains(t, err.Error(), "privateKey is forbidden in Gitlab connection") + }) +} diff --git a/pkg/tests/apis/provisioning/fieldselector_test.go b/pkg/tests/apis/provisioning/fieldselector_test.go new file mode 100644 index 00000000000..78f05eeacb7 --- /dev/null +++ b/pkg/tests/apis/provisioning/fieldselector_test.go @@ -0,0 +1,211 @@ +package provisioning + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + provisioning "github.com/grafana/grafana/apps/provisioning/pkg/apis/provisioning/v0alpha1" + "github.com/grafana/grafana/pkg/util/testutil" +) + +// TestIntegrationProvisioning_RepositoryFieldSelector tests that fieldSelector +// works correctly for Repository resources. This prevents regression where +// fieldSelector=metadata.name= was not working properly. +func TestIntegrationProvisioning_RepositoryFieldSelector(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + // Create multiple repositories for testing + repo1Name := "repo-selector-test-1" + repo2Name := "repo-selector-test-2" + repo3Name := "repo-selector-test-3" + + // Create first repository + repo1 := helper.RenderObject(t, "testdata/local-write.json.tmpl", map[string]any{ + "Name": repo1Name, + "SyncEnabled": false, // Disable sync to speed up test + }) + _, err := helper.Repositories.Resource.Create(ctx, repo1, metav1.CreateOptions{}) + require.NoError(t, err, "failed to create first repository") + helper.WaitForHealthyRepository(t, repo1Name) + + // Create second repository + repo2 := helper.RenderObject(t, "testdata/local-write.json.tmpl", map[string]any{ + "Name": repo2Name, + "SyncEnabled": false, + }) + _, err = helper.Repositories.Resource.Create(ctx, repo2, metav1.CreateOptions{}) + require.NoError(t, err, "failed to create second repository") + helper.WaitForHealthyRepository(t, repo2Name) + + // Create third repository + repo3 := helper.RenderObject(t, "testdata/local-write.json.tmpl", map[string]any{ + "Name": repo3Name, + "SyncEnabled": false, + }) + _, err = helper.Repositories.Resource.Create(ctx, repo3, metav1.CreateOptions{}) + require.NoError(t, err, "failed to create third repository") + helper.WaitForHealthyRepository(t, repo3Name) + + // Verify all repositories were created + allRepos, err := helper.Repositories.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err, "should be able to list all repositories") + require.GreaterOrEqual(t, len(allRepos.Items), 3, "should have at least 3 repositories") + + t.Run("should filter by metadata.name and return single repository", func(t *testing.T) { + list, err := helper.Repositories.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=" + repo2Name, + }) + require.NoError(t, err, "fieldSelector query should succeed") + require.Len(t, list.Items, 1, "should return exactly one repository") + require.Equal(t, repo2Name, list.Items[0].GetName(), "should return the correct repository") + }) + + t.Run("should filter by different metadata.name", func(t *testing.T) { + list, err := helper.Repositories.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=" + repo1Name, + }) + require.NoError(t, err, "fieldSelector query should succeed") + require.Len(t, list.Items, 1, "should return exactly one repository") + require.Equal(t, repo1Name, list.Items[0].GetName(), "should return the first repository") + }) + + t.Run("should return empty when fieldSelector does not match any repository", func(t *testing.T) { + list, err := helper.Repositories.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=non-existent-repository", + }) + require.NoError(t, err, "fieldSelector query should succeed even with no matches") + require.Empty(t, list.Items, "should return empty list when no repositories match") + }) + + t.Run("listing without fieldSelector should return all repositories", func(t *testing.T) { + list, err := helper.Repositories.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err, "should be able to list without fieldSelector") + require.GreaterOrEqual(t, len(list.Items), 3, "should return all repositories when no filter is applied") + + // Verify our test repositories are in the list + names := make(map[string]bool) + for _, item := range list.Items { + names[item.GetName()] = true + } + require.True(t, names[repo1Name], "should contain repo1") + require.True(t, names[repo2Name], "should contain repo2") + require.True(t, names[repo3Name], "should contain repo3") + }) +} + +// TestIntegrationProvisioning_JobFieldSelector tests that fieldSelector +// works correctly for Job resources. This prevents regression where +// fieldSelector=metadata.name= was not working properly. +func TestIntegrationProvisioning_JobFieldSelector(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + // Create a repository to trigger jobs + repoName := "job-selector-test-repo" + repo := helper.RenderObject(t, "testdata/local-write.json.tmpl", map[string]any{ + "Name": repoName, + "SyncEnabled": false, + }) + _, err := helper.Repositories.Resource.Create(ctx, repo, metav1.CreateOptions{}) + require.NoError(t, err, "failed to create repository") + helper.WaitForHealthyRepository(t, repoName) + + // Copy some test files to trigger jobs + helper.CopyToProvisioningPath(t, "testdata/all-panels.json", "job-test-dashboard-1.json") + helper.CopyToProvisioningPath(t, "testdata/text-options.json", "job-test-dashboard-2.json") + + // Trigger multiple jobs to have multiple job resources + job1Spec := provisioning.JobSpec{ + Action: provisioning.JobActionPull, + Pull: &provisioning.SyncJobOptions{}, + } + + // Trigger first job + body1 := asJSON(job1Spec) + result1 := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repoName). + SubResource("jobs"). + Body(body1). + SetHeader("Content-Type", "application/json"). + Do(ctx) + require.NoError(t, result1.Error(), "should be able to trigger first job") + + obj1, err := result1.Get() + require.NoError(t, err, "should get first job object") + job1 := obj1.(*unstructured.Unstructured) + job1Name := job1.GetName() + require.NotEmpty(t, job1Name, "first job should have a name") + + // Wait for first job to complete before starting second + helper.AwaitJobs(t, repoName) + + // Trigger second job + result2 := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repoName). + SubResource("jobs"). + Body(body1). + SetHeader("Content-Type", "application/json"). + Do(ctx) + require.NoError(t, result2.Error(), "should be able to trigger second job") + + obj2, err := result2.Get() + require.NoError(t, err, "should get second job object") + job2 := obj2.(*unstructured.Unstructured) + job2Name := job2.GetName() + require.NotEmpty(t, job2Name, "second job should have a name") + + t.Run("should filter by metadata.name and return single job", func(t *testing.T) { + // Note: Jobs are ephemeral and may complete quickly, so we test while they exist + list, err := helper.Jobs.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=" + job2Name, + }) + require.NoError(t, err, "fieldSelector query should succeed") + + // The job might have completed already, but if it exists, it should be the only one + if len(list.Items) > 0 { + require.Len(t, list.Items, 1, "should return at most one job") + require.Equal(t, job2Name, list.Items[0].GetName(), "should return the correct job") + } + }) + + t.Run("should filter by different metadata.name", func(t *testing.T) { + list, err := helper.Jobs.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=" + job1Name, + }) + require.NoError(t, err, "fieldSelector query should succeed") + + // The job might have completed already, but if it exists, it should be the only one + if len(list.Items) > 0 { + require.Len(t, list.Items, 1, "should return at most one job") + require.Equal(t, job1Name, list.Items[0].GetName(), "should return the first job") + } + }) + + t.Run("should return empty when fieldSelector does not match any job", func(t *testing.T) { + list, err := helper.Jobs.Resource.List(ctx, metav1.ListOptions{ + FieldSelector: "metadata.name=non-existent-job", + }) + require.NoError(t, err, "fieldSelector query should succeed even with no matches") + require.Empty(t, list.Items, "should return empty list when no jobs match") + }) + + t.Run("listing without fieldSelector should work", func(t *testing.T) { + list, err := helper.Jobs.Resource.List(ctx, metav1.ListOptions{}) + require.NoError(t, err, "should be able to list without fieldSelector") + // Jobs may have completed, so we don't assert on count, just that the query works + t.Logf("Found %d active jobs without filter", len(list.Items)) + }) +} diff --git a/pkg/tests/apis/provisioning/files_test.go b/pkg/tests/apis/provisioning/files_test.go index 3eed9171578..e31674be505 100644 --- a/pkg/tests/apis/provisioning/files_test.go +++ b/pkg/tests/apis/provisioning/files_test.go @@ -1,7 +1,9 @@ package provisioning import ( + "bytes" "context" + "encoding/json" "errors" "fmt" "io" @@ -11,6 +13,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/services/accesscontrol/resourcepermissions" "github.com/grafana/grafana/pkg/util/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -68,22 +71,45 @@ func TestIntegrationProvisioning_DeleteResources(t *testing.T) { helper.validateManagedDashboardsFolderMetadata(t, ctx, repo, dashboards.Items) - t.Run("delete individual dashboard file, should delete from repo and grafana", func(t *testing.T) { + t.Run("delete individual dashboard file on configured branch should succeed", func(t *testing.T) { result := helper.AdminREST.Delete(). Namespace("default"). Resource("repositories"). Name(repo). SubResource("files", "dashboard1.json"). Do(ctx) - require.NoError(t, result.Error()) - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "dashboard1.json") - require.Error(t, err) - dashboards, err = helper.DashboardsV1.Resource.List(ctx, metav1.ListOptions{}) - require.NoError(t, err) - require.Equal(t, 2, len(dashboards.Items)) + require.NoError(t, result.Error(), "delete file on configured branch should succeed") + + // Verify the dashboard is removed from Grafana + const allPanelsUID = "n1jR8vnnz" // UID from all-panels.json + _, err := helper.DashboardsV1.Resource.Get(ctx, allPanelsUID, metav1.GetOptions{}) + require.Error(t, err, "dashboard should be deleted from Grafana") + require.True(t, apierrors.IsNotFound(err), "should return NotFound for deleted dashboard") }) - t.Run("delete folder, should delete from repo and grafana all nested resources too", func(t *testing.T) { + t.Run("delete individual dashboard file on branch should succeed", func(t *testing.T) { + // Create a branch first by creating a file on a branch + branchRef := "test-branch-delete" + helper.CopyToProvisioningPath(t, "testdata/text-options.json", "branch-test-delete.json") + + // Delete on branch should work + result := helper.AdminREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "branch-test-delete.json"). + Param("ref", branchRef). + Do(ctx) + // Note: This might fail if branch doesn't exist, but the important thing is it doesn't return MethodNotAllowed + if result.Error() != nil { + var statusErr *apierrors.StatusError + if errors.As(result.Error(), &statusErr) { + require.NotEqual(t, int32(http.StatusMethodNotAllowed), statusErr.ErrStatus.Code, "should not return MethodNotAllowed for branch delete") + } + } + }) + + t.Run("delete folder on configured branch should return MethodNotAllowed", func(t *testing.T) { // need to delete directly through the url, because the k8s client doesn't support `/` in a subresource // but that is needed by gitsync to know that it is a folder addr := helper.GetEnv().Server.HTTPServer.Listener.Addr().String() @@ -94,27 +120,11 @@ func TestIntegrationProvisioning_DeleteResources(t *testing.T) { require.NoError(t, err) // nolint:errcheck defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) + require.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode, "should return MethodNotAllowed for configured branch folder delete") - // should be deleted from the repo - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "folder") - require.Error(t, err) + // Verify a file inside the folder still exists (operation was rejected) _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "folder", "dashboard2.json") - require.Error(t, err) - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "folder", "nested") - require.Error(t, err) - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "folder", "nested", "dashboard3.json") - require.Error(t, err) - - // all should be deleted from grafana - for _, d := range dashboards.Items { - _, err = helper.DashboardsV1.Resource.Get(ctx, d.GetName(), metav1.GetOptions{}) - require.Error(t, err) - } - for _, f := range folders.Items { - _, err = helper.Folders.Resource.Get(ctx, f.GetName(), metav1.GetOptions{}) - require.Error(t, err) - } + require.NoError(t, err, "file inside folder should still exist after rejected delete") }) t.Run("deleting a non-existent file should fail", func(t *testing.T) { @@ -158,10 +168,10 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { require.NoError(t, err, "original dashboard should exist in Grafana") require.Equal(t, repo, obj.GetAnnotations()[utils.AnnoKeyManagerIdentity]) - t.Run("move file without content change", func(t *testing.T) { + t.Run("move file without content change on configured branch should succeed", func(t *testing.T) { const targetPath = "moved/simple-move.json" - // Perform the move operation using helper function + // Perform the move operation using helper function (no ref = configured branch) resp := helper.postFilesRequest(t, repo, filesPostOptions{ targetPath: targetPath, originalPath: "all-panels.json", @@ -169,32 +179,52 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { }) // nolint:errcheck defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode, "move operation should succeed") + require.Equal(t, http.StatusOK, resp.StatusCode, "move operation on configured branch should succeed") - // Verify the file moved in the repository - movedObj, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved", "simple-move.json") - require.NoError(t, err, "moved file should exist in repository") + // Verify file was moved - read from new location + _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved", "simple-move.json") + require.NoError(t, err, "file should exist at new location") - // Check the content is preserved (verify it's still the all-panels dashboard) - resource, _, err := unstructured.NestedMap(movedObj.Object, "resource") - require.NoError(t, err) - dryRun, _, err := unstructured.NestedMap(resource, "dryRun") - require.NoError(t, err) - title, _, err := unstructured.NestedString(dryRun, "spec", "title") - require.NoError(t, err) - require.Equal(t, "Panel tests - All panels", title, "content should be preserved") - - // Verify original file no longer exists + // Verify file no longer exists at old location _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "all-panels.json") - require.Error(t, err, "original file should no longer exist") - - // Verify dashboard still exists in Grafana with same content but may have updated path references - helper.SyncAndWait(t, repo, nil) - _, err = helper.DashboardsV1.Resource.Get(ctx, allPanelsUID, metav1.GetOptions{}) - require.NoError(t, err, "dashboard should still exist in Grafana after move") + require.Error(t, err, "file should not exist at old location") }) - t.Run("move file to nested path without ref", func(t *testing.T) { + t.Run("move file without content change on branch should succeed", func(t *testing.T) { + const targetPath = "moved/simple-move-branch.json" + branchRef := "test-branch-move" + + // Perform the move operation using helper function with ref parameter + resp := helper.postFilesRequest(t, repo, filesPostOptions{ + targetPath: targetPath, + originalPath: "all-panels.json", + message: "move file without content change", + ref: branchRef, + }) + // nolint:errcheck + defer resp.Body.Close() + // Note: This might fail if branch doesn't exist, but the important thing is it doesn't return MethodNotAllowed + if resp.StatusCode == http.StatusMethodNotAllowed { + t.Fatal("should not return MethodNotAllowed for branch move") + } + + // If move succeeded (not MethodNotAllowed), verify the file moved in the repository + if resp.StatusCode == http.StatusOK { + movedObj, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved", "simple-move-branch.json") + require.NoError(t, err, "moved file should exist in repository") + + // Check the content is preserved (verify it's still the all-panels dashboard) + resource, _, err := unstructured.NestedMap(movedObj.Object, "resource") + require.NoError(t, err) + dryRun, _, err := unstructured.NestedMap(resource, "dryRun") + require.NoError(t, err) + title, _, err := unstructured.NestedString(dryRun, "spec", "title") + require.NoError(t, err) + require.Equal(t, "Panel tests - All panels", title, "content should be preserved") + } + }) + + t.Run("move file to nested path on configured branch should succeed", func(t *testing.T) { // Test a different scenario: Move a file that was never synced to Grafana // This might reveal the issue if dashboard creation fails during move const sourceFile = "never-synced.json" @@ -203,7 +233,7 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { // DO NOT sync - move the file immediately without it ever being in Grafana const targetPath = "deep/nested/timeline.json" - // Perform the move operation without the file ever being synced to Grafana + // Perform the move operation without the file ever being synced to Grafana (no ref = configured branch) resp := helper.postFilesRequest(t, repo, filesPostOptions{ targetPath: targetPath, originalPath: sourceFile, @@ -211,70 +241,25 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { }) // nolint:errcheck defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode, "move operation should succeed") + require.Equal(t, http.StatusOK, resp.StatusCode, "move operation on configured branch should succeed") - // Check folders were created and validate hierarchy - folderList, err := helper.Folders.Resource.List(ctx, metav1.ListOptions{}) - require.NoError(t, err, "should be able to list folders") + // File should exist at new location + _, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "deep", "nested", "timeline.json") + require.NoError(t, err, "file should exist at new nested location") - // Build a map of folder names to their objects for easier lookup - folders := make(map[string]*unstructured.Unstructured) - for _, folder := range folderList.Items { - title, _, _ := unstructured.NestedString(folder.Object, "spec", "title") - folders[title] = &folder - parent, _, _ := unstructured.NestedString(folder.Object, "metadata", "annotations", "grafana.app/folder") - t.Logf(" - %s: %s (parent: %s)", folder.GetName(), title, parent) - } - - // Validate expected folders exist with proper hierarchy - // Expected structure: deep -> deep/nested - deepFolderTitle := "deep" - nestedFolderTitle := "nested" - - // Validate "deep" folder exists and has no parent (is top-level) - require.Contains(t, folders, deepFolderTitle, "deep folder should exist") - f := folders[deepFolderTitle] - deepFolderName := f.GetName() - title, _, _ := unstructured.NestedString(f.Object, "spec", "title") - require.Equal(t, deepFolderTitle, title, "deep folder should have correct title") - parent, found, _ := unstructured.NestedString(f.Object, "metadata", "annotations", "grafana.app/folder") - require.True(t, !found || parent == "", "deep folder should be top-level (no parent)") - - // Validate "deep/nested" folder exists and has "deep" as parent - require.Contains(t, folders, nestedFolderTitle, "nested folder should exist") - f = folders[nestedFolderTitle] - nestedFolderName := f.GetName() - title, _, _ = unstructured.NestedString(f.Object, "spec", "title") - require.Equal(t, nestedFolderTitle, title, "nested folder should have correct title") - parent, _, _ = unstructured.NestedString(f.Object, "metadata", "annotations", "grafana.app/folder") - require.Equal(t, deepFolderName, parent, "nested folder should have deep folder as parent") - - // The key test: Check if dashboard was created in Grafana during move - const timelineUID = "mIJjFy8Kz" - dashboard, err := helper.DashboardsV1.Resource.Get(ctx, timelineUID, metav1.GetOptions{}) - require.NoError(t, err, "dashboard should exist in Grafana after moving never-synced file") - dashboardFolder, _, _ := unstructured.NestedString(dashboard.Object, "metadata", "annotations", "grafana.app/folder") - - // Validate dashboard is in the correct nested folder - require.Equal(t, nestedFolderName, dashboardFolder, "dashboard should be in the nested folder") - - // Verify the file moved in the repository - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "deep", "nested", "timeline.json") - require.NoError(t, err, "moved file should exist in nested repository path") - - // Verify the original file no longer exists in the repository + // File should not exist at original location _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", sourceFile) - require.Error(t, err, "original file should no longer exist in repository") + require.Error(t, err, "file should not exist at original location after move") }) - t.Run("move file with content update", func(t *testing.T) { - const sourcePath = "moved/simple-move.json" // Use the file from previous test + t.Run("move file with content update on configured branch should succeed", func(t *testing.T) { + const sourcePath = "moved/simple-move.json" // Use the file we moved earlier const targetPath = "updated/content-updated.json" // Use text-options.json content for the update updatedContent := helper.LoadFile("testdata/text-options.json") - // Perform move with content update using helper function + // Perform move with content update using helper function (no ref = configured branch) resp := helper.postFilesRequest(t, repo, filesPostOptions{ targetPath: targetPath, originalPath: sourcePath, @@ -283,51 +268,27 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { }) // nolint:errcheck defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode, "move with content update should succeed") + require.Equal(t, http.StatusOK, resp.StatusCode, "move with content update on configured branch should succeed") - // Verify the moved file has updated content (should now be text-options dashboard) + // File should exist at new location with updated content movedObj, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "updated", "content-updated.json") - require.NoError(t, err, "moved file should exist in repository") + require.NoError(t, err, "file should exist at new location") + // Verify content was updated (should be text-options dashboard now) resource, _, err := unstructured.NestedMap(movedObj.Object, "resource") require.NoError(t, err) dryRun, _, err := unstructured.NestedMap(resource, "dryRun") require.NoError(t, err) title, _, err := unstructured.NestedString(dryRun, "spec", "title") require.NoError(t, err) - require.Equal(t, "Text options", title, "content should be updated to text-options dashboard") + require.Equal(t, "Text options", title, "content should be updated") - // Check it has the expected UID from text-options.json - name, _, err := unstructured.NestedString(dryRun, "metadata", "name") - require.NoError(t, err) - require.Equal(t, "WZ7AhQiVz", name, "should have the UID from text-options.json") - - // Verify source file no longer exists - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved", "simple-move.json") - require.Error(t, err, "source file should no longer exist") - - // Sync and verify the updated dashboard exists in Grafana - helper.SyncAndWait(t, repo, nil) - const textOptionsUID = "WZ7AhQiVz" // UID from text-options.json - updatedDashboard, err := helper.DashboardsV1.Resource.Get(ctx, textOptionsUID, metav1.GetOptions{}) - require.NoError(t, err, "updated dashboard should exist in Grafana") - - // Verify the original dashboard was deleted from Grafana - _, err = helper.DashboardsV1.Resource.Get(ctx, allPanelsUID, metav1.GetOptions{}) - require.Error(t, err, "original dashboard should be deleted from Grafana") - require.True(t, apierrors.IsNotFound(err)) - - // Verify the new dashboard has the updated content - updatedTitle, _, err := unstructured.NestedString(updatedDashboard.Object, "spec", "title") - require.NoError(t, err) - require.Equal(t, "Text options", updatedTitle) + // Source file should not exist anymore + _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", sourcePath) + require.Error(t, err, "source file should not exist after move") }) - t.Run("move directory", func(t *testing.T) { - t.Skip("Skip as implementation is broken and leaves dashboards behind in the move") - // FIXME: https://github.com/grafana/git-ui-sync-project/issues/379 - // The current implementation of moving directories is flawed. - // It will be deprecated in favor of queuing a move job + t.Run("move directory on configured branch should return MethodNotAllowed", func(t *testing.T) { // Create some files in a directory first using existing testdata files helper.CopyToProvisioningPath(t, "testdata/timeline-demo.json", "source-dir/timeline-demo.json") helper.CopyToProvisioningPath(t, "testdata/text-options.json", "source-dir/text-options.json") @@ -338,7 +299,7 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { const sourceDir = "source-dir/" const targetDir = "moved-dir/" - // Move directory using helper function + // Move directory using helper function (no ref = configured branch) resp := helper.postFilesRequest(t, repo, filesPostOptions{ targetPath: targetDir, originalPath: sourceDir, @@ -346,20 +307,11 @@ func TestIntegrationProvisioning_MoveResources(t *testing.T) { }) // nolint:errcheck defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) - require.NoError(t, err, "should read response body") - t.Logf("Response Body: %s", string(body)) - require.Equal(t, http.StatusOK, resp.StatusCode, "directory move should succeed") + require.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode, "directory move on configured branch should return MethodNotAllowed") - // Verify source directory no longer exists - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "source-dir") - require.Error(t, err, "source directory should no longer exist") - - // Verify target directory and files exist - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved-dir", "timeline-demo.json") - require.NoError(t, err, "moved timeline-demo.json should exist") - _, err = helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "moved-dir", "text-options.json") - require.NoError(t, err, "moved text-options.json should exist") + // Verify files in source directory still exist (operation was rejected) + _, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "source-dir", "timeline-demo.json") + require.NoError(t, err, "file in source directory should still exist after rejected move") }) t.Run("error cases", func(t *testing.T) { @@ -566,7 +518,7 @@ func TestIntegrationProvisioning_FilesOwnershipProtection(t *testing.T) { }) t.Run("DELETE resource owned by different repository - should fail", func(t *testing.T) { - // Create a file manually in the second repo which is already in first one + // Create a file manually in the second repo which has UID from first repo helper.CopyToProvisioningPath(t, "testdata/all-panels.json", "repo2/conflicting-delete.json") printFileTree(t, helper.ProvisioningPath) @@ -590,10 +542,7 @@ func TestIntegrationProvisioning_FilesOwnershipProtection(t *testing.T) { } // Verify it returns BadRequest (400) for ownership conflicts - if !apierrors.IsBadRequest(err) { - t.Errorf("Expected BadRequest error but got: %T - %v", err, err) - return - } + require.True(t, apierrors.IsBadRequest(err), "Expected BadRequest error but got: %T - %v", err, err) // Check error message contains ownership conflict information errorMsg := err.Error() @@ -607,7 +556,7 @@ func TestIntegrationProvisioning_FilesOwnershipProtection(t *testing.T) { targetPath: "moved-dashboard.json", originalPath: path.Join("dashboard2.json"), message: "attempt to move file from different repository", - body: string(helper.LoadFile("testdata/all-panels.json")), // Content to move with the conflicting UID + body: string(helper.LoadFile("testdata/all-panels.json")), // Content with the conflicting UID }) // nolint:errcheck defer resp.Body.Close() @@ -644,3 +593,390 @@ func TestIntegrationProvisioning_FilesOwnershipProtection(t *testing.T) { require.Equal(t, repo2, dashboard2.GetAnnotations()[utils.AnnoKeyManagerIdentity], "repo2's dashboard should still be owned by repo2") }) } + +func TestIntegrationProvisioning_FilesAuthorization(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + const repo = "auth-test-repo" + helper.CreateRepo(t, TestRepo{ + Name: repo, + Path: helper.ProvisioningPath, + Target: "instance", + Copies: map[string]string{ + "testdata/all-panels.json": "dashboard1.json", + }, + ExpectedDashboards: 1, + ExpectedFolders: 0, + }) + + // Wait for initial sync to complete + var dashboardUID string + require.EventuallyWithT(t, func(collect *assert.CollectT) { + dashboards, err := helper.DashboardsV1.Resource.List(t.Context(), metav1.ListOptions{}) + if err != nil { + collect.Errorf("could not list dashboards error: %s", err.Error()) + return + } + if len(dashboards.Items) != 1 { + collect.Errorf("should have the expected dashboards after sync. got: %d. expected: %d", len(dashboards.Items), 1) + return + } + assert.Len(collect, dashboards.Items, 1) + dashboardUID = dashboards.Items[0].GetName() + }, waitTimeoutDefault, waitIntervalDefault, "should have the expected dashboards after sync") + + // Grant permissions to Editor user for all dashboards using wildcard + // The access checker checks resource-level permissions, so we need to grant them + // Using wildcard "*" to grant permissions to all dashboards (including ones created during tests) + // Note: Viewer role gets permissions via HTTP API below, Editor gets them here via SetPermissions + helper.SetPermissions(helper.Org1.Editor, []resourcepermissions.SetResourcePermissionCommand{ + { + Actions: []string{"dashboards:read", "dashboards:write", "dashboards:delete"}, + Resource: "dashboards", + ResourceAttribute: "uid", + ResourceID: "*", + }, + }) + + // Grant view permission to Viewer role via HTTP API (for the initial dashboard) + // Note: This only grants permissions to the initial dashboard, but viewers should be able to read all + addr := helper.GetEnv().Server.HTTPServer.Listener.Addr().String() + setDashboardPermissions := func(permissions []map[string]interface{}) { + payload := map[string]interface{}{ + "items": permissions, + } + payloadBytes, err := json.Marshal(payload) + require.NoError(t, err) + url := fmt.Sprintf("http://admin:admin@%s/api/dashboards/uid/%s/permissions", addr, dashboardUID) + req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode) + require.NoError(t, resp.Body.Close()) + } + + // Grant view permission to Viewer role for the initial dashboard + setDashboardPermissions([]map[string]interface{}{ + {"role": "Viewer", "permission": 1}, // View permission + }) + + t.Run("GET operations", func(t *testing.T) { + t.Run("viewer can GET files", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "dashboard1.json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "viewer should be able to GET files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("editor can GET files", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "dashboard1.json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to GET files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("admin can GET files", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Get(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "dashboard1.json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to GET files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + }) + + t.Run("POST operations", func(t *testing.T) { + t.Run("viewer cannot POST files", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "viewer-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to POST files") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("editor can POST files", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "editor-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to POST files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + + // Clean up + helper.AdminREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "editor-test.json"). + Do(ctx) + }) + + t.Run("admin can POST files", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "admin-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to POST files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + + // Clean up + helper.AdminREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "admin-test.json"). + Do(ctx) + }) + }) + + t.Run("PUT operations", func(t *testing.T) { + // Create a test file first using admin + helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "update-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx) + + t.Run("viewer cannot PUT files", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Put(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "update-test.json"). + Body(helper.LoadFile("testdata/timeline-demo.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to PUT files") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("editor can PUT files", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Put(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "update-test.json"). + Body(helper.LoadFile("testdata/timeline-demo.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to PUT files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + t.Run("admin can PUT files", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Put(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "update-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to PUT files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + }) + + // Clean up + helper.AdminREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "update-test.json"). + Do(ctx) + }) + + t.Run("DELETE operations", func(t *testing.T) { + // Create test files for deletion tests + helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-viewer-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx) + + helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-editor-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx) + + helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-admin-test.json"). + Body(helper.LoadFile("testdata/text-options.json")). + SetHeader("Content-Type", "application/json"). + Do(ctx) + + t.Run("viewer cannot DELETE files", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-viewer-test.json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to DELETE files") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + + // Verify file still exists + _, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "delete-viewer-test.json") + require.NoError(t, err, "file should still exist after failed delete") + }) + + t.Run("editor can DELETE files", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-editor-test.json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to DELETE files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + + // Verify file was deleted + _, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "delete-editor-test.json") + require.Error(t, err, "file should be deleted") + require.True(t, apierrors.IsNotFound(err), "should return NotFound for deleted file") + }) + + t.Run("admin can DELETE files", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Delete(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("files", "delete-admin-test.json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "admin should be able to DELETE files") + require.Equal(t, http.StatusOK, statusCode, "should return 200 OK") + + // Verify file was deleted + _, err := helper.Repositories.Resource.Get(ctx, repo, metav1.GetOptions{}, "files", "delete-admin-test.json") + require.Error(t, err, "file should be deleted") + require.True(t, apierrors.IsNotFound(err), "should return NotFound for deleted file") + }) + }) + + t.Run("folder operations", func(t *testing.T) { + t.Run("viewer cannot create folders", func(t *testing.T) { + // Create a folder by POSTing to a directory path + addr := helper.GetEnv().Server.HTTPServer.Listener.Addr().String() + url := fmt.Sprintf("http://viewer:viewer@%s/apis/provisioning.grafana.app/v0alpha1/namespaces/default/repositories/%s/files/test-folder/", addr, repo) + req, err := http.NewRequest(http.MethodPost, url, nil) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + // nolint:errcheck + defer resp.Body.Close() + + require.Equal(t, http.StatusForbidden, resp.StatusCode, "viewer should not be able to create folders") + }) + + t.Run("editor can create folders", func(t *testing.T) { + addr := helper.GetEnv().Server.HTTPServer.Listener.Addr().String() + url := fmt.Sprintf("http://editor:editor@%s/apis/provisioning.grafana.app/v0alpha1/namespaces/default/repositories/%s/files/editor-folder/", addr, repo) + req, err := http.NewRequest(http.MethodPost, url, nil) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + // nolint:errcheck + defer resp.Body.Close() + + require.Equal(t, http.StatusOK, resp.StatusCode, "editor should be able to create folders") + + // Clean up - delete folder + deleteURL := fmt.Sprintf("http://admin:admin@%s/apis/provisioning.grafana.app/v0alpha1/namespaces/default/repositories/%s/files/editor-folder/", addr, repo) + deleteReq, err := http.NewRequest(http.MethodDelete, deleteURL, nil) + require.NoError(t, err) + deleteResp, err := http.DefaultClient.Do(deleteReq) + require.NoError(t, err) + // nolint:errcheck + defer deleteResp.Body.Close() + }) + + t.Run("admin can create folders", func(t *testing.T) { + addr := helper.GetEnv().Server.HTTPServer.Listener.Addr().String() + url := fmt.Sprintf("http://admin:admin@%s/apis/provisioning.grafana.app/v0alpha1/namespaces/default/repositories/%s/files/admin-folder/", addr, repo) + req, err := http.NewRequest(http.MethodPost, url, nil) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + // nolint:errcheck + defer resp.Body.Close() + + require.Equal(t, http.StatusOK, resp.StatusCode, "admin should be able to create folders") + + // Clean up - delete folder + deleteURL := fmt.Sprintf("http://admin:admin@%s/apis/provisioning.grafana.app/v0alpha1/namespaces/default/repositories/%s/files/admin-folder/", addr, repo) + deleteReq, err := http.NewRequest(http.MethodDelete, deleteURL, nil) + require.NoError(t, err) + deleteResp, err := http.DefaultClient.Do(deleteReq) + require.NoError(t, err) + // nolint:errcheck + defer deleteResp.Body.Close() + }) + }) +} diff --git a/pkg/tests/apis/provisioning/helper_test.go b/pkg/tests/apis/provisioning/helper_test.go index f4687bdb01b..5f2ec6a3985 100644 --- a/pkg/tests/apis/provisioning/helper_test.go +++ b/pkg/tests/apis/provisioning/helper_test.go @@ -53,6 +53,7 @@ type provisioningTestHelper struct { ProvisioningPath string Repositories *apis.K8sResourceClient + Connections *apis.K8sResourceClient Jobs *apis.K8sResourceClient Folders *apis.K8sResourceClient DashboardsV0 *apis.K8sResourceClient @@ -703,6 +704,11 @@ func runGrafana(t *testing.T, options ...grafanaOption) *provisioningTestHelper Namespace: "default", // actually org1 GVR: provisioning.RepositoryResourceInfo.GroupVersionResource(), }) + connections := helper.GetResourceClient(apis.ResourceClientArgs{ + User: helper.Org1.Admin, + Namespace: "default", // actually org1 + GVR: provisioning.ConnectionResourceInfo.GroupVersionResource(), + }) jobs := helper.GetResourceClient(apis.ResourceClientArgs{ User: helper.Org1.Admin, Namespace: "default", // actually org1 @@ -763,6 +769,7 @@ func runGrafana(t *testing.T, options ...grafanaOption) *provisioningTestHelper K8sTestHelper: helper, Repositories: repositories, + Connections: connections, AdminREST: adminClient, EditorREST: editorClient, ViewerREST: viewerClient, @@ -957,3 +964,49 @@ func (h *provisioningTestHelper) CleanupAllRepos(t *testing.T) { assert.Equal(collect, 0, len(list.Items), "repositories should be cleaned up") }, waitTimeoutDefault, waitIntervalDefault, "repositories should be cleaned up between subtests") } + +func postHelper(t *testing.T, helper apis.K8sTestHelper, path string, body interface{}, user apis.User) (map[string]interface{}, int, error) { + return requestHelper(t, helper, http.MethodPost, path, body, user) +} + +func patchHelper(t *testing.T, helper apis.K8sTestHelper, path string, body interface{}, user apis.User) (map[string]interface{}, int, error) { + return requestHelper(t, helper, http.MethodPatch, path, body, user) +} + +func requestHelper( + t *testing.T, + helper apis.K8sTestHelper, + method string, + path string, + body interface{}, + user apis.User, +) (map[string]interface{}, int, error) { + bodyJSON, err := json.Marshal(body) + require.NoError(t, err) + + resp := apis.DoRequest(&helper, apis.RequestParams{ + User: user, + Method: method, + Path: path, + Body: bodyJSON, + ContentType: "application/json", + }, &struct{}{}) + + if resp.Response.StatusCode != http.StatusOK { + res := map[string]interface{}{} + err := json.Unmarshal(resp.Body, &res) + if err != nil { + return nil, 0, fmt.Errorf("failed to unmarshal response JSON: %v", err) + } + + return res, resp.Response.StatusCode, fmt.Errorf("failure when making request: %s", resp.Response.Status) + } + + var result map[string]interface{} + err = json.Unmarshal(resp.Body, &result) + if err != nil { + return nil, 0, fmt.Errorf("failed to unmarshal response JSON: %v", err) + } + + return result, resp.Response.StatusCode, nil +} diff --git a/pkg/tests/apis/provisioning/librarypanels_test.go b/pkg/tests/apis/provisioning/librarypanels_test.go new file mode 100644 index 00000000000..47f87e7fb86 --- /dev/null +++ b/pkg/tests/apis/provisioning/librarypanels_test.go @@ -0,0 +1,175 @@ +package provisioning + +import ( + "fmt" + "net/http" + "testing" + "time" + + foldersV1 "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" + "github.com/grafana/grafana/pkg/apimachinery/utils" + "github.com/grafana/grafana/pkg/services/accesscontrol/resourcepermissions" + "github.com/grafana/grafana/pkg/util/testutil" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" +) + +// We currently block the creation of library panels in provisioned folders. +func TestIntegrationLibraryPanels_ProvisionedFolders(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + helper.CreateRepo(t, TestRepo{ + Name: "test-repo", + Target: "folder", + ExpectedFolders: 1, + }) + + t.Run("should fail to create library element in provisioned folder", func(t *testing.T) { + folders, err := helper.Folders.Resource.List(t.Context(), metav1.ListOptions{}) + require.NoError(t, err) + require.Len(t, folders.Items, 1) + + managedFolderName := folders.Items[0].GetName() + libraryElement := map[string]interface{}{ + "kind": 1, + "name": "Library Panel", + "folderUid": managedFolderName, + "model": map[string]interface{}{ + "type": "text", + "title": "Library Panel", + }, + } + libraryElementURL := "/api/library-elements" + libraryElementData, code, err := postHelper(t, *helper.K8sTestHelper, libraryElementURL, libraryElement, helper.Org1.Admin) + require.Error(t, err) + require.Equal(t, http.StatusConflict, code) + require.NotNil(t, libraryElementData) + require.Equal(t, "resource type not supported in repository-managed folders", libraryElementData["message"]) + }) + + t.Run("should fail to patch library element, moving it in a provisioned folder", func(t *testing.T) { + // Getting managed folder + folders, err := helper.Folders.Resource.List(t.Context(), metav1.ListOptions{}) + require.NoError(t, err) + require.Len(t, folders.Items, 1) + managedFolderName := folders.Items[0].GetName() + + unmanagedFolder := &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": foldersV1.FolderResourceInfo.GroupVersion().String(), + "kind": foldersV1.FolderResourceInfo.GroupVersionKind().Kind, + "metadata": map[string]interface{}{ + "generateName": "test-folder-", + }, + "spec": map[string]interface{}{ + "title": "Library Panel", + }, + }, + } + createdFolder, err := helper.Folders.Resource.Create(t.Context(), unmanagedFolder, metav1.CreateOptions{}) + require.NoError(t, err) + require.NotNil(t, createdFolder) + + libraryElement := map[string]interface{}{ + "kind": 1, + "name": "Moved Library Panel", + "folderUid": createdFolder.GetName(), + "model": map[string]interface{}{ + "type": "text", + "title": "Moved Library Panel", + }, + } + libraryElementURL := "/api/library-elements" + libraryElementData, code, err := postHelper(t, *helper.K8sTestHelper, libraryElementURL, libraryElement, helper.Org1.Admin) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + require.NotNil(t, libraryElementData) + + res := libraryElementData["result"].(map[string]interface{}) + helper.SetPermissions(helper.Org1.Admin, []resourcepermissions.SetResourcePermissionCommand{ + { + Actions: []string{"library.panels:write"}, + Resource: "library.panels", + ResourceAttribute: "uid", + ResourceID: "*", + }, + }) + + // Patching libraryElement - changing folder to a managed one + updatedLibraryElement := map[string]interface{}{ + "kind": 1, + "version": res["version"], + "folderUid": managedFolderName, + } + patchLibraryElementURL := fmt.Sprintf("/api/library-elements/%f", +res["id"].(float64)) + newLibraryElement, code, err := patchHelper(t, *helper.K8sTestHelper, patchLibraryElementURL, updatedLibraryElement, helper.Org1.Admin) + require.Error(t, err) + require.Equal(t, http.StatusConflict, code) + require.NotNil(t, newLibraryElement) + require.Equal(t, "resource type not supported in repository-managed folders", newLibraryElement["message"]) + }) +} + +func TestIntegrationLibraryPanels_UnprovisionedFolders(t *testing.T) { + const repo = "test-repo" + helper := runGrafana(t) + helper.CreateRepo(t, TestRepo{ + Name: repo, + Target: "folder", + ExpectedFolders: 1, + }) + + t.Run("should create library element when folder is released", func(t *testing.T) { + folders, err := helper.Folders.Resource.List(t.Context(), metav1.ListOptions{}) + require.NoError(t, err) + require.Len(t, folders.Items, 1) + managedFolderName := folders.Items[0].GetName() + require.Contains(t, folders.Items[0].GetAnnotations(), utils.AnnoKeyManagerKind, "folder should be managed") + require.Contains(t, folders.Items[0].GetAnnotations(), utils.AnnoKeyManagerIdentity, "folder should be managed") + + _, err = helper.Repositories.Resource.Patch(t.Context(), repo, types.JSONPatchType, []byte(`[ + { + "op": "replace", + "path": "/metadata/finalizers", + "value": ["cleanup", "release-orphan-resources"] + } + ]`), metav1.PatchOptions{}) + require.NoError(t, err, "should successfully patch finalizers") + + require.NoError(t, helper.Repositories.Resource.Delete(t.Context(), repo, metav1.DeleteOptions{})) + require.EventuallyWithT(t, func(collect *assert.CollectT) { + _, err := helper.Repositories.Resource.Get(t.Context(), repo, metav1.GetOptions{}) + assert.True(collect, apierrors.IsNotFound(err), "repository should be deleted") + }, time.Second*10, time.Millisecond*50, "repository should be deleted") + require.EventuallyWithT(t, func(collect *assert.CollectT) { + foundFolders, err := helper.Folders.Resource.List(t.Context(), metav1.ListOptions{}) + require.NoError(t, err, "can list values") + for _, v := range foundFolders.Items { + assert.NotContains(t, v.GetAnnotations(), utils.AnnoKeyManagerKind) + assert.NotContains(t, v.GetAnnotations(), utils.AnnoKeyManagerIdentity) + assert.NotContains(t, v.GetAnnotations(), utils.AnnoKeySourcePath) + assert.NotContains(t, v.GetAnnotations(), utils.AnnoKeySourceChecksum) + } + }, time.Second*20, time.Millisecond*10, "Expected folders to be released") + + libraryElement := map[string]interface{}{ + "kind": 1, + "name": "Library Panel", + "folderUid": managedFolderName, + "model": map[string]interface{}{ + "type": "text", + "title": "Library Panel", + }, + } + libraryElementURL := "/api/library-elements" + libraryElementData, code, err := postHelper(t, *helper.K8sTestHelper, libraryElementURL, libraryElement, helper.Org1.Admin) + require.NoError(t, err) + require.Equal(t, http.StatusOK, code) + require.NotNil(t, libraryElementData) + }) +} diff --git a/pkg/tests/apis/provisioning/repository_test.go b/pkg/tests/apis/provisioning/repository_test.go index d7850c52d0a..877ed0d5f98 100644 --- a/pkg/tests/apis/provisioning/repository_test.go +++ b/pkg/tests/apis/provisioning/repository_test.go @@ -786,7 +786,7 @@ func TestIntegrationProvisioning_ImportAllPanelsFromLocalRepository(t *testing.T v, _, _ := unstructured.NestedString(obj.Object, "metadata", "annotations", utils.AnnoKeyUpdatedBy) require.Equal(t, "access-policy:provisioning", v) - // Should not be able to directly delete the managed resource + // Should be able to directly delete the managed resource err = helper.DashboardsV1.Resource.Delete(ctx, allPanels, metav1.DeleteOptions{}) require.NoError(t, err, "user can delete") @@ -867,3 +867,86 @@ func TestIntegrationProvisioning_DeleteRepositoryAndReleaseResources(t *testing. } }, time.Second*20, time.Millisecond*10, "Expected folders to be released") } + +func TestIntegrationProvisioning_JobPermissions(t *testing.T) { + testutil.SkipIntegrationTestInShortMode(t) + + helper := runGrafana(t) + ctx := context.Background() + + const repo = "job-permissions-test" + testRepo := TestRepo{ + Name: repo, + Target: "folder", + Copies: map[string]string{}, // No files needed for this test + ExpectedDashboards: 0, + ExpectedFolders: 1, // Repository creates a folder + } + helper.CreateRepo(t, testRepo) + + jobSpec := provisioning.JobSpec{ + Action: provisioning.JobActionPull, + Pull: &provisioning.SyncJobOptions{}, + } + body := asJSON(jobSpec) + + t.Run("editor can POST jobs", func(t *testing.T) { + var statusCode int + result := helper.EditorREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("jobs"). + Body(body). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.NoError(t, result.Error(), "editor should be able to POST jobs") + require.Equal(t, http.StatusAccepted, statusCode, "should return 202 Accepted") + + // Verify the job was created + obj, err := result.Get() + require.NoError(t, err, "should get job object") + unstruct, ok := obj.(*unstructured.Unstructured) + require.True(t, ok, "expecting unstructured object") + require.NotEmpty(t, unstruct.GetName(), "job should have a name") + }) + + t.Run("viewer cannot POST jobs", func(t *testing.T) { + var statusCode int + result := helper.ViewerREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("jobs"). + Body(body). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + require.Error(t, result.Error(), "viewer should not be able to POST jobs") + require.Equal(t, http.StatusForbidden, statusCode, "should return 403 Forbidden") + require.True(t, apierrors.IsForbidden(result.Error()), "error should be forbidden") + }) + + t.Run("admin can POST jobs", func(t *testing.T) { + var statusCode int + result := helper.AdminREST.Post(). + Namespace("default"). + Resource("repositories"). + Name(repo). + SubResource("jobs"). + Body(body). + SetHeader("Content-Type", "application/json"). + Do(ctx).StatusCode(&statusCode) + + // Job might already exist from previous test, which is acceptable + if apierrors.IsAlreadyExists(result.Error()) { + // Wait for the existing job to complete + helper.AwaitJobs(t, repo) + return + } + + require.NoError(t, result.Error(), "admin should be able to POST jobs") + require.Equal(t, http.StatusAccepted, statusCode, "should return 202 Accepted") + }) +} diff --git a/pkg/tsdb/elasticsearch/client/models.go b/pkg/tsdb/elasticsearch/client/models.go index c8648f0bdeb..de8dda2b61c 100644 --- a/pkg/tsdb/elasticsearch/client/models.go +++ b/pkg/tsdb/elasticsearch/client/models.go @@ -20,10 +20,18 @@ type SearchRequest struct { Aggs AggArray CustomProps map[string]interface{} TimeRange backend.TimeRange + // RawBody contains the raw Elasticsearch Query DSL JSON for raw DSL queries + // When set, this takes precedence over all other fields during marshaling + RawBody map[string]interface{} } // MarshalJSON returns the JSON encoding of the request. func (r *SearchRequest) MarshalJSON() ([]byte, error) { + // If RawBody is set, use it directly for raw DSL queries + if len(r.RawBody) > 0 { + return json.Marshal(r.RawBody) + } + root := make(map[string]interface{}) root["size"] = r.Size diff --git a/pkg/tsdb/elasticsearch/client/request_encoder.go b/pkg/tsdb/elasticsearch/client/request_encoder.go index ae22c8e2694..0c6e2314d99 100644 --- a/pkg/tsdb/elasticsearch/client/request_encoder.go +++ b/pkg/tsdb/elasticsearch/client/request_encoder.go @@ -3,6 +3,7 @@ package es import ( "bytes" "encoding/json" + "fmt" "strconv" "strings" "time" @@ -25,6 +26,9 @@ func newRequestEncoder(logger log.Logger) *requestEncoder { // encodeBatchRequests encodes multiple requests into NDJSON format func (e *requestEncoder) encodeBatchRequests(requests []*multiRequest) ([]byte, error) { start := time.Now() + defer func() { + e.logger.Debug("Completed encoding of batch requests to json", "duration", time.Since(start)) + }() payload := bytes.Buffer{} for _, r := range requests { @@ -34,20 +38,25 @@ func (e *requestEncoder) encodeBatchRequests(requests []*multiRequest) ([]byte, } payload.WriteString(string(reqHeader) + "\n") - reqBody, err := json.Marshal(r.body) - if err != nil { - return nil, err + body := "" + switch r.body.(type) { + case *SearchRequest: + reqBody, err := json.Marshal(r.body) + if err != nil { + return nil, err + } + body = string(reqBody) + case string: + body = r.body.(string) + default: + return nil, fmt.Errorf("unknown request type: %T", r.body) } - body := string(reqBody) body = strings.ReplaceAll(body, "$__interval_ms", strconv.FormatInt(r.interval.Milliseconds(), 10)) body = strings.ReplaceAll(body, "$__interval", r.interval.String()) payload.WriteString(body + "\n") } - elapsed := time.Since(start) - e.logger.Debug("Completed encoding of batch requests to json", "duration", elapsed) - return payload.Bytes(), nil } diff --git a/pkg/tsdb/elasticsearch/client/search_request.go b/pkg/tsdb/elasticsearch/client/search_request.go index f898517ab07..8f47d240a28 100644 --- a/pkg/tsdb/elasticsearch/client/search_request.go +++ b/pkg/tsdb/elasticsearch/client/search_request.go @@ -30,6 +30,8 @@ type SearchRequestBuilder struct { aggBuilders []AggBuilder customProps map[string]any timeRange backend.TimeRange + // rawBody contains the raw Elasticsearch Query DSL JSON for raw DSL queries + rawBody map[string]any } // NewSearchRequestBuilder create a new search request builder @@ -53,6 +55,12 @@ func (b *SearchRequestBuilder) Build() (*SearchRequest, error) { Size: b.size, Sort: b.sort, CustomProps: b.customProps, + RawBody: b.rawBody, + } + + // If RawBody is set, skip building query and aggs as they're in the raw body + if len(b.rawBody) > 0 { + return &sr, nil } if b.queryBuilder != nil { @@ -141,6 +149,19 @@ func (b *SearchRequestBuilder) AddSearchAfter(value any) *SearchRequestBuilder { return b } +// AddCustomProp adds a custom property to the search request +func (b *SearchRequestBuilder) AddCustomProp(key string, value any) *SearchRequestBuilder { + b.customProps[key] = value + return b +} + +// SetRawBody sets the raw Elasticsearch Query DSL body directly +// This bypasses all builder logic and sends the query as-is to Elasticsearch +func (b *SearchRequestBuilder) SetRawBody(rawBody map[string]any) *SearchRequestBuilder { + b.rawBody = rawBody + return b +} + // Query creates and return a query builder func (b *SearchRequestBuilder) Query() *QueryBuilder { if b.queryBuilder == nil { diff --git a/pkg/tsdb/elasticsearch/data_query.go b/pkg/tsdb/elasticsearch/data_query.go index e883b3d769c..949b93fd148 100644 --- a/pkg/tsdb/elasticsearch/data_query.go +++ b/pkg/tsdb/elasticsearch/data_query.go @@ -20,11 +20,12 @@ const ( ) type elasticsearchDataQuery struct { - client es.Client - dataQueries []backend.DataQuery - logger log.Logger - ctx context.Context - keepLabelsInResponse bool + client es.Client + dataQueries []backend.DataQuery + logger log.Logger + ctx context.Context + keepLabelsInResponse bool + aggregationParserDSLRawQuery AggregationParser } var newElasticsearchDataQuery = func(ctx context.Context, client es.Client, req *backend.QueryDataRequest, logger log.Logger) *elasticsearchDataQuery { @@ -39,6 +40,8 @@ var newElasticsearchDataQuery = func(ctx context.Context, client es.Client, req // To maintain backward compatibility, it is necessary to keep labels in responses for alerting and expressions queries. // Historically, these labels have been used in alerting rules and transformations. keepLabelsInResponse: fromAlert || fromExpression, + + aggregationParserDSLRawQuery: NewAggregationParser(), } } diff --git a/pkg/tsdb/elasticsearch/data_query_processor.go b/pkg/tsdb/elasticsearch/data_query_processor.go index 5f6ea448ddd..1c4ec7b3cdd 100644 --- a/pkg/tsdb/elasticsearch/data_query_processor.go +++ b/pkg/tsdb/elasticsearch/data_query_processor.go @@ -1,6 +1,7 @@ package elasticsearch import ( + "encoding/json" "fmt" "strconv" @@ -23,6 +24,17 @@ func (e *elasticsearchDataQuery) processQuery(q *Query, ms *es.MultiSearchReques filters.AddDateRangeFilter(defaultTimeField, to, from, es.DateFormatEpochMS) filters.AddQueryStringFilter(q.RawQuery, true) + if q.EditorType != nil && *q.EditorType == "code" && q.RawDSLQuery != "" { + cfg := backend.GrafanaConfigFromContext(e.ctx) + if !cfg.FeatureToggles().IsEnabled("elasticsearchRawDSLQuery") { + return backend.DownstreamError(fmt.Errorf("raw DSL query feature is disabled. Enable the elasticsearchRawDSLQuery feature toggle to use this query type")) + } + + if err := e.processRawDSLQuery(q, b); err != nil { + return err + } + } + if isLogsQuery(q) { processLogsQuery(q, b, from, to, defaultTimeField) } else if isDocumentQuery(q) { @@ -184,6 +196,46 @@ func processTimeSeriesQuery(q *Query, b *es.SearchRequestBuilder, from, to int64 } } +func (e *elasticsearchDataQuery) processRawDSLQuery(q *Query, b *es.SearchRequestBuilder) error { + if q.RawDSLQuery == "" { + return backend.DownstreamError(fmt.Errorf("raw DSL query is empty")) + } + + // Parse the raw DSL query JSON + var queryBody map[string]any + if err := json.Unmarshal([]byte(q.RawDSLQuery), &queryBody); err != nil { + return backend.DownstreamError(fmt.Errorf("invalid raw DSL query JSON: %w", err)) + } + + if len(q.Metrics) > 0 { + firstMetricType := q.Metrics[0].Type + if firstMetricType != logsType && firstMetricType != rawDataType && firstMetricType != rawDocumentType { + bucketAggs, metricAggs, err := e.aggregationParserDSLRawQuery.Parse(q.RawDSLQuery) + if err != nil { + return backend.DownstreamError(fmt.Errorf("failed to parse aggregations: %w", err)) + } + + // If there is no metric agg in the query, it is a count agg + if len(metricAggs) == 0 { + metricAggs = append(metricAggs, &MetricAgg{Type: "count"}) + } + + q.BucketAggs = bucketAggs + q.Metrics = metricAggs + + if queryPart, ok := queryBody["query"].(map[string]any); ok { + queryJSON, _ := json.Marshal(queryPart) + q.RawQuery = string(queryJSON) + } + return nil + } + } + + // For non-time-series queries (logs, raw data), pass through the raw body directly + b.SetRawBody(queryBody) + return nil +} + // getPipelineAggField returns the pipeline aggregation field func getPipelineAggField(m *MetricAgg) string { // In frontend we are using Field as pipelineAggField diff --git a/pkg/tsdb/elasticsearch/data_query_test.go b/pkg/tsdb/elasticsearch/data_query_test.go index 887b8ba661d..e2531766eaf 100644 --- a/pkg/tsdb/elasticsearch/data_query_test.go +++ b/pkg/tsdb/elasticsearch/data_query_test.go @@ -8,6 +8,7 @@ import ( "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend/log" + "github.com/grafana/grafana-plugin-sdk-go/experimental/featuretoggles" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1887,6 +1888,11 @@ func newDataQuery(body string) (backend.QueryDataRequest, error) { } func executeElasticsearchDataQuery(c es.Client, body string, from, to time.Time) ( + *backend.QueryDataResponse, error) { + return executeElasticsearchDataQueryWithContext(c, body, from, to, context.Background()) +} + +func executeElasticsearchDataQueryWithContext(c es.Client, body string, from, to time.Time, ctx context.Context) ( *backend.QueryDataResponse, error) { timeRange := backend.TimeRange{ From: from, @@ -1901,6 +1907,98 @@ func executeElasticsearchDataQuery(c es.Client, body string, from, to time.Time) }, }, } - query := newElasticsearchDataQuery(context.Background(), c, &dataRequest, log.New()) + query := newElasticsearchDataQuery(ctx, c, &dataRequest, log.New()) return query.execute() } + +func TestRawDSLQuery(t *testing.T) { + from := time.Date(2018, 5, 15, 17, 50, 0, 0, time.UTC) + to := time.Date(2018, 5, 15, 17, 55, 0, 0, time.UTC) + + // Create context with raw DSL query feature toggle enabled + cfg := backend.NewGrafanaCfg(map[string]string{ + featuretoggles.EnabledFeatures: "elasticsearchRawDSLQuery", + }) + ctx := backend.WithGrafanaConfig(context.Background(), cfg) + + t.Run("With raw DSL query", func(t *testing.T) { + t.Run("Basic raw DSL query with aggregations", func(t *testing.T) { + c := newFakeClient() + _, err := executeElasticsearchDataQueryWithContext(c, `{ + "editorType": "code", + "rawDSLQuery": "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"@timestamp\":{\"gte\":1526405400000,\"lte\":1526405700000,\"format\":\"epoch_millis\"}}}]}},\"aggs\":{\"date_histogram\":{\"date_histogram\":{\"field\":\"@timestamp\",\"interval\":\"1m\"}}},\"size\":0}" + }`, from, to, ctx) + require.NoError(t, err) + require.Len(t, c.multisearchRequests, 1) + require.Len(t, c.multisearchRequests[0].Requests, 1) + sr := c.multisearchRequests[0].Requests[0] + + // Verify RawBody contains the entire DSL query + require.NotNil(t, sr.RawBody) + require.Contains(t, sr.RawBody, "query") + require.Contains(t, sr.RawBody, "aggs") + + // Verify size from raw body + size, ok := sr.RawBody["size"].(float64) + require.True(t, ok) + require.Equal(t, float64(0), size) + }) + + t.Run("Raw DSL query with query_string", func(t *testing.T) { + c := newFakeClient() + _, err := executeElasticsearchDataQueryWithContext(c, `{ + "editorType": "code", + "rawDSLQuery": "{\"query\":{\"query_string\":{\"query\":\"status:200\",\"analyze_wildcard\":true}},\"size\":100}" + }`, from, to, ctx) + require.NoError(t, err) + require.Len(t, c.multisearchRequests, 1) + sr := c.multisearchRequests[0].Requests[0] + + // Verify RawBody contains the entire DSL query + require.NotNil(t, sr.RawBody) + require.Contains(t, sr.RawBody, "query") + + // Verify size from raw body + size, ok := sr.RawBody["size"].(float64) + require.True(t, ok) + require.Equal(t, float64(100), size) + + // Verify query object exists in raw body + query, ok := sr.RawBody["query"].(map[string]any) + require.True(t, ok) + require.Contains(t, query, "query_string") + }) + + t.Run("Raw DSL query with sort", func(t *testing.T) { + c := newFakeClient() + _, err := executeElasticsearchDataQueryWithContext(c, `{ + "editorType": "code", + "rawDSLQuery": "{\"query\":{\"match_all\":{}},\"sort\":[{\"@timestamp\":{\"order\":\"desc\"}}],\"size\":50}" + }`, from, to, ctx) + require.NoError(t, err) + require.Len(t, c.multisearchRequests, 1) + sr := c.multisearchRequests[0].Requests[0] + + // Verify RawBody contains the entire DSL query + require.NotNil(t, sr.RawBody) + require.Contains(t, sr.RawBody, "query") + require.Contains(t, sr.RawBody, "sort") + + // Verify sort in raw body + sort, ok := sr.RawBody["sort"].([]any) + require.True(t, ok) + require.NotEmpty(t, sort) + }) + + t.Run("Invalid JSON in raw DSL query returns error", func(t *testing.T) { + c := newFakeClient() + response, err := executeElasticsearchDataQueryWithContext(c, `{ + "editorType": "code", + "rawDSLQuery": "{ invalid json }" + }`, from, to, ctx) + require.NoError(t, err) + require.NotNil(t, response.Responses["A"].Error) + require.Contains(t, response.Responses["A"].Error.Error(), "invalid raw DSL query JSON") + }) + }) +} diff --git a/pkg/tsdb/elasticsearch/data_query_validator.go b/pkg/tsdb/elasticsearch/data_query_validator.go index def537c02da..648dbb53109 100644 --- a/pkg/tsdb/elasticsearch/data_query_validator.go +++ b/pkg/tsdb/elasticsearch/data_query_validator.go @@ -6,6 +6,10 @@ import ( // isQueryWithError validates the query and returns an error if invalid func isQueryWithError(query *Query) error { + // Skip validation for raw DSL queries because no easy way to see it is valid without just running it + if query.EditorType != nil && *query.EditorType == "code" && query.RawDSLQuery != "" { + return nil + } if len(query.BucketAggs) == 0 { // If no aggregations, only document and logs queries are valid if len(query.Metrics) == 0 || (!isLogsQuery(query) && !isDocumentQuery(query)) { diff --git a/pkg/tsdb/elasticsearch/kinds/dataquery/types_dataquery_gen.go b/pkg/tsdb/elasticsearch/kinds/dataquery/types_dataquery_gen.go index 175a486589c..31583f96f79 100644 --- a/pkg/tsdb/elasticsearch/kinds/dataquery/types_dataquery_gen.go +++ b/pkg/tsdb/elasticsearch/kinds/dataquery/types_dataquery_gen.go @@ -775,8 +775,12 @@ type ElasticsearchDataQuery struct { Alias *string `json:"alias,omitempty"` // Lucene query Query *string `json:"query,omitempty"` + // Raw DSL query + RawDSLQuery *string `json:"rawDSLQuery,omitempty"` // Name of time field TimeField *string `json:"timeField,omitempty"` + // Editor type + EditorType *string `json:"editorType,omitempty"` // List of bucket aggregations BucketAggs []BucketAggregation `json:"bucketAggs,omitempty"` // List of metric aggregations diff --git a/pkg/tsdb/elasticsearch/models.go b/pkg/tsdb/elasticsearch/models.go index d03861d3943..adb18554339 100644 --- a/pkg/tsdb/elasticsearch/models.go +++ b/pkg/tsdb/elasticsearch/models.go @@ -10,6 +10,7 @@ import ( // Query represents the time series query model of the datasource type Query struct { RawQuery string `json:"query"` + RawDSLQuery string `json:"rawDSLQuery"` BucketAggs []*BucketAgg `json:"bucketAggs"` Metrics []*MetricAgg `json:"metrics"` Alias string `json:"alias"` @@ -18,6 +19,7 @@ type Query struct { RefID string MaxDataPoints int64 TimeRange backend.TimeRange + EditorType *string `json:"editorType"` } // BucketAgg represents a bucket aggregation of the time series query model of the datasource diff --git a/pkg/tsdb/elasticsearch/parse_query.go b/pkg/tsdb/elasticsearch/parse_query.go index 27b9bc9b2e8..e1bfa189ab9 100644 --- a/pkg/tsdb/elasticsearch/parse_query.go +++ b/pkg/tsdb/elasticsearch/parse_query.go @@ -21,6 +21,13 @@ func parseQuery(tsdbQuery []backend.DataQuery, logger log.Logger) ([]*Query, err // please do not create a new field with that name, to avoid potential problems with old, persisted queries. rawQuery := model.Get("query").MustString() + rawDSLQuery := model.Get("rawDSLQuery").MustString() + + var editorType *string + if et := model.Get("editorType").MustString(); et != "" { + editorType = &et + } + bucketAggs, err := parseBucketAggs(model) if err != nil { logger.Error("Failed to parse bucket aggs in query", "error", err, "model", string(q.JSON)) @@ -37,6 +44,7 @@ func parseQuery(tsdbQuery []backend.DataQuery, logger log.Logger) ([]*Query, err queries = append(queries, &Query{ RawQuery: rawQuery, + RawDSLQuery: rawDSLQuery, BucketAggs: bucketAggs, Metrics: metrics, Alias: alias, @@ -45,6 +53,7 @@ func parseQuery(tsdbQuery []backend.DataQuery, logger log.Logger) ([]*Query, err RefID: q.RefID, MaxDataPoints: q.MaxDataPoints, TimeRange: q.TimeRange, + EditorType: editorType, }) } diff --git a/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser.go b/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser.go new file mode 100644 index 00000000000..b092763b57d --- /dev/null +++ b/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser.go @@ -0,0 +1,628 @@ +package elasticsearch + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/grafana/grafana/pkg/components/simplejson" +) + +// AggregationParser parses raw Elasticsearch DSL aggregations +type AggregationParser interface { + Parse(rawQuery string) ([]*BucketAgg, []*MetricAgg, error) +} + +// aggregationTypeParser handles parsing of specific aggregation types +type aggregationTypeParser interface { + CanParse(aggType string) bool + Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) +} + +type AggType string + +const ( + aggTypeBucket = AggType("bucket") + aggTypeMetric = AggType("metric") +) + +type dslAgg struct { + Field string `json:"field"` + Hide bool `json:"hide"` + ID string `json:"id"` + PipelineAggregate string `json:"pipelineAgg"` + PipelineVariables map[string]string `json:"pipelineVariables"` + Settings *simplejson.Json `json:"settings"` + Meta *simplejson.Json `json:"meta"` + Type string `json:"type"` + AggType AggType +} + +func (a *dslAgg) toBucketAgg() *BucketAgg { + return &BucketAgg{ + Field: a.Field, + ID: a.ID, + Settings: a.Settings, + Type: a.Type, + } +} + +func (a *dslAgg) toMetricAgg() *MetricAgg { + return &MetricAgg{ + Field: a.Field, + Hide: a.Hide, + ID: a.ID, + PipelineAggregate: a.PipelineAggregate, + PipelineVariables: a.PipelineVariables, + Settings: a.Settings, + Meta: a.Meta, + Type: a.Type, + } +} + +// fieldExtractor handles extracting and converting field values +type fieldExtractor struct{} + +func (e *fieldExtractor) getString(data map[string]any, key string) string { + if val, ok := data[key]; ok { + if str, ok := val.(string); ok { + return str + } + } + return "" +} + +func (e *fieldExtractor) getInt(data map[string]any, key string) int { + if val, ok := data[key]; ok { + switch v := val.(type) { + case float64: + return int(v) + case int: + return v + case string: + if i, err := strconv.Atoi(v); err == nil { + return i + } + } + } + return 0 +} + +func (e *fieldExtractor) getFloat(data map[string]any, key string) float64 { + if val, ok := data[key]; ok { + switch v := val.(type) { + case float64: + return v + case int: + return float64(v) + case string: + if f, err := strconv.ParseFloat(v, 64); err == nil { + return f + } + } + } + return 0 +} + +func (e *fieldExtractor) getMap(data map[string]any, key string) map[string]any { + if val, ok := data[key]; ok { + if m, ok := val.(map[string]any); ok { + return m + } + } + return nil +} + +func (e *fieldExtractor) getSettings(data map[string]any) *simplejson.Json { + settings := make(map[string]any) + for k, v := range data { + // Skip known non-setting fields + if k == "field" || k == "buckets_path" { + continue + } + settings[k] = v + } + return simplejson.NewFromAny(settings) +} + +// dateHistogramParser handles date_histogram aggregations +type dateHistogramParser struct { + extractor *fieldExtractor +} + +func (p *dateHistogramParser) CanParse(aggType string) bool { + return aggType == dateHistType +} + +func (p *dateHistogramParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + + settings := make(map[string]any) + if interval := p.extractor.getString(aggValue, "fixed_interval"); interval != "" { + settings["interval"] = interval + } else if interval := p.extractor.getString(aggValue, "calendar_interval"); interval != "" { + settings["interval"] = interval + } else if interval := p.extractor.getString(aggValue, "interval"); interval != "" { + settings["interval"] = interval + } + + if minDocCount := p.extractor.getInt(aggValue, "min_doc_count"); minDocCount > 0 { + settings["min_doc_count"] = strconv.Itoa(minDocCount) + } + + if timeZone := p.extractor.getString(aggValue, "time_zone"); timeZone != "" { + settings["time_zone"] = timeZone + } + + return &dslAgg{ + ID: id, + Type: dateHistType, + Field: field, + Settings: simplejson.NewFromAny(settings), + AggType: aggTypeBucket, + }, nil +} + +// termsParser handles terms aggregations +type termsParser struct { + extractor *fieldExtractor +} + +func (p *termsParser) CanParse(aggType string) bool { + return aggType == termsType +} + +func (p *termsParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + + settings := make(map[string]any) + if size := p.extractor.getInt(aggValue, "size"); size > 0 { + settings["size"] = strconv.Itoa(size) + } + + if order := p.extractor.getMap(aggValue, "order"); order != nil { + for k := range order { + settings["orderBy"] = k + orderJSON := p.extractor.getString(order, k) + settings["order"] = orderJSON + } + } + + if minDocCount := p.extractor.getInt(aggValue, "min_doc_count"); minDocCount != 0 { + minDocCountJSON, _ := json.Marshal(minDocCount) + settings["min_doc_count"] = string(minDocCountJSON) + } + + if missing := p.extractor.getString(aggValue, "missing"); missing != "" { + settings["missing"] = missing + } + + return &dslAgg{ + ID: id, + Type: termsType, + Field: field, + Settings: simplejson.NewFromAny(settings), + AggType: aggTypeBucket, + }, nil +} + +// histogramParser handles histogram aggregations +type histogramParser struct { + extractor *fieldExtractor +} + +func (p *histogramParser) CanParse(aggType string) bool { + return aggType == histogramType +} + +func (p *histogramParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + + settings := make(map[string]any) + if interval := p.extractor.getFloat(aggValue, "interval"); interval > 0 { + settings["interval"] = strconv.FormatFloat(interval, 'f', -1, 64) + } + + if minDocCount := p.extractor.getInt(aggValue, "min_doc_count"); minDocCount > 0 { + settings["min_doc_count"] = strconv.Itoa(minDocCount) + } + + return &dslAgg{ + ID: id, + Type: histogramType, + Field: field, + Settings: simplejson.NewFromAny(settings), + AggType: aggTypeBucket, + }, nil +} + +// simpleMetricParser handles simple metric aggregations (avg, sum, min, max, cardinality) +type simpleMetricParser struct { + extractor *fieldExtractor + types map[string]bool +} + +func newSimpleMetricParser() *simpleMetricParser { + return &simpleMetricParser{ + extractor: &fieldExtractor{}, + types: map[string]bool{ + "avg": true, + "sum": true, + "min": true, + "max": true, + "cardinality": true, + }, + } +} + +func (p *simpleMetricParser) CanParse(aggType string) bool { + return p.types[aggType] +} + +func (p *simpleMetricParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + settings := p.extractor.getSettings(aggValue) + + return &dslAgg{ + ID: id, + Type: aggType, + Field: field, + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// filtersParser handles filters aggregations +type filtersParser struct { + extractor *fieldExtractor +} + +func (p *filtersParser) CanParse(aggType string) bool { + return aggType == filtersType +} + +func (p *filtersParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + settings := make(map[string]any) + + if filters := p.extractor.getMap(aggValue, "filters"); filters != nil { + filtersArray := make([]any, 0, len(filters)) + for k, v := range filters { + if queryString := p.extractor.getMap(v.(map[string]any), "query_string"); queryString != nil { + queryString["label"] = k + filtersArray = append(filtersArray, queryString) + } + } + settings["filters"] = filtersArray + } + + return &dslAgg{ + ID: id, + Type: filtersType, + Field: "", + Settings: simplejson.NewFromAny(settings), + AggType: aggTypeBucket, + }, nil +} + +// geohashGridParser handles geohash_grid aggregations +type geohashGridParser struct { + extractor *fieldExtractor +} + +func (p *geohashGridParser) CanParse(aggType string) bool { + return aggType == geohashGridType +} + +func (p *geohashGridParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + + settings := make(map[string]any) + if precision := p.extractor.getInt(aggValue, "precision"); precision > 0 { + settings["precision"] = strconv.Itoa(precision) + } + + return &dslAgg{ + ID: id, + Type: geohashGridType, + Field: field, + Settings: simplejson.NewFromAny(settings), + AggType: aggTypeBucket, + }, nil +} + +// nestedParser handles nested aggregations +type nestedParser struct { + extractor *fieldExtractor +} + +func (p *nestedParser) CanParse(aggType string) bool { + return aggType == nestedType +} + +func (p *nestedParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + path := p.extractor.getString(aggValue, "path") + + return &dslAgg{ + ID: id, + Type: nestedType, + Field: path, + Settings: simplejson.NewFromAny(map[string]any{}), + AggType: aggTypeBucket, + }, nil +} + +// extendedStatsParser handles extended_stats aggregations +type extendedStatsParser struct { + extractor *fieldExtractor +} + +func (p *extendedStatsParser) CanParse(aggType string) bool { + return aggType == extendedStatsType +} + +func (p *extendedStatsParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + settings := p.extractor.getSettings(aggValue) + + return &dslAgg{ + ID: id, + Type: extendedStatsType, + Field: field, + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// percentilesParser handles percentiles aggregations +type percentilesParser struct { + extractor *fieldExtractor +} + +func (p *percentilesParser) CanParse(aggType string) bool { + return aggType == percentilesType +} + +func (p *percentilesParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + field := p.extractor.getString(aggValue, "field") + settings := p.extractor.getSettings(aggValue) + + return &dslAgg{ + ID: id, + Type: percentilesType, + Field: field, + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// topMetricsParser handles top_metrics aggregations +type topMetricsParser struct { + extractor *fieldExtractor +} + +func (p *topMetricsParser) CanParse(aggType string) bool { + return aggType == topMetricsType +} + +func (p *topMetricsParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + settings := p.extractor.getSettings(aggValue) + + // Extract metrics field if present + field := "" + if metrics := p.extractor.getMap(aggValue, "metrics"); metrics != nil { + if metricsField := p.extractor.getString(metrics, "field"); metricsField != "" { + field = metricsField + } + } + + return &dslAgg{ + ID: id, + Type: topMetricsType, + Field: field, + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// pipelineParser handles pipeline aggregations +type pipelineParser struct { + extractor *fieldExtractor + types map[string]bool +} + +func newPipelineParser() *pipelineParser { + return &pipelineParser{ + extractor: &fieldExtractor{}, + types: map[string]bool{ + "moving_avg": true, + "moving_fn": true, + "derivative": true, + "cumulative_sum": true, + "serial_diff": true, + }, + } +} + +func (p *pipelineParser) CanParse(aggType string) bool { + return p.types[aggType] +} + +func (p *pipelineParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + bucketsPath := p.extractor.getString(aggValue, "buckets_path") + settings := p.extractor.getSettings(aggValue) + + return &dslAgg{ + ID: id, + Type: aggType, + Field: bucketsPath, // For pipeline aggs, buckets_path goes in Field + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// bucketScriptParser handles bucket_script aggregations +type bucketScriptParser struct { + extractor *fieldExtractor +} + +func (p *bucketScriptParser) CanParse(aggType string) bool { + return aggType == "bucket_script" +} + +func (p *bucketScriptParser) Parse(id, aggType string, aggValue map[string]any) (*dslAgg, error) { + settings := p.extractor.getSettings(aggValue) + + // Extract buckets_path (can be a string or map) + pipelineVariables := make(map[string]string) + if bucketsPath, ok := aggValue["buckets_path"]; ok { + switch bp := bucketsPath.(type) { + case string: + // Single string bucket path + pipelineVariables["var1"] = bp + case map[string]any: + // Map of variable names to bucket paths + for varName, path := range bp { + if pathStr, ok := path.(string); ok { + pipelineVariables[varName] = pathStr + } + } + } + } + + return &dslAgg{ + ID: id, + Type: "bucket_script", + Field: "", + PipelineVariables: pipelineVariables, + Settings: settings, + AggType: aggTypeMetric, + }, nil +} + +// compositeParser combines multiple parsers +type compositeParser struct { + parsers []aggregationTypeParser + extractor *fieldExtractor +} + +func newCompositeParser() *compositeParser { + extractor := &fieldExtractor{} + return &compositeParser{ + extractor: extractor, + parsers: []aggregationTypeParser{ + // Bucket aggregations + &dateHistogramParser{extractor: extractor}, + &termsParser{extractor: extractor}, + &histogramParser{extractor: extractor}, + &filtersParser{extractor: extractor}, + &geohashGridParser{extractor: extractor}, + &nestedParser{extractor: extractor}, + // Metric aggregations + newSimpleMetricParser(), + &extendedStatsParser{extractor: extractor}, + &percentilesParser{extractor: extractor}, + &topMetricsParser{extractor: extractor}, + + // Pipeline aggregations + newPipelineParser(), + &bucketScriptParser{extractor: extractor}, + }, + } +} + +func (p *compositeParser) findParser(aggType string) aggregationTypeParser { + for _, parser := range p.parsers { + if parser.CanParse(aggType) { + return parser + } + } + return nil +} + +func (p *compositeParser) Parse(rawQuery string) ([]*BucketAgg, []*MetricAgg, error) { + if rawQuery == "" { + return nil, nil, nil + } + + var queryBody map[string]any + if err := json.Unmarshal([]byte(rawQuery), &queryBody); err != nil { + return nil, nil, fmt.Errorf("failed to parse raw query JSON: %w", err) + } + + // Look for aggregations in both "aggs" and "aggregations" + var aggsData map[string]any + if aggs, ok := queryBody["aggs"].(map[string]any); ok { + aggsData = aggs + } else if aggs, ok := queryBody["aggregations"].(map[string]any); ok { + aggsData = aggs + } + + if aggsData == nil { + return nil, nil, nil + } + + b, m := p.parseAggregations(aggsData) + return b, m, nil +} + +func (p *compositeParser) parseAggregations(aggsData map[string]any) ([]*BucketAgg, []*MetricAgg) { + var bucketAggs []*BucketAgg + var metricAggs []*MetricAgg + + for aggID, aggData := range aggsData { + aggMap, ok := aggData.(map[string]any) + if !ok { + continue + } + + // Find the aggregation type (first key that's not "aggs" or "aggregations") + var aggType string + var aggValue map[string]any + for key, value := range aggMap { + if key != "aggs" && key != "aggregations" { + aggType = key + if val, ok := value.(map[string]any); ok { + aggValue = val + } + break + } + } + + if aggType == "" || aggValue == nil { + continue + } + + // Find the appropriate parser for this aggregation type + parser := p.findParser(aggType) + if parser == nil { + // Unknown aggregation type, skip it + continue + } + + // Try to parse as agg aggregation + if agg, err := parser.Parse(aggID, aggType, aggValue); err == nil && agg != nil { + switch agg.AggType { + case aggTypeBucket: + bucketAggs = append(bucketAggs, agg.toBucketAgg()) + case aggTypeMetric: + metricAggs = append(metricAggs, agg.toMetricAgg()) + } + } + + // Parse nested aggregations + nestedAggs := p.extractor.getMap(aggMap, "aggs") + if nestedAggs == nil { + nestedAggs = p.extractor.getMap(aggMap, "aggregations") + } + nestedBuckets, nestedMetrics := p.parseAggregations(nestedAggs) + bucketAggs = append(bucketAggs, nestedBuckets...) + metricAggs = append(metricAggs, nestedMetrics...) + } + + return bucketAggs, metricAggs +} + +// NewAggregationParser creates a new aggregation parser +func NewAggregationParser() AggregationParser { + return newCompositeParser() +} diff --git a/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser_test.go b/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser_test.go new file mode 100644 index 00000000000..c8ad0c9ef6e --- /dev/null +++ b/pkg/tsdb/elasticsearch/raw_dsl_aggregation_parser_test.go @@ -0,0 +1,706 @@ +package elasticsearch + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestFieldExtractor tests the field extraction utility +func TestFieldExtractor(t *testing.T) { + extractor := &fieldExtractor{} + + t.Run("getString", func(t *testing.T) { + data := map[string]any{ + "field": "value", + "number": 42, + "missing": nil, + } + + assert.Equal(t, "value", extractor.getString(data, "field")) + assert.Equal(t, "", extractor.getString(data, "number")) + assert.Equal(t, "", extractor.getString(data, "missing")) + assert.Equal(t, "", extractor.getString(data, "nonexistent")) + }) + + t.Run("getInt", func(t *testing.T) { + data := map[string]any{ + "float": 42.0, + "int": 100, + "string": "200", + "bad": "notanumber", + } + + assert.Equal(t, 42, extractor.getInt(data, "float")) + assert.Equal(t, 100, extractor.getInt(data, "int")) + assert.Equal(t, 200, extractor.getInt(data, "string")) + assert.Equal(t, 0, extractor.getInt(data, "bad")) + assert.Equal(t, 0, extractor.getInt(data, "nonexistent")) + }) + + t.Run("getFloat", func(t *testing.T) { + data := map[string]any{ + "float": 42.5, + "int": 100, + "string": "3.14", + } + + assert.Equal(t, 42.5, extractor.getFloat(data, "float")) + assert.Equal(t, 100.0, extractor.getFloat(data, "int")) + assert.Equal(t, 3.14, extractor.getFloat(data, "string")) + assert.Equal(t, 0.0, extractor.getFloat(data, "nonexistent")) + }) + + t.Run("getMap", func(t *testing.T) { + data := map[string]any{ + "map": map[string]any{"key": "value"}, + "notmap": "string", + } + + result := extractor.getMap(data, "map") + require.NotNil(t, result) + assert.Equal(t, "value", result["key"]) + + assert.Nil(t, extractor.getMap(data, "notmap")) + assert.Nil(t, extractor.getMap(data, "nonexistent")) + }) +} + +// TestDateHistogramParser tests the date histogram parser +func TestDateHistogramParser(t *testing.T) { + parser := &dateHistogramParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(dateHistType)) + assert.False(t, parser.CanParse("terms")) + }) + + t.Run("Parse with fixed_interval", func(t *testing.T) { + aggValue := map[string]any{ + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 1, + } + + agg, err := parser.Parse("1", dateHistType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + bucket := agg.toBucketAgg() + assert.Equal(t, "1", bucket.ID) + assert.Equal(t, dateHistType, bucket.Type) + assert.Equal(t, "@timestamp", bucket.Field) + assert.Equal(t, "30s", bucket.Settings.Get("interval").MustString()) + assert.Equal(t, "1", bucket.Settings.Get("min_doc_count").MustString()) + }) + + t.Run("Parse with calendar_interval", func(t *testing.T) { + aggValue := map[string]any{ + "field": "@timestamp", + "calendar_interval": "1d", + "time_zone": "UTC", + } + + agg, err := parser.Parse("2", dateHistType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + bucket := agg.toBucketAgg() + assert.Equal(t, "1d", bucket.Settings.Get("interval").MustString()) + assert.Equal(t, "UTC", bucket.Settings.Get("time_zone").MustString()) + }) + + t.Run("Parse returns bucket aggregation", func(t *testing.T) { + agg, err := parser.Parse("1", dateHistType, map[string]any{"field": "@timestamp"}) + assert.NoError(t, err) + assert.NotNil(t, agg) + assert.Equal(t, aggTypeBucket, agg.AggType) + }) +} + +// TestTermsParser tests the terms parser +func TestTermsParser(t *testing.T) { + parser := &termsParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(termsType)) + assert.False(t, parser.CanParse("histogram")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "field": "hostname.keyword", + "size": 10, + "order": map[string]any{"_count": "desc"}, + } + + agg, err := parser.Parse("3", termsType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + bucket := agg.toBucketAgg() + assert.Equal(t, "3", bucket.ID) + assert.Equal(t, termsType, bucket.Type) + assert.Equal(t, "hostname.keyword", bucket.Field) + assert.Equal(t, "10", bucket.Settings.Get("size").MustString()) + }) +} + +// TestHistogramParser tests the histogram parser +func TestHistogramParser(t *testing.T) { + parser := &histogramParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(histogramType)) + assert.False(t, parser.CanParse("terms")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "field": "response_time", + "interval": 50.0, + } + + agg, err := parser.Parse("4", histogramType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + bucket := agg.toBucketAgg() + assert.Equal(t, "4", bucket.ID) + assert.Equal(t, histogramType, bucket.Type) + assert.Equal(t, "response_time", bucket.Field) + assert.Equal(t, "50", bucket.Settings.Get("interval").MustString()) + }) +} + +// TestFiltersParser tests the filters parser +func TestFiltersParser(t *testing.T) { + parser := &filtersParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(filtersType)) + assert.False(t, parser.CanParse("terms")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "filters": map[string]any{ + "errors": map[string]any{"query_string": map[string]any{"query": "level:error"}}, + "warnings": map[string]any{"query_string": map[string]any{"query": "level:warning"}}, + }, + } + + agg, err := parser.Parse("filters", filtersType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + bucket := agg.toBucketAgg() + assert.Equal(t, "filters", bucket.ID) + assert.Equal(t, filtersType, bucket.Type) + filtersArray := bucket.Settings.Get("filters").MustArray() + assert.NotEmpty(t, filtersArray) + assert.Len(t, filtersArray, 2) + }) +} + +// TestSimpleMetricParser tests the simple metric parser +func TestSimpleMetricParser(t *testing.T) { + parser := newSimpleMetricParser() + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse("avg")) + assert.True(t, parser.CanParse("sum")) + assert.True(t, parser.CanParse("min")) + assert.True(t, parser.CanParse("max")) + assert.True(t, parser.CanParse("cardinality")) + assert.False(t, parser.CanParse("bucket_script")) + }) + + t.Run("Parse avg", func(t *testing.T) { + aggValue := map[string]any{ + "field": "response_time", + } + + agg, err := parser.Parse("1", "avg", aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "1", metric.ID) + assert.Equal(t, "avg", metric.Type) + assert.Equal(t, "response_time", metric.Field) + }) + + t.Run("Parse returns metric aggregation", func(t *testing.T) { + agg, err := parser.Parse("1", "avg", map[string]any{}) + assert.NoError(t, err) + assert.NotNil(t, agg) + assert.Equal(t, aggTypeMetric, agg.AggType) + }) +} + +// TestExtendedStatsParser tests the extended stats parser +func TestExtendedStatsParser(t *testing.T) { + parser := &extendedStatsParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(extendedStatsType)) + assert.False(t, parser.CanParse("avg")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "field": "response_time", + "sigma": 2, + } + + agg, err := parser.Parse("stats", extendedStatsType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "stats", metric.ID) + assert.Equal(t, extendedStatsType, metric.Type) + assert.Equal(t, "response_time", metric.Field) + }) +} + +// TestPercentilesParser tests the percentiles parser +func TestPercentilesParser(t *testing.T) { + parser := &percentilesParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse(percentilesType)) + assert.False(t, parser.CanParse("avg")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "field": "response_time", + "percents": []any{50.0, 95.0, 99.0}, + } + + agg, err := parser.Parse("percentiles", percentilesType, aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "percentiles", metric.ID) + assert.Equal(t, percentilesType, metric.Type) + assert.Equal(t, "response_time", metric.Field) + }) +} + +// TestPipelineParser tests the pipeline parser +func TestPipelineParser(t *testing.T) { + parser := newPipelineParser() + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse("moving_avg")) + assert.True(t, parser.CanParse("derivative")) + assert.True(t, parser.CanParse("cumulative_sum")) + assert.False(t, parser.CanParse("bucket_script")) + }) + + t.Run("Parse", func(t *testing.T) { + aggValue := map[string]any{ + "buckets_path": "1", + } + + agg, err := parser.Parse("moving", "moving_avg", aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "moving", metric.ID) + assert.Equal(t, "moving_avg", metric.Type) + assert.Equal(t, "1", metric.Field) + }) +} + +// TestBucketScriptParser tests the bucket script parser +func TestBucketScriptParser(t *testing.T) { + parser := &bucketScriptParser{extractor: &fieldExtractor{}} + + t.Run("CanParse", func(t *testing.T) { + assert.True(t, parser.CanParse("bucket_script")) + assert.False(t, parser.CanParse("moving_avg")) + }) + + t.Run("Parse with map buckets_path", func(t *testing.T) { + aggValue := map[string]any{ + "buckets_path": map[string]any{ + "count": "total", + }, + "script": "params.count / 60", + } + + agg, err := parser.Parse("rate", "bucket_script", aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "rate", metric.ID) + assert.Equal(t, "bucket_script", metric.Type) + assert.Equal(t, "total", metric.PipelineVariables["count"]) + assert.Equal(t, "params.count / 60", metric.Settings.Get("script").MustString()) + }) + + t.Run("Parse with string buckets_path", func(t *testing.T) { + aggValue := map[string]any{ + "buckets_path": "1", + } + + agg, err := parser.Parse("rate", "bucket_script", aggValue) + require.NoError(t, err) + require.NotNil(t, agg) + + metric := agg.toMetricAgg() + assert.Equal(t, "1", metric.PipelineVariables["var1"]) + }) +} + +// TestCompositeParser tests the full parser integration +func TestCompositeParser(t *testing.T) { + parser := NewAggregationParser() + + t.Run("Parse date histogram aggregation", func(t *testing.T) { + rawQuery := `{ + "query": { + "match_all": {} + }, + "aggs": { + "2": { + "date_histogram": { + "field": "@timestamp", + "fixed_interval": "30s", + "min_doc_count": 1 + } + } + } + }` + + bucketAggs, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + require.Len(t, metricAggs, 0) + + assert.Equal(t, "2", bucketAggs[0].ID) + assert.Equal(t, dateHistType, bucketAggs[0].Type) + assert.Equal(t, "@timestamp", bucketAggs[0].Field) + assert.Equal(t, "30s", bucketAggs[0].Settings.Get("interval").MustString()) + }) + + t.Run("Parse nested aggregations with metrics", func(t *testing.T) { + rawQuery := `{ + "query": { + "match_all": {} + }, + "aggs": { + "2": { + "date_histogram": { + "field": "@timestamp", + "fixed_interval": "30s" + }, + "aggs": { + "1": { + "avg": { + "field": "value" + } + }, + "3": { + "sum": { + "field": "total" + } + } + } + } + } + }` + + bucketAggs, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + require.Len(t, metricAggs, 2) + + // Check bucket aggregation + assert.Equal(t, "2", bucketAggs[0].ID) + assert.Equal(t, dateHistType, bucketAggs[0].Type) + + // Check metric aggregations + avgFound := false + sumFound := false + for _, m := range metricAggs { + if m.ID == "1" && m.Type == "avg" && m.Field == "value" { + avgFound = true + } + if m.ID == "3" && m.Type == "sum" && m.Field == "total" { + sumFound = true + } + } + assert.True(t, avgFound, "avg aggregation not found") + assert.True(t, sumFound, "sum aggregation not found") + }) + + t.Run("Parse terms aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "3": { + "terms": { + "field": "hostname.keyword", + "size": 10, + "order": { + "_count": "desc" + } + } + } + } + }` + + bucketAggs, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + require.Len(t, metricAggs, 0) + + assert.Equal(t, "3", bucketAggs[0].ID) + assert.Equal(t, termsType, bucketAggs[0].Type) + assert.Equal(t, "hostname.keyword", bucketAggs[0].Field) + assert.Equal(t, "10", bucketAggs[0].Settings.Get("size").MustString()) + }) + + t.Run("Parse histogram aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "4": { + "histogram": { + "field": "response_time", + "interval": 50 + } + } + } + }` + + bucketAggs, _, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + + assert.Equal(t, "4", bucketAggs[0].ID) + assert.Equal(t, histogramType, bucketAggs[0].Type) + assert.Equal(t, "response_time", bucketAggs[0].Field) + assert.Equal(t, "50", bucketAggs[0].Settings.Get("interval").MustString()) + }) + + t.Run("Parse extended stats aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "stats": { + "extended_stats": { + "field": "response_time", + "sigma": 2 + } + } + } + }` + + _, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, metricAggs, 1) + + assert.Equal(t, "stats", metricAggs[0].ID) + assert.Equal(t, extendedStatsType, metricAggs[0].Type) + assert.Equal(t, "response_time", metricAggs[0].Field) + }) + + t.Run("Parse percentiles aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "percentiles": { + "percentiles": { + "field": "response_time", + "percents": [50, 95, 99] + } + } + } + }` + + _, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, metricAggs, 1) + + assert.Equal(t, "percentiles", metricAggs[0].ID) + assert.Equal(t, percentilesType, metricAggs[0].Type) + }) + + t.Run("Parse pipeline aggregations", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "2": { + "date_histogram": { + "field": "@timestamp", + "fixed_interval": "1m" + }, + "aggs": { + "1": { + "avg": { + "field": "value" + } + }, + "moving": { + "moving_avg": { + "buckets_path": "1" + } + }, + "deriv": { + "derivative": { + "buckets_path": "1" + } + } + } + } + } + }` + + bucketAggs, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + require.GreaterOrEqual(t, len(metricAggs), 2) // At least avg and one pipeline + + // Find pipeline aggregations + movingAvgFound := false + derivativeFound := false + for _, m := range metricAggs { + if m.ID == "moving" && m.Type == "moving_avg" { + movingAvgFound = true + assert.Equal(t, "1", m.Field) + } + if m.ID == "deriv" && m.Type == "derivative" { + derivativeFound = true + assert.Equal(t, "1", m.Field) + } + } + assert.True(t, movingAvgFound, "moving_avg aggregation not found") + assert.True(t, derivativeFound, "derivative aggregation not found") + }) + + t.Run("Parse bucket script aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "2": { + "date_histogram": { + "field": "@timestamp", + "fixed_interval": "1m" + }, + "aggs": { + "total": { + "sum": { + "field": "bytes" + } + }, + "rate": { + "bucket_script": { + "buckets_path": { + "count": "total" + }, + "script": "params.count / 60" + } + } + } + } + } + }` + + _, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + + // Find bucket script + var bucketScriptAgg *MetricAgg + for _, m := range metricAggs { + if m.ID == "rate" && m.Type == "bucket_script" { + bucketScriptAgg = m + break + } + } + require.NotNil(t, bucketScriptAgg, "bucket_script aggregation not found") + assert.Equal(t, "params.count / 60", bucketScriptAgg.Settings.Get("script").MustString()) + assert.Equal(t, "total", bucketScriptAgg.PipelineVariables["count"]) + }) + + t.Run("Parse filters aggregation", func(t *testing.T) { + rawQuery := `{ + "aggs": { + "messages": { + "filters": { + "filters": { + "errors": { + "query_string": { + "query": "level:error" + } + }, + "warnings": { + "query_string": { + "query": "level:warning" + } + } + } + } + } + } + }` + + bucketAggs, _, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + + assert.Equal(t, "messages", bucketAggs[0].ID) + assert.Equal(t, filtersType, bucketAggs[0].Type) + }) + + t.Run("Handle empty query", func(t *testing.T) { + bucketAggs, metricAggs, err := parser.Parse("") + require.NoError(t, err) + assert.Nil(t, bucketAggs) + assert.Nil(t, metricAggs) + }) + + t.Run("Handle query without aggregations", func(t *testing.T) { + rawQuery := `{ + "query": { + "match_all": {} + } + }` + + bucketAggs, metricAggs, err := parser.Parse(rawQuery) + require.NoError(t, err) + assert.Nil(t, bucketAggs) + assert.Nil(t, metricAggs) + }) + + t.Run("Handle invalid JSON", func(t *testing.T) { + rawQuery := `{invalid json` + + _, _, err := parser.Parse(rawQuery) + require.Error(t, err) + }) + + t.Run("Use 'aggregations' instead of 'aggs'", func(t *testing.T) { + rawQuery := `{ + "query": { + "match_all": {} + }, + "aggregations": { + "2": { + "date_histogram": { + "field": "@timestamp", + "fixed_interval": "30s" + } + } + } + }` + + bucketAggs, _, err := parser.Parse(rawQuery) + require.NoError(t, err) + require.Len(t, bucketAggs, 1) + assert.Equal(t, "2", bucketAggs[0].ID) + }) +} diff --git a/pkg/tsdb/opentsdb/callresource.go b/pkg/tsdb/opentsdb/callresource.go new file mode 100644 index 00000000000..be0f81b9c80 --- /dev/null +++ b/pkg/tsdb/opentsdb/callresource.go @@ -0,0 +1,67 @@ +package opentsdb + +import ( + "fmt" + "net/http" + "net/url" + "path" + + "github.com/grafana/grafana-plugin-sdk-go/backend" +) + +func (s *Service) HandleSuggestQuery(rw http.ResponseWriter, req *http.Request) { + logger := logger.FromContext(req.Context()) + + dsInfo, err := s.getDSInfo(req.Context(), backend.PluginConfigFromContext(req.Context())) + if err != nil { + http.Error(rw, fmt.Sprintf("failed to get datasource info: %v", err), http.StatusInternalServerError) + return + } + + u, err := url.Parse(dsInfo.URL) + if err != nil { + http.Error(rw, fmt.Sprintf("failed to parse datasource URL: %v", err), http.StatusInternalServerError) + return + } + + u.Path = path.Join(u.Path, "api/suggest") + u.RawQuery = req.URL.RawQuery + httpReq, err := http.NewRequestWithContext(req.Context(), http.MethodGet, u.String(), nil) + if err != nil { + http.Error(rw, fmt.Sprintf("failed to create request: %v", err), http.StatusInternalServerError) + return + } + + res, err := dsInfo.HTTPClient.Do(httpReq) + if err != nil { + http.Error(rw, fmt.Sprintf("failed to execute request: %v", err), http.StatusInternalServerError) + return + } + + defer func() { + if err := res.Body.Close(); err != nil { + logger.Error("Failed to close response body", "error", err) + } + }() + + responseBody, err := DecodeResponseBody(res, logger) + if err != nil { + http.Error(rw, fmt.Sprintf("failed to decode response: %v", err), http.StatusInternalServerError) + return + } + + for name, values := range res.Header { + if name == "Content-Encoding" || name == "Content-Length" { + continue + } + for _, value := range values { + rw.Header().Add(name, value) + } + } + + rw.WriteHeader(res.StatusCode) + if _, err := rw.Write(responseBody); err != nil { + logger.Error("Failed to write response", "error", err) + return + } +} diff --git a/pkg/tsdb/opentsdb/opentsdb.go b/pkg/tsdb/opentsdb/opentsdb.go index d00242f6432..a694445e1cd 100644 --- a/pkg/tsdb/opentsdb/opentsdb.go +++ b/pkg/tsdb/opentsdb/opentsdb.go @@ -4,21 +4,15 @@ import ( "context" "encoding/json" "fmt" - "io" "net/http" "net/url" "path" - "sort" - "strconv" - "strings" - "time" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend/datasource" "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient" "github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt" - "github.com/grafana/grafana-plugin-sdk-go/backend/log" - "github.com/grafana/grafana-plugin-sdk-go/data" + "github.com/grafana/grafana-plugin-sdk-go/backend/resource/httpadapter" ) var logger = backend.NewLoggerWith("tsdb.opentsdb") @@ -155,6 +149,14 @@ func (s *Service) CheckHealth(ctx context.Context, req *backend.CheckHealthReque }, nil } +func (s *Service) CallResource(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error { + mux := http.NewServeMux() + mux.HandleFunc("/api/suggest", s.HandleSuggestQuery) + + handler := httpadapter.New(mux) + return handler.CallResource(ctx, req, sender) +} + func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { logger := logger.FromContext(ctx) @@ -166,16 +168,15 @@ func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) result := backend.NewQueryDataResponse() for _, query := range req.Queries { - // Build OpenTsdbQuery with per-query time range tsdbQuery := OpenTsdbQuery{ Start: query.TimeRange.From.Unix(), End: query.TimeRange.To.Unix(), Queries: []map[string]any{ - s.buildMetric(query), + BuildMetric(query), }, } - httpReq, err := s.createRequest(ctx, logger, dsInfo, tsdbQuery) + httpReq, err := CreateRequest(ctx, logger, dsInfo, tsdbQuery) if err != nil { return nil, err } @@ -191,251 +192,17 @@ func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) } }() - queryRes, err := s.parseResponse(logger, httpRes, query.RefID, dsInfo.TSDBVersion) + queryRes, err := ParseResponse(logger, httpRes, query.RefID, dsInfo.TSDBVersion) if err != nil { return nil, err } - // Attach parsed result for this query's RefID result.Responses[query.RefID] = queryRes.Responses[query.RefID] } return result, nil } -func (s *Service) createRequest(ctx context.Context, logger log.Logger, dsInfo *datasourceInfo, data OpenTsdbQuery) (*http.Request, error) { - u, err := url.Parse(dsInfo.URL) - if err != nil { - return nil, err - } - u.Path = path.Join(u.Path, "api/query") - if dsInfo.TSDBVersion == 4 { - queryParams := u.Query() - queryParams.Set("arrays", "true") - u.RawQuery = queryParams.Encode() - } - - postData, err := json.Marshal(data) - if err != nil { - logger.Info("Failed marshaling data", "error", err) - return nil, fmt.Errorf("failed to create request: %w", err) - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(string(postData))) - if err != nil { - logger.Info("Failed to create request", "error", err) - return nil, fmt.Errorf("failed to create request: %w", err) - } - - req.Header.Set("Content-Type", "application/json") - return req, nil -} - -func createInitialFrame(val OpenTsdbCommon, length int, refID string) *data.Frame { - labels := data.Labels{} - for label, value := range val.Tags { - labels[label] = value - } - - tagKeys := make([]string, 0, len(val.Tags)+len(val.AggregateTags)) - for tagKey := range val.Tags { - tagKeys = append(tagKeys, tagKey) - } - sort.Strings(tagKeys) - tagKeys = append(tagKeys, val.AggregateTags...) - - frame := data.NewFrameOfFieldTypes(val.Metric, length, data.FieldTypeTime, data.FieldTypeFloat64) - frame.Meta = &data.FrameMeta{ - Type: data.FrameTypeTimeSeriesMulti, - TypeVersion: data.FrameTypeVersion{0, 1}, - Custom: map[string]any{"tagKeys": tagKeys}, - } - frame.RefID = refID - timeField := frame.Fields[0] - timeField.Name = data.TimeSeriesTimeFieldName - dataField := frame.Fields[1] - dataField.Name = val.Metric - dataField.Labels = labels - - return frame -} - -// Parse response function for OpenTSDB version 2.4 -func parseResponse24(responseData []OpenTsdbResponse24, refID string, frames data.Frames) data.Frames { - for _, val := range responseData { - frame := createInitialFrame(val.OpenTsdbCommon, len(val.DataPoints), refID) - - for i, point := range val.DataPoints { - frame.SetRow(i, time.Unix(int64(point[0]), 0).UTC(), point[1]) - } - - frames = append(frames, frame) - } - - return frames -} - -// Parse response function for OpenTSDB versions < 2.4 -func parseResponseLT24(responseData []OpenTsdbResponse, refID string, frames data.Frames) (data.Frames, error) { - for _, val := range responseData { - frame := createInitialFrame(val.OpenTsdbCommon, len(val.DataPoints), refID) - - // Order the timestamps in ascending order to avoid issues like https://github.com/grafana/grafana/issues/38729 - timestamps := make([]string, 0, len(val.DataPoints)) - for timestamp := range val.DataPoints { - timestamps = append(timestamps, timestamp) - } - sort.Strings(timestamps) - - for i, timeString := range timestamps { - timestamp, err := strconv.ParseInt(timeString, 10, 64) - if err != nil { - logger.Info("Failed to unmarshal opentsdb timestamp", "timestamp", timeString) - return frames, err - } - frame.SetRow(i, time.Unix(timestamp, 0).UTC(), val.DataPoints[timeString]) - } - - frames = append(frames, frame) - } - - return frames, nil -} - -func (s *Service) parseResponse(logger log.Logger, res *http.Response, refID string, tsdbVersion float32) (*backend.QueryDataResponse, error) { - resp := backend.NewQueryDataResponse() - - body, err := io.ReadAll(res.Body) - if err != nil { - return nil, err - } - defer func() { - if err := res.Body.Close(); err != nil { - logger.Warn("Failed to close response body", "err", err) - } - }() - - if res.StatusCode/100 != 2 { - logger.Info("Request failed", "status", res.Status, "body", string(body)) - return nil, fmt.Errorf("request failed, status: %s", res.Status) - } - - frames := data.Frames{} - - var responseData []OpenTsdbResponse - var responseData24 []OpenTsdbResponse24 - if tsdbVersion == 4 { - err = json.Unmarshal(body, &responseData24) - if err != nil { - logger.Info("Failed to unmarshal opentsdb response", "error", err, "status", res.Status, "body", string(body)) - return nil, err - } - - frames = parseResponse24(responseData24, refID, frames) - } else { - err = json.Unmarshal(body, &responseData) - if err != nil { - logger.Info("Failed to unmarshal opentsdb response", "error", err, "status", res.Status, "body", string(body)) - return nil, err - } - - frames, err = parseResponseLT24(responseData, refID, frames) - if err != nil { - return nil, err - } - } - - result := resp.Responses[refID] - result.Frames = frames - resp.Responses[refID] = result - return resp, nil -} - -func (s *Service) buildMetric(query backend.DataQuery) map[string]any { - metric := make(map[string]any) - - var model QueryModel - if err := json.Unmarshal(query.JSON, &model); err != nil { - return nil - } - - // Setting metric and aggregator - metric["metric"] = model.Metric - metric["aggregator"] = model.Aggregator - - // Setting downsampling options - if !model.DisableDownsampling { - downsampleInterval := model.DownsampleInterval - if downsampleInterval == "" { - if ms := query.Interval.Milliseconds(); ms > 0 { - downsampleInterval = FormatDownsampleInterval(ms) - } else { - downsampleInterval = "1m" - } - } else if strings.Contains(downsampleInterval, ".") && strings.HasSuffix(downsampleInterval, "s") { - if val, err := strconv.ParseFloat(strings.TrimSuffix(downsampleInterval, "s"), 64); err == nil { - downsampleInterval = strconv.FormatInt(int64(val*1000), 10) + "ms" - } - } - - downsample := downsampleInterval + "-" + model.DownsampleAggregator - if model.DownsampleFillPolicy != "" && model.DownsampleFillPolicy != "none" { - metric["downsample"] = downsample + "-" + model.DownsampleFillPolicy - } else { - metric["downsample"] = downsample - } - } - - // Setting rate options - if model.ShouldComputeRate { - metric["rate"] = true - rateOptions := make(map[string]any) - rateOptions["counter"] = model.IsCounter - - var counterMax *float64 - if model.CounterMax != "" { - if val, err := strconv.ParseFloat(model.CounterMax, 64); err == nil { - counterMax = &val - } - } - if counterMax != nil { - rateOptions["counterMax"] = *counterMax - } - - var counterResetValue *float64 - if model.CounterResetValue != "" { - if val, err := strconv.ParseFloat(model.CounterResetValue, 64); err == nil { - counterResetValue = &val - } - } - if counterResetValue != nil { - rateOptions["resetValue"] = *counterResetValue - } - - if counterMax == nil && (counterResetValue == nil || *counterResetValue == 0) { - rateOptions["dropResets"] = true - } - - metric["rateOptions"] = rateOptions - } - - // Setting tags - if len(model.Tags) > 0 { - metric["tags"] = model.Tags - } - - // Setting filters - if len(model.Filters) > 0 { - metric["filters"] = model.Filters - } - - if model.ExplicitTags { - metric["explicitTags"] = true - } - - return metric -} - func (s *Service) getDSInfo(ctx context.Context, pluginCtx backend.PluginContext) (*datasourceInfo, error) { i, err := s.im.Get(ctx, pluginCtx) if err != nil { diff --git a/pkg/tsdb/opentsdb/opentsdb_test.go b/pkg/tsdb/opentsdb/opentsdb_test.go index a0150b9e75f..72bbe6bf8b9 100644 --- a/pkg/tsdb/opentsdb/opentsdb_test.go +++ b/pkg/tsdb/opentsdb/opentsdb_test.go @@ -71,8 +71,6 @@ func TestCheckHealth(t *testing.T) { } func TestBuildMetric(t *testing.T) { - service := &Service{} - t.Run("Metric with no downsampleInterval should use query interval", func(t *testing.T) { query := backend.DataQuery{ JSON: []byte(` @@ -88,7 +86,7 @@ func TestBuildMetric(t *testing.T) { Interval: 30 * time.Second, } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "30s-avg", metric["downsample"], "should use query interval formatted as seconds") }) @@ -106,7 +104,7 @@ func TestBuildMetric(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "500ms-avg", metric["downsample"], "should convert 0.5s to 500ms") }) @@ -125,7 +123,7 @@ func TestBuildMetric(t *testing.T) { Interval: 500 * time.Millisecond, } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "500ms-avg", metric["downsample"], "should use query interval formatted as milliseconds") }) @@ -144,7 +142,7 @@ func TestBuildMetric(t *testing.T) { Interval: 5 * time.Minute, } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "5m-sum", metric["downsample"], "should use query interval formatted as minutes") }) @@ -163,7 +161,7 @@ func TestBuildMetric(t *testing.T) { Interval: 2 * time.Hour, } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "2h-max", metric["downsample"], "should use query interval formatted as hours") }) @@ -182,7 +180,7 @@ func TestBuildMetric(t *testing.T) { Interval: 48 * time.Hour, } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Equal(t, "2d-min", metric["downsample"], "should use query interval formatted as days") }) @@ -201,7 +199,7 @@ func TestBuildMetric(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.True(t, metric["explicitTags"].(bool), "explicitTags should be true") metricTags := metric["tags"].(map[string]any) @@ -223,16 +221,14 @@ func TestBuildMetric(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Nil(t, metric["explicitTags"], "explicitTags should not be present when false") }) } func TestOpenTsdbExecutor(t *testing.T) { - service := &Service{} - t.Run("create request", func(t *testing.T) { - req, err := service.createRequest(context.Background(), logger, &datasourceInfo{}, OpenTsdbQuery{}) + req, err := CreateRequest(context.Background(), logger, &datasourceInfo{}, OpenTsdbQuery{}) require.NoError(t, err) assert.Equal(t, "POST", req.Method) @@ -247,7 +243,7 @@ func TestOpenTsdbExecutor(t *testing.T) { response := `{ invalid }` tsdbVersion := float32(4) - result, err := service.parseResponse(logger, &http.Response{Body: io.NopCloser(strings.NewReader(response))}, "A", tsdbVersion) + result, err := ParseResponse(logger, &http.Response{Body: io.NopCloser(strings.NewReader(response))}, "A", tsdbVersion) require.Nil(t, result) require.Error(t, err) }) @@ -284,7 +280,7 @@ func TestOpenTsdbExecutor(t *testing.T) { resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 - result, err := service.parseResponse(logger, &resp, "A", tsdbVersion) + result, err := ParseResponse(logger, &resp, "A", tsdbVersion) require.NoError(t, err) frame := result.Responses["A"] @@ -326,7 +322,7 @@ func TestOpenTsdbExecutor(t *testing.T) { resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 - result, err := service.parseResponse(logger, &resp, "A", tsdbVersion) + result, err := ParseResponse(logger, &resp, "A", tsdbVersion) require.NoError(t, err) frame := result.Responses["A"] @@ -399,7 +395,7 @@ func TestOpenTsdbExecutor(t *testing.T) { resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 - result, err := service.parseResponse(logger, &resp, "A", tsdbVersion) + result, err := ParseResponse(logger, &resp, "A", tsdbVersion) require.NoError(t, err) frame := result.Responses["A"] @@ -444,7 +440,7 @@ func TestOpenTsdbExecutor(t *testing.T) { resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 - result, err := service.parseResponse(logger, &resp, myRefid, tsdbVersion) + result, err := ParseResponse(logger, &resp, myRefid, tsdbVersion) require.NoError(t, err) if diff := cmp.Diff(testFrame, result.Responses[myRefid].Frames[0], data.FrameTestCompareOptions()...); diff != "" { @@ -473,7 +469,7 @@ func TestOpenTsdbExecutor(t *testing.T) { resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 - result, err := service.parseResponse(logger, &resp, "A", tsdbVersion) + result, err := ParseResponse(logger, &resp, "A", tsdbVersion) require.NoError(t, err) frame := result.Responses["A"].Frames[0] @@ -505,7 +501,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Len(t, metric, 3) require.Equal(t, "cpu.average.percent", metric["metric"]) @@ -527,7 +523,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Len(t, metric, 2) require.Equal(t, "cpu.average.percent", metric["metric"]) @@ -548,7 +544,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Len(t, metric, 3) require.Equal(t, "cpu.average.percent", metric["metric"]) @@ -574,7 +570,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Len(t, metric, 3) require.Equal(t, "cpu.average.percent", metric["metric"]) @@ -605,7 +601,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) require.Len(t, metric, 5) require.Equal(t, "cpu.average.percent", metric["metric"]) @@ -640,7 +636,7 @@ func TestOpenTsdbExecutor(t *testing.T) { ), } - metric := service.buildMetric(query) + metric := BuildMetric(query) t.Log(metric) require.Len(t, metric, 5) diff --git a/pkg/tsdb/opentsdb/standalone/datasource.go b/pkg/tsdb/opentsdb/standalone/datasource.go index c2eacaf1d53..97241d651d6 100644 --- a/pkg/tsdb/opentsdb/standalone/datasource.go +++ b/pkg/tsdb/opentsdb/standalone/datasource.go @@ -10,8 +10,9 @@ import ( ) var ( - _ backend.QueryDataHandler = (*Datasource)(nil) - _ backend.CheckHealthHandler = (*Datasource)(nil) + _ backend.CheckHealthHandler = (*Datasource)(nil) + _ backend.CallResourceHandler = (*Datasource)(nil) + _ backend.QueryDataHandler = (*Datasource)(nil) ) type Datasource struct { @@ -24,10 +25,14 @@ func NewDatasource(context.Context, backend.DataSourceInstanceSettings) (instanc }, nil } -func (d *Datasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { - return d.Service.QueryData(ctx, req) -} - func (d *Datasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRequest) (*backend.CheckHealthResult, error) { return d.Service.CheckHealth(ctx, req) } + +func (d *Datasource) CallResource(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error { + return d.Service.CallResource(ctx, req, sender) +} + +func (d *Datasource) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { + return d.Service.QueryData(ctx, req) +} diff --git a/pkg/tsdb/opentsdb/utils.go b/pkg/tsdb/opentsdb/utils.go index ae57b3e787a..ddfa8122fce 100644 --- a/pkg/tsdb/opentsdb/utils.go +++ b/pkg/tsdb/opentsdb/utils.go @@ -1,8 +1,22 @@ package opentsdb import ( + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "path" + "sort" "strconv" + "strings" "time" + + "github.com/grafana/grafana-plugin-sdk-go/backend" + "github.com/grafana/grafana-plugin-sdk-go/backend/log" + "github.com/grafana/grafana-plugin-sdk-go/data" ) func FormatDownsampleInterval(ms int64) string { @@ -29,3 +43,262 @@ func FormatDownsampleInterval(ms int64) string { days := int64(duration / (24 * time.Hour)) return strconv.FormatInt(days, 10) + "d" } + +func BuildMetric(query backend.DataQuery) map[string]any { + metric := make(map[string]any) + + var model QueryModel + if err := json.Unmarshal(query.JSON, &model); err != nil { + return nil + } + + // Setting metric and aggregator + metric["metric"] = model.Metric + metric["aggregator"] = model.Aggregator + + // Setting downsampling options + if !model.DisableDownsampling { + downsampleInterval := model.DownsampleInterval + if downsampleInterval == "" { + if ms := query.Interval.Milliseconds(); ms > 0 { + downsampleInterval = FormatDownsampleInterval(ms) + } else { + downsampleInterval = "1m" + } + } else if strings.Contains(downsampleInterval, ".") && strings.HasSuffix(downsampleInterval, "s") { + if val, err := strconv.ParseFloat(strings.TrimSuffix(downsampleInterval, "s"), 64); err == nil { + downsampleInterval = strconv.FormatInt(int64(val*1000), 10) + "ms" + } + } + + downsample := downsampleInterval + "-" + model.DownsampleAggregator + if model.DownsampleFillPolicy != "" && model.DownsampleFillPolicy != "none" { + metric["downsample"] = downsample + "-" + model.DownsampleFillPolicy + } else { + metric["downsample"] = downsample + } + } + + // Setting rate options + if model.ShouldComputeRate { + metric["rate"] = true + rateOptions := make(map[string]any) + rateOptions["counter"] = model.IsCounter + + var counterMax *float64 + if model.CounterMax != "" { + if val, err := strconv.ParseFloat(model.CounterMax, 64); err == nil { + counterMax = &val + } + } + if counterMax != nil { + rateOptions["counterMax"] = *counterMax + } + + var counterResetValue *float64 + if model.CounterResetValue != "" { + if val, err := strconv.ParseFloat(model.CounterResetValue, 64); err == nil { + counterResetValue = &val + } + } + if counterResetValue != nil { + rateOptions["resetValue"] = *counterResetValue + } + + if counterMax == nil && (counterResetValue == nil || *counterResetValue == 0) { + rateOptions["dropResets"] = true + } + + metric["rateOptions"] = rateOptions + } + + // Setting tags + if len(model.Tags) > 0 { + metric["tags"] = model.Tags + } + + // Setting filters + if len(model.Filters) > 0 { + metric["filters"] = model.Filters + } + + if model.ExplicitTags { + metric["explicitTags"] = true + } + + return metric +} + +func CreateRequest(ctx context.Context, logger log.Logger, dsInfo *datasourceInfo, data OpenTsdbQuery) (*http.Request, error) { + u, err := url.Parse(dsInfo.URL) + if err != nil { + return nil, err + } + u.Path = path.Join(u.Path, "api/query") + if dsInfo.TSDBVersion == 4 { + queryParams := u.Query() + queryParams.Set("arrays", "true") + u.RawQuery = queryParams.Encode() + } + + postData, err := json.Marshal(data) + if err != nil { + logger.Info("Failed marshaling data", "error", err) + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), strings.NewReader(string(postData))) + if err != nil { + logger.Info("Failed to create request", "error", err) + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Header.Set("Content-Type", "application/json") + return req, nil +} + +func DecodeResponseBody(res *http.Response, logger log.Logger) ([]byte, error) { + encoding := res.Header.Get("Content-Encoding") + var reader io.Reader + + switch encoding { + case "gzip": + gzipReader, err := gzip.NewReader(res.Body) + if err != nil { + return nil, fmt.Errorf("failed to create gzip reader: %w", err) + } + defer func() { + if err := gzipReader.Close(); err != nil { + logger.Warn("Failed to close gzip reader", "error", err) + } + }() + reader = gzipReader + default: + reader = res.Body + } + + body, err := io.ReadAll(reader) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + return body, nil +} + +func CreateDataFrame(val OpenTsdbCommon, length int, refID string) *data.Frame { + labels := data.Labels{} + for label, value := range val.Tags { + labels[label] = value + } + + tagKeys := make([]string, 0, len(val.Tags)+len(val.AggregateTags)) + for tagKey := range val.Tags { + tagKeys = append(tagKeys, tagKey) + } + sort.Strings(tagKeys) + tagKeys = append(tagKeys, val.AggregateTags...) + + frame := data.NewFrameOfFieldTypes(val.Metric, length, data.FieldTypeTime, data.FieldTypeFloat64) + frame.Meta = &data.FrameMeta{ + Type: data.FrameTypeTimeSeriesMulti, + TypeVersion: data.FrameTypeVersion{0, 1}, + Custom: map[string]any{"tagKeys": tagKeys}, + } + frame.RefID = refID + timeField := frame.Fields[0] + timeField.Name = data.TimeSeriesTimeFieldName + dataField := frame.Fields[1] + dataField.Name = val.Metric + dataField.Labels = labels + + return frame +} + +func ParseResponse(logger log.Logger, res *http.Response, refID string, tsdbVersion float32) (*backend.QueryDataResponse, error) { + resp := backend.NewQueryDataResponse() + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + defer func() { + if err := res.Body.Close(); err != nil { + logger.Warn("Failed to close response body", "err", err) + } + }() + + if res.StatusCode/100 != 2 { + logger.Info("Request failed", "status", res.Status, "body", string(body)) + return nil, fmt.Errorf("request failed, status: %s", res.Status) + } + + frames := data.Frames{} + + var responseData []OpenTsdbResponse + var responseData24 []OpenTsdbResponse24 + if tsdbVersion == 4 { + err = json.Unmarshal(body, &responseData24) + if err != nil { + logger.Info("Failed to unmarshal opentsdb response", "error", err, "status", res.Status, "body", string(body)) + return nil, err + } + + frames = ParseResponse24(responseData24, refID, frames) + } else { + err = json.Unmarshal(body, &responseData) + if err != nil { + logger.Info("Failed to unmarshal opentsdb response", "error", err, "status", res.Status, "body", string(body)) + return nil, err + } + + frames, err = ParseResponseLT24(responseData, refID, frames) + if err != nil { + return nil, err + } + } + + result := resp.Responses[refID] + result.Frames = frames + resp.Responses[refID] = result + return resp, nil +} + +func ParseResponse24(responseData []OpenTsdbResponse24, refID string, frames data.Frames) data.Frames { + for _, val := range responseData { + frame := CreateDataFrame(val.OpenTsdbCommon, len(val.DataPoints), refID) + + for i, point := range val.DataPoints { + frame.SetRow(i, time.Unix(int64(point[0]), 0).UTC(), point[1]) + } + + frames = append(frames, frame) + } + + return frames +} + +func ParseResponseLT24(responseData []OpenTsdbResponse, refID string, frames data.Frames) (data.Frames, error) { + for _, val := range responseData { + frame := CreateDataFrame(val.OpenTsdbCommon, len(val.DataPoints), refID) + + // Order the timestamps in ascending order to avoid issues like https://github.com/grafana/grafana/issues/38729 + timestamps := make([]string, 0, len(val.DataPoints)) + for timestamp := range val.DataPoints { + timestamps = append(timestamps, timestamp) + } + sort.Strings(timestamps) + + for i, timeString := range timestamps { + timestamp, err := strconv.ParseInt(timeString, 10, 64) + if err != nil { + logger.Info("Failed to unmarshal opentsdb timestamp", "timestamp", timeString) + return frames, err + } + frame.SetRow(i, time.Unix(timestamp, 0).UTC(), val.DataPoints[timeString]) + } + + frames = append(frames, frame) + } + + return frames, nil +} diff --git a/pkg/tsdb/tempo/tempo.go b/pkg/tsdb/tempo/tempo.go index 1224c3b7029..cb797184a60 100644 --- a/pkg/tsdb/tempo/tempo.go +++ b/pkg/tsdb/tempo/tempo.go @@ -280,7 +280,15 @@ func (s *Service) handleTagValues(rw http.ResponseWriter, req *http.Request) { return } - tempoPath := fmt.Sprintf("api/v2/search/tag/%s/values", encodedTag) + // escape tag + tag, err := url.PathUnescape(encodedTag) + if err != nil { + s.logger.Error("Failed to unescape", "error", err, "tag", encodedTag) + http.Error(rw, "Invalid 'tag' parameter", http.StatusBadRequest) + return + } + + tempoPath := fmt.Sprintf("api/v2/search/tag/%s/values", tag) s.proxyToTempo(rw, req, tempoPath) } diff --git a/public/api-enterprise-spec.json b/public/api-enterprise-spec.json index d2fdd854168..9f09c0135d7 100644 --- a/public/api-enterprise-spec.json +++ b/public/api-enterprise-spec.json @@ -2263,8 +2263,7 @@ "operationId": "getTeamGroupsApi", "parameters": [ { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true @@ -2308,8 +2307,7 @@ } }, { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true @@ -2350,8 +2348,7 @@ "in": "query" }, { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true diff --git a/public/api-merged.json b/public/api-merged.json index 6effd7054fa..323a545e0cf 100644 --- a/public/api-merged.json +++ b/public/api-merged.json @@ -3402,11 +3402,12 @@ }, "/dashboards/home": { "get": { + "description": "NOTE: the home dashboard is configured in preferences. This API will be removed in G13", "tags": [ "dashboards" ], - "summary": "Get home dashboard.", "operationId": "getHomeDashboard", + "deprecated": true, "responses": { "200": { "$ref": "#/responses/getHomeDashboardResponse" @@ -9926,8 +9927,7 @@ "operationId": "getTeamGroupsApi", "parameters": [ { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true @@ -9971,8 +9971,7 @@ } }, { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true @@ -10013,8 +10012,7 @@ "in": "query" }, { - "type": "integer", - "format": "int64", + "type": "string", "name": "teamId", "in": "path", "required": true diff --git a/public/app/core/components/AppChrome/TopBar/SingleTopBar.tsx b/public/app/core/components/AppChrome/TopBar/SingleTopBar.tsx index 6542e457f2c..d5179570ef3 100644 --- a/public/app/core/components/AppChrome/TopBar/SingleTopBar.tsx +++ b/public/app/core/components/AppChrome/TopBar/SingleTopBar.tsx @@ -93,7 +93,6 @@ export const SingleTopBar = memo(function SingleTopBar({ justifyContent={'flex-end'} flex={1} data-testid={!showToolbarLevel ? Components.NavToolbar.container : undefined} - minWidth={{ xs: 'unset', lg: 0 }} > diff --git a/public/app/core/components/NestedFolderPicker/useFoldersQuery.test.tsx b/public/app/core/components/NestedFolderPicker/useFoldersQuery.test.tsx index 534c175d436..9a336b09ba0 100644 --- a/public/app/core/components/NestedFolderPicker/useFoldersQuery.test.tsx +++ b/public/app/core/components/NestedFolderPicker/useFoldersQuery.test.tsx @@ -12,7 +12,7 @@ import { DashboardViewItem } from '../../../features/search/types'; import { useFoldersQuery } from './useFoldersQuery'; import { getCustomRootFolderItem, getRootFolderItem } from './utils'; -const [_, { folderA, folderB, folderC }] = getFolderFixtures(); +const [_, { folderA, folderB, folderC, folderD }] = getFolderFixtures(); runtime.setBackendSrv(backendSrv); setupMockServer(); @@ -44,7 +44,7 @@ describe('useFoldersQuery', () => { const [_dashboardsContainer, ...items] = await testFn(); const sortedItemTitles = items.map((item) => (item.item as DashboardViewItem).title).sort(); - const expectedTitles = [folderA.item.title, folderB.item.title, folderC.item.title].sort(); + const expectedTitles = [folderA.item.title, folderB.item.title, folderC.item.title, folderD.item.title].sort(); expect(sortedItemTitles).toEqual(expectedTitles); }); diff --git a/public/app/core/icons/cached.json b/public/app/core/icons/cached.json index e78419e6d72..6e35e64dd0c 100644 --- a/public/app/core/icons/cached.json +++ b/public/app/core/icons/cached.json @@ -193,5 +193,6 @@ "unicons/ban", "unicons/git", "unicons/bitbucket", - "unicons/tachometer-fast" + "unicons/tachometer-fast", + "unicons/tachometer-empty" ] diff --git a/public/app/core/reducers/root.ts b/public/app/core/reducers/root.ts index d86b93c916e..b73e12e2f22 100644 --- a/public/app/core/reducers/root.ts +++ b/public/app/core/reducers/root.ts @@ -23,7 +23,6 @@ import { reducer as pluginsReducer } from 'app/features/plugins/admin/state/redu import userReducers from 'app/features/profile/state/reducers'; import serviceAccountsReducer from 'app/features/serviceaccounts/state/reducers'; import supportBundlesReducer from 'app/features/support-bundles/state/reducers'; -import teamsReducers from 'app/features/teams/state/reducers'; import usersReducers from 'app/features/users/state/reducers'; import templatingReducers from 'app/features/variables/state/keyedVariablesReducer'; @@ -33,7 +32,6 @@ import { cleanUpAction } from '../actions/cleanUp'; const rootReducers = { ...sharedReducers, ...alertingReducers, - ...teamsReducers, ...dashboardReducers, ...exploreReducers, ...dataSourcesReducers, diff --git a/public/app/core/services/echo/init.ts b/public/app/core/services/echo/init.ts index d4ff585b700..5e49e72422a 100644 --- a/public/app/core/services/echo/init.ts +++ b/public/app/core/services/echo/init.ts @@ -146,7 +146,19 @@ async function initRudderstackBackend() { return; } - const modulePromise = config.featureToggles.rudderstackUpgrade + // this will need to be updated when rudderstackSdkV3Url is added + // Desired logic: if only one of the sdk urls is provided, use respective code + // otherwise defer to the feature toggle. + const fakeConfigRudderstackSdkV3Url: string | undefined = undefined; + + const hasOldSdkUrl = Boolean(config.rudderstackSdkUrl); + const hasNewSdkUrl = Boolean(fakeConfigRudderstackSdkV3Url); + const onlyOneConfigURLSet = hasOldSdkUrl !== hasNewSdkUrl; + const useNewRudderstack = onlyOneConfigURLSet ? hasNewSdkUrl : config.featureToggles.rudderstackUpgrade; + + const configUrl = useNewRudderstack ? fakeConfigRudderstackSdkV3Url : config.rudderstackSdkUrl; + + const modulePromise = useNewRudderstack ? import('./backends/analytics/RudderstackV3Backend') : import('./backends/analytics/RudderstackBackend'); @@ -157,7 +169,7 @@ async function initRudderstackBackend() { dataPlaneUrl: config.rudderstackDataPlaneUrl, user: contextSrv.user, sdkUrl: config.rudderstackSdkUrl, - configUrl: config.rudderstackConfigUrl, + configUrl: configUrl, integrationsUrl: config.rudderstackIntegrationsUrl, buildInfo: config.buildInfo, }) diff --git a/public/app/core/utils/navBarItem-translations.ts b/public/app/core/utils/navBarItem-translations.ts index 0ac5619e893..0fab359de4e 100644 --- a/public/app/core/utils/navBarItem-translations.ts +++ b/public/app/core/utils/navBarItem-translations.ts @@ -1,5 +1,4 @@ import { t } from '@grafana/i18n'; -import { config } from '@grafana/runtime'; // Maps the ID of the nav item to a translated phrase to later pass to // Because the navigation content is dynamic (defined in the backend), we can not use // the normal inline message definition method. @@ -49,9 +48,7 @@ export function getNavTitle(navId: string | undefined) { case 'dashboards/recently-deleted': return t('nav.recently-deleted.title', 'Recently deleted'); case 'dashboards/new': - return config.featureToggles.dashboardTemplates - ? t('nav.new-dashboard.empty-title', 'Empty dashboard') - : t('nav.new-dashboard.title', 'New dashboard'); + return t('nav.new-dashboard.title', 'New dashboard'); case 'dashboards/folder/new': return t('nav.new-folder.title', 'New folder'); case 'dashboards/import': diff --git a/public/app/features/alerting/unified/CLAUDE.md b/public/app/features/alerting/unified/CLAUDE.md index 6fc487dd46d..124b9da622f 100644 --- a/public/app/features/alerting/unified/CLAUDE.md +++ b/public/app/features/alerting/unified/CLAUDE.md @@ -417,6 +417,60 @@ Check https://testing-library.com/docs/queries/about/ for what selectors to pref - [ ] Async operations use `await` and `findBy*` - [ ] Permissions tested with `grantUserPermissions` +## Using GitHub CLI for Context + +When working on issues, PRs, or needing repository context, use the GitHub CLI (`gh`) to fetch information directly: + +### Common Commands + +```bash +# View issue details +gh issue view + +# View PR details and diff +gh pr view +gh pr diff + +# List recent issues +gh issue list --limit 10 + +# List PRs with specific labels +gh pr list --label "alerting" + +# Search issues +gh issue list --search "keyword" + +# View PR reviews and comments +gh pr view --comments + +# Check CI status +gh pr checks + +# View repository info +gh repo view +``` + +### When to Use + +- **Understanding issue context**: Fetch issue descriptions, comments, and linked PRs +- **Reviewing PR changes**: Get diffs, review comments, and CI status +- **Finding related work**: Search for similar issues or existing implementations +- **Checking project status**: List open issues/PRs for the alerting team + +### Example Workflow + +```bash +# Working on issue #12345 +gh issue view 12345 + +# Check if there's an existing PR +gh pr list --search "fixes #12345" + +# Review a related PR +gh pr view 67890 +gh pr diff 67890 +``` + ## Getting Help - Check patterns in existing `components/` code @@ -425,6 +479,7 @@ Check https://testing-library.com/docs/queries/about/ for what selectors to pref - See `mocks.ts` for data factories - Read [./TESTING.md](./TESTING.md) for testing details - Review Grafana style guides (linked at top) +- Use `gh` CLI to fetch issue/PR context from GitHub --- diff --git a/public/app/features/alerting/unified/api/prometheusApi.ts b/public/app/features/alerting/unified/api/prometheusApi.ts index 3c4fe219dd0..12fa3aae223 100644 --- a/public/app/features/alerting/unified/api/prometheusApi.ts +++ b/public/app/features/alerting/unified/api/prometheusApi.ts @@ -47,6 +47,7 @@ export type GrafanaPromRulesOptions = Omit ({ url: `api/prometheus/grafana/api/v1/rules`, params: { @@ -120,6 +122,7 @@ export const prometheusApi = alertingApi.injectEndpoints({ 'search.rule_name': title, 'search.rule_group': searchGroupName, dashboard_uid: dashboardUid, + rule_matcher: ruleMatchers, }, }), providesTags: (_result, _error, { folderUid, groupName, ruleName }) => { diff --git a/public/app/features/alerting/unified/components/assistant/AnalizeRuleButton.tsx b/public/app/features/alerting/unified/components/assistant/AnalizeRuleButton.tsx index 6438ceb70de..2736a2e4f0f 100644 --- a/public/app/features/alerting/unified/components/assistant/AnalizeRuleButton.tsx +++ b/public/app/features/alerting/unified/components/assistant/AnalizeRuleButton.tsx @@ -59,7 +59,7 @@ function AnalyzeRuleButtonView({ }); openAssistant({ - origin: 'alerting', + origin: 'alerting/analyze-rule-menu-item', mode: 'assistant', prompt: analyzeRulePrompt, context: [alertContext], @@ -99,7 +99,7 @@ function buildAnalyzeAlertingRulePrompt(rule: GrafanaAlertingRule): string { const state = rule.state || 'firing'; const timeInfo = rule.activeAt ? ` starting at ${new Date(rule.activeAt).toISOString()}` : ''; const alertsNavigationPrompt = config.featureToggles.alertingTriage - ? '\n- Include navigation to follow up on the alerts page' + ? '\n- Include navigation to the alerts page ONLY if the alert is firing or pending' : ''; let prompt = ` diff --git a/public/app/features/alerting/unified/components/import-to-gma/ImportToGMARules.tsx b/public/app/features/alerting/unified/components/import-to-gma/ImportToGMARules.tsx index d88d446642d..98451409af5 100644 --- a/public/app/features/alerting/unified/components/import-to-gma/ImportToGMARules.tsx +++ b/public/app/features/alerting/unified/components/import-to-gma/ImportToGMARules.tsx @@ -21,8 +21,8 @@ import { Stack, Text, } from '@grafana/ui'; -import { NestedFolderPicker } from 'app/core/components/NestedFolderPicker/NestedFolderPicker'; import { DataSourcePicker } from 'app/features/datasources/components/picker/DataSourcePicker'; +import { ProvisioningAwareFolderPicker } from 'app/features/provisioning/components/Shared/ProvisioningAwareFolderPicker'; import { Folder } from '../../types/rule-form'; import { @@ -409,9 +409,10 @@ function TargetFolderField() { name="targetFolder" render={({ field: { onChange, ref, ...field } }) => ( - (null); const isGrafanaAlertManager = alertmanager === GRAFANA_RULES_SOURCE_NAME; + // Check if user has permission to test templates + const canTestTemplates = + contextSrv.hasPermission(AccessControlAction.AlertingNotificationsTemplatesTest) || + contextSrv.hasPermission(AccessControlAction.AlertingNotificationsWrite); + + // Only show preview and payload panels if both conditions are met: + // 1. It's a Grafana Alertmanager + // 2. User has the test permission + const showPreviewAndPayload = isGrafanaAlertManager && canTestTemplates; + const error = updateTemplateError ?? createTemplateError; const [cheatsheetOpened, toggleCheatsheetOpened] = useToggle(false); @@ -118,16 +130,16 @@ export const TemplateForm = ({ originalTemplate, prefill, alertmanager }: Props) // splitter for template and payload editor const columnSplitter = useSplitter({ direction: 'column', - // if Grafana Alertmanager, split 50/50, otherwise 100/0 because there is no payload editor - initialSize: isGrafanaAlertManager ? 0.5 : 1, + // if showing preview/payload panels, split 50/50, otherwise 100/0 because there is no payload editor + initialSize: showPreviewAndPayload ? 0.5 : 1, dragPosition: 'middle', }); // splitter for template editor and preview const rowSplitter = useSplitter({ direction: 'row', - // if Grafana Alertmanager, split 60/40, otherwise 100/0 because there is no preview - initialSize: isGrafanaAlertManager ? 0.6 : 1, + // if showing preview/payload panels, split 60/40, otherwise 100/0 because there is no preview + initialSize: showPreviewAndPayload ? 0.6 : 1, dragPosition: 'middle', }); @@ -319,8 +331,8 @@ export const TemplateForm = ({ originalTemplate, prefill, alertmanager }: Props) - {/* payload editor – only available for Grafana Alertmanager */} - {isGrafanaAlertManager && ( + {/* payload editor – only shown if user has test permission */} + {showPreviewAndPayload && ( <>
@@ -345,8 +357,8 @@ export const TemplateForm = ({ originalTemplate, prefill, alertmanager }: Props) )}
- {/* preview column – full height and half-width */} - {isGrafanaAlertManager && ( + {/* preview column – only shown if user has test permission */} + {showPreviewAndPayload && (
{ * This is used to access the settings and secure fields for the integration in a type-safe way. */ integrationPrefix: `items.${number}`; + canEditProtectedFields: boolean; readOnly?: boolean; - customValidators?: Record['customValidator']>; } @@ -44,6 +44,7 @@ export function ChannelOptions({ integrationPrefix, readOnly = false, customValidators = {}, + canEditProtectedFields, }: Props): JSX.Element { const { watch } = useFormContext>(); @@ -54,7 +55,7 @@ export function ChannelOptions({ const getOptionMeta = (option: NotificationChannelOption): OptionMeta => ({ required: determineRequired(option, settings, secureFields), - readOnly: determineReadOnly(option, settings, secureFields), + readOnly: determineReadOnly(option, settings, secureFields, canEditProtectedFields), }); return ( @@ -78,6 +79,7 @@ export function ChannelOptions({ label={option.label} description={option.description} htmlFor={`${settingsPath}${option.propertyName}`} + noMargin > ({ ); } - const error: FieldError | DeepMap | undefined = ( - (option.secure ? errors?.secureFields : errors?.settings) as DeepMap | undefined - )?.[option.secureFieldKey ?? option.propertyName]; + const errorSource = option.secure ? errors?.secureFields : errors?.settings; + const propertyKey = option.secureFieldKey ?? option.propertyName; + const error = // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + (errorSource as Record, FieldError>> | undefined)?.[ + propertyKey + ]; const defaultValue = defaultValues?.settings?.[option.propertyName]; @@ -140,8 +145,14 @@ const determineRequired = ( const determineReadOnly = ( option: NotificationChannelOption, settings: Record, - secureFields: NotificationChannelSecureFields + secureFields: NotificationChannelSecureFields, + canEditProtectedFields: boolean ) => { + if (option.protected && !canEditProtectedFields) { + return true; + } + + // Handle fields with dependencies (e.g., field B depends on field A being set) if (!option.dependsOn) { return false; } diff --git a/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.test.tsx b/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.test.tsx index 4fda03e9d53..00a933acec3 100644 --- a/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.test.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.test.tsx @@ -89,6 +89,7 @@ describe('ChannelSubForm', () => { commonSettingsComponent={GrafanaCommonChannelSettings} isEditable={true} isTestable={false} + canEditProtectedFields={true} /> diff --git a/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx b/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx index 645c6565a01..c49b5184623 100644 --- a/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/ChannelSubForm.tsx @@ -35,6 +35,7 @@ interface Props { onDelete?: () => void; isEditable?: boolean; isTestable?: boolean; + canEditProtectedFields: boolean; customValidators?: React.ComponentProps['customValidators']; } @@ -52,6 +53,7 @@ export function ChannelSubForm({ commonSettingsComponent: CommonSettingsComponent, isEditable = true, isTestable, + canEditProtectedFields, customValidators = {}, }: Props): JSX.Element { const styles = useStyles2(getStyles); @@ -210,6 +212,7 @@ export function ChannelSubForm({ label={t('alerting.channel-sub-form.label-integration', 'Integration')} htmlFor={contactPointTypeInputId} data-testid={`${pathPrefix}type`} + noMargin > ({ onDeleteSubform={onDeleteSubform} integrationPrefix={channelFieldPath} readOnly={!isEditable} + canEditProtectedFields={canEditProtectedFields} customValidators={customValidators} /> {!!(mandatoryOptions.length && optionalOptions.length) && ( @@ -301,6 +305,7 @@ export function ChannelSubForm({ errors={errors} integrationPrefix={channelFieldPath} readOnly={!isEditable} + canEditProtectedFields={canEditProtectedFields} customValidators={customValidators} /> diff --git a/public/app/features/alerting/unified/components/receivers/form/CloudReceiverForm.tsx b/public/app/features/alerting/unified/components/receivers/form/CloudReceiverForm.tsx index 6512dcf86b3..ea490821452 100644 --- a/public/app/features/alerting/unified/components/receivers/form/CloudReceiverForm.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/CloudReceiverForm.tsx @@ -91,6 +91,7 @@ export const CloudReceiverForm = ({ contactPoint, alertManagerSourceName, readOn alertManagerSourceName={alertManagerSourceName} defaultItem={defaultChannelValues} commonSettingsComponent={CloudCommonChannelSettings} + canEditProtectedFields={true} /> ); diff --git a/public/app/features/alerting/unified/components/receivers/form/GrafanaReceiverForm.tsx b/public/app/features/alerting/unified/components/receivers/form/GrafanaReceiverForm.tsx index de17ab6c7c0..df68ab185dc 100644 --- a/public/app/features/alerting/unified/components/receivers/form/GrafanaReceiverForm.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/GrafanaReceiverForm.tsx @@ -9,7 +9,7 @@ import { } from 'app/features/alerting/unified/components/contact-points/useContactPoints'; import { showManageContactPointPermissions } from 'app/features/alerting/unified/components/contact-points/utils'; import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource'; -import { canEditEntity } from 'app/features/alerting/unified/utils/k8s/utils'; +import { canEditEntity, canModifyProtectedEntity } from 'app/features/alerting/unified/utils/k8s/utils'; import { GrafanaManagedContactPoint, GrafanaManagedReceiverConfig, @@ -124,8 +124,10 @@ export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode } // If there is no contact point it means we're creating a new one, so scoped permissions doesn't exist yet const hasScopedEditPermissions = contactPoint ? canEditEntity(contactPoint) : true; + const hasScopedEditProtectedPermissions = contactPoint ? canModifyProtectedEntity(contactPoint) : true; const isEditable = !readOnly && hasScopedEditPermissions && !contactPoint?.provisioned; const isTestable = !readOnly; + const canEditProtectedFields = editMode ? hasScopedEditProtectedPermissions : true; if (isLoadingNotifiers || isLoadingOnCallIntegration) { return ( @@ -178,6 +180,7 @@ export const GrafanaReceiverForm = ({ contactPoint, readOnly = false, editMode } canManagePermissions={ editMode && contactPoint && showManageContactPointPermissions(GRAFANA_RULES_SOURCE_NAME, contactPoint) } + canEditProtectedFields={canEditProtectedFields} /> {testReceivers && ( { showDefaultRouteWarning?: boolean; contactPointId?: string; canManagePermissions?: boolean; + canEditProtectedFields: boolean; } export function ReceiverForm({ @@ -58,6 +59,7 @@ export function ReceiverForm({ showDefaultRouteWarning, contactPointId, canManagePermissions, + canEditProtectedFields, }: Props) { const notifyApp = useAppNotification(); const styles = useStyles2(getStyles); @@ -66,15 +68,16 @@ export function ReceiverForm({ // normalize deprecated and new config values const normalizedConfig = normalizeFormValues(initialValues); - const defaultValues = normalizedConfig ?? { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + const defaultValues = (normalizedConfig ?? { name: '', items: [ { ...defaultItem, __id: String(Math.random()), - } as any, + }, ], - }; + }) as ReceiverFormValues; const formAPI = useForm>({ // making a copy here beacuse react-hook-form will mutate these, and break if the object is frozen. for real. @@ -148,6 +151,7 @@ export function ReceiverForm({ invalid={!!errors.name} error={errors.name && errors.name.message} required + noMargin > ({ onDelete={() => remove(index)} pathPrefix={pathPrefix} notifiers={notifiers} - errors={errors?.items?.[index] as FieldErrors} + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + errors={errors?.items?.[index] as FieldErrors | undefined} commonSettingsComponent={commonSettingsComponent} isEditable={isEditable} isTestable={isTestable} + canEditProtectedFields={canEditProtectedFields} customValidators={customValidators ? customValidators[field.type] : undefined} /> ); diff --git a/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.test.tsx b/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.test.tsx new file mode 100644 index 00000000000..c52b4bfeca5 --- /dev/null +++ b/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.test.tsx @@ -0,0 +1,448 @@ +import userEvent from '@testing-library/user-event'; +import { FormProvider, useForm } from 'react-hook-form'; +import { render, screen, waitFor } from 'test/test-utils'; + +import { + NotificationChannelOption, + NotificationChannelSecureFields, + OptionMeta, +} from 'app/features/alerting/unified/types/alerting'; + +import { OptionField } from './OptionField'; + +const TestWrapper = ({ children }: { children: React.ReactNode }) => { + const methods = useForm(); + return {children}; +}; + +const renderOptionField = ( + option: NotificationChannelOption, + props: { + getOptionMeta?: (option: NotificationChannelOption) => OptionMeta; + readOnly?: boolean; + secureFields?: NotificationChannelSecureFields; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + defaultValue?: any; + } = {} +) => { + const defaultProps = { + option, + defaultValue: '', + pathPrefix: 'test.', + secureFields: {}, + ...props, + }; + + return render( + + + + ); +}; + +describe('OptionField', () => { + describe('Protected field indicator', () => { + it('should display lock icon with tooltip when field is protected and readOnly', async () => { + const option: NotificationChannelOption = { + propertyName: 'testField', + label: 'Test Field', + description: 'A test field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }; + + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + renderOptionField(option, { getOptionMeta }); + + // Check that lock icon is displayed + const lockIcon = screen.getByTestId('lock-icon'); + expect(lockIcon).toBeInTheDocument(); + + // Hover over the icon to show tooltip + await userEvent.hover(lockIcon); + + // Check that tooltip appears with correct text + await waitFor(() => { + expect( + screen.getByText('This field is protected and can only be edited by users with elevated permissions') + ).toBeInTheDocument(); + }); + }); + + it('should NOT display lock icon when field is protected but NOT readOnly', () => { + const option: NotificationChannelOption = { + propertyName: 'testField', + label: 'Test Field', + description: 'A test field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }; + + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: false, required: false }); + + renderOptionField(option, { getOptionMeta }); + + // Lock icon should not be displayed + expect(screen.queryByTestId('lock-icon')).not.toBeInTheDocument(); + }); + + it('should NOT display lock icon when field is NOT protected', () => { + const option: NotificationChannelOption = { + propertyName: 'testField', + label: 'Test Field', + description: 'A test field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + }; + + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + renderOptionField(option, { getOptionMeta }); + + // Lock icon should not be displayed + expect(screen.queryByTestId('lock-icon')).not.toBeInTheDocument(); + }); + + it('should NOT display lock icon when getOptionMeta is not provided', () => { + const option: NotificationChannelOption = { + propertyName: 'testField', + label: 'Test Field', + description: 'A test field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }; + + renderOptionField(option); + + // Lock icon should not be displayed + expect(screen.queryByTestId('lock-icon')).not.toBeInTheDocument(); + }); + + it('should display lock icon for checkbox fields when protected and readOnly', () => { + const option: NotificationChannelOption = { + propertyName: 'testCheckbox', + label: 'Test Checkbox', + description: 'A test checkbox', + element: 'checkbox', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }; + + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + renderOptionField(option, { getOptionMeta }); + + // Lock icon should be displayed even for checkbox + const lockIcon = screen.getByTestId('lock-icon'); + expect(lockIcon).toBeInTheDocument(); + }); + + it('should display lock icon for select fields when protected and readOnly', () => { + const option: NotificationChannelOption = { + propertyName: 'testSelect', + label: 'Test Select', + description: 'A test select', + element: 'select', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + selectOptions: [ + { label: 'Option 1', value: 'opt1' }, + { label: 'Option 2', value: 'opt2' }, + ], + }; + + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + renderOptionField(option, { getOptionMeta }); + + // Lock icon should be displayed + const lockIcon = screen.getByTestId('lock-icon'); + expect(lockIcon).toBeInTheDocument(); + }); + }); + + describe('Subform fields', () => { + it('should pass getOptionMeta to SubformField component', () => { + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + const option: NotificationChannelOption = { + propertyName: 'testSubform', + label: 'Test Subform', + description: 'A test subform', + element: 'subform', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + subformOptions: [ + { + propertyName: 'nestedField', + label: 'Nested Field', + description: 'A nested field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }, + ], + }; + + renderOptionField(option, { getOptionMeta, defaultValue: { nestedField: 'test' } }); + + // The subform should be rendered with the nested field + expect(screen.getByText('Test Subform')).toBeInTheDocument(); + + // Verify that getOptionMeta was called for the nested field + // This ensures it was passed through to the SubformField component + expect(getOptionMeta).toHaveBeenCalled(); + }); + + it('should display lock icon for protected fields inside subform when readOnly', async () => { + const getOptionMeta = jest.fn((opt) => { + // Make the nested protected field readOnly + if (opt.protected) { + return { readOnly: true, required: false }; + } + return { readOnly: false, required: false }; + }); + + const option: NotificationChannelOption = { + propertyName: 'oauth2', + label: 'OAuth2 Configuration', + description: 'OAuth2 settings', + element: 'subform', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + subformOptions: [ + { + propertyName: 'token_url', + label: 'Token URL', + description: 'OAuth2 token URL', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }, + ], + }; + + renderOptionField(option, { getOptionMeta, defaultValue: { token_url: 'https://example.com/token' } }); + + // Check that lock icon is displayed for the nested protected field + const lockIcon = screen.getByTestId('lock-icon'); + expect(lockIcon).toBeInTheDocument(); + + // Hover over the icon to show tooltip + await userEvent.hover(lockIcon); + + // Check that tooltip appears + await waitFor(() => { + expect( + screen.getByText('This field is protected and can only be edited by users with elevated permissions') + ).toBeInTheDocument(); + }); + }); + + it('should NOT display lock icon for protected fields inside subform when user can edit', () => { + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: false, required: false }); + + const option: NotificationChannelOption = { + propertyName: 'oauth2', + label: 'OAuth2 Configuration', + description: 'OAuth2 settings', + element: 'subform', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + subformOptions: [ + { + propertyName: 'token_url', + label: 'Token URL', + description: 'OAuth2 token URL', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }, + ], + }; + + renderOptionField(option, { getOptionMeta, defaultValue: { token_url: 'https://example.com/token' } }); + + // Lock icon should not be displayed when user has permission + expect(screen.queryByTestId('lock-icon')).not.toBeInTheDocument(); + }); + }); + + describe('Subform array fields', () => { + it('should pass getOptionMeta to SubformArrayField component', () => { + const getOptionMeta = jest.fn().mockReturnValue({ readOnly: true, required: false }); + + const option: NotificationChannelOption = { + propertyName: 'testSubformArray', + label: 'Test Subform Array', + description: 'A test subform array', + element: 'subform_array', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + subformOptions: [ + { + propertyName: 'nestedField', + label: 'Nested Field', + description: 'A nested field', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }, + ], + }; + + renderOptionField(option, { getOptionMeta, defaultValue: [{ nestedField: 'test' }] }); + + // The subform array should be rendered + expect(screen.getByText('Test Subform Array (1)')).toBeInTheDocument(); + + // Verify that getOptionMeta was called + expect(getOptionMeta).toHaveBeenCalled(); + }); + + it('should display lock icon for protected fields inside subform array when readOnly', async () => { + const getOptionMeta = jest.fn((opt) => { + if (opt.protected) { + return { readOnly: true, required: false }; + } + return { readOnly: false, required: false }; + }); + + const option: NotificationChannelOption = { + propertyName: 'headers', + label: 'HTTP Headers', + description: 'Custom headers', + element: 'subform_array', + inputType: '', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: false, + dependsOn: '', + subformOptions: [ + { + propertyName: 'authorization', + label: 'Authorization Header', + description: 'Auth header value', + element: 'input', + inputType: 'text', + placeholder: '', + required: false, + secure: false, + showWhen: { field: '', is: '' }, + validationRule: '', + protected: true, + dependsOn: '', + }, + ], + }; + + renderOptionField(option, { getOptionMeta, defaultValue: [{ authorization: 'Bearer token' }] }); + + // Check that lock icon is displayed for the nested protected field + const lockIcon = screen.getByTestId('lock-icon'); + expect(lockIcon).toBeInTheDocument(); + + // Hover over the icon to show tooltip + await userEvent.hover(lockIcon); + + // Check that tooltip appears + await waitFor(() => { + expect( + screen.getByText('This field is protected and can only be edited by users with elevated permissions') + ).toBeInTheDocument(); + }); + }); + }); +}); diff --git a/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.tsx b/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.tsx index d965fafb40d..f037a127b64 100644 --- a/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/fields/OptionField.tsx @@ -3,15 +3,19 @@ import { FC } from 'react'; import { Controller, DeepMap, FieldError, useFormContext } from 'react-hook-form'; import { GrafanaTheme2 } from '@grafana/data'; +import { t } from '@grafana/i18n'; import { Checkbox, Field, + Icon, Input, RadioButtonList, SecretInput, SecretTextArea, Select, + Stack, TextArea, + Tooltip, useStyles2, } from '@grafana/ui'; import { @@ -64,6 +68,7 @@ export const OptionField: FC = ({ errors={error} pathPrefix={pathPrefix} onDelete={onDeleteSubform} + getOptionMeta={getOptionMeta} /> ); } @@ -76,13 +81,34 @@ export const OptionField: FC = ({ option={option} pathPrefix={pathPrefix} errors={error as Array> | undefined} + getOptionMeta={getOptionMeta} /> ); } + const shouldShowProtectedIndicator = option.protected && getOptionMeta?.(option).readOnly; + + const labelText = option.element !== 'checkbox' && option.element !== 'radio' ? option.label : undefined; + + const label = shouldShowProtectedIndicator ? ( + + + + + {labelText} + + ) : ( + labelText + ); + return ( (
- ['onClick']; href?: React.ComponentProps['href']; + enableFiltering?: boolean; + alertState?: InstanceStateFilter; } -function ShowMoreInstances({ stats, onClick, href }: ShowMoreInstancesProps) { +function ShowMoreInstances({ stats, onClick, href, enableFiltering, alertState }: ShowMoreInstancesProps) { const styles = useStyles2(getStyles); const { visibleItemsCount, totalItemsCount } = stats; return (
- - Showing {{ visibleItemsCount }} out of {{ totalItemsCount }} instances - + {enableFiltering && alertState ? ( + + Showing {{ visibleItemsCount }} {{ alertState }} out of {{ totalItemsCount }} instances + + ) : ( + + Showing {{ visibleItemsCount }} out of {{ totalItemsCount }} instances + + )}
- - Show all {{ totalItemsCount }} alert instances - + {enableFiltering ? ( + Show all + ) : ( + + Show all {{ totalItemsCount }} alert instances + + )}
); @@ -128,6 +146,8 @@ export function RuleDetailsMatchingInstances(props: Props) { stats={stats} onClick={enableFiltering ? resetFilter : undefined} href={!enableFiltering ? ruleViewPageLink : undefined} + enableFiltering={enableFiltering} + alertState={alertState} /> ) : undefined; diff --git a/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.test.ts b/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.test.ts index 12a46a87bdd..ab9404d4e52 100644 --- a/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.test.ts +++ b/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.test.ts @@ -1,9 +1,12 @@ import { testWithFeatureToggles } from 'test/test-utils'; +import { config } from '@grafana/runtime'; import { PromAlertingRuleState, PromRuleGroupDTO, PromRuleType } from 'app/types/unified-alerting-dto'; import { mockGrafanaPromAlertingRule, mockPromRecordingRule } from '../../mocks'; import { RuleHealth } from '../../search/rulesSearchParser'; +import { pluginMeta, pluginMetaToPluginConfig } from '../../testSetup/plugins'; +import { SupportedPlugin } from '../../types/pluginBridges'; import { Annotation } from '../../utils/constants'; import { getDatasourceAPIUid } from '../../utils/datasource'; import { getFilter } from '../../utils/search'; @@ -416,19 +419,40 @@ describe('grafana-managed rules', () => { expect(frontendFilter.groupMatches(group)).toBe(true); }); + it('should include ruleMatchers in backend filter when labels are provided', () => { + const { backendFilter } = getGrafanaFilter(getFilter({ labels: ['severity=critical'] })); + + expect(backendFilter.ruleMatchers).toBeDefined(); + expect(backendFilter.ruleMatchers).toHaveLength(1); + expect(backendFilter.ruleMatchers).toEqual([ + '{"name":"severity","value":"critical","isRegex":false,"isEqual":true}', + ]); + }); + it('should still apply other frontend filters', () => { - const rule = mockGrafanaPromAlertingRule({ + // Set up test plugin as installed + config.apps[SupportedPlugin.Slo] = pluginMetaToPluginConfig(pluginMeta[SupportedPlugin.Slo]); + + const regularRule = mockGrafanaPromAlertingRule({ name: 'High CPU Usage', labels: { severity: 'critical', team: 'ops' }, alerts: [], }); - // Label filter should still work on frontend - const { frontendFilter } = getGrafanaFilter(getFilter({ labels: ['severity=warning'] })); - expect(frontendFilter.ruleMatches(rule)).toBe(false); + const pluginRule = mockGrafanaPromAlertingRule({ + name: 'Plugin Rule', + labels: { __grafana_origin: `plugin/${SupportedPlugin.Slo}` }, + alerts: [], + }); - const { frontendFilter: frontendFilter2 } = getGrafanaFilter(getFilter({ labels: ['severity=critical'] })); - expect(frontendFilter2.ruleMatches(rule)).toBe(true); + // Plugins filter should still work on frontend + const { frontendFilter } = getGrafanaFilter(getFilter({ plugins: 'hide' })); + + // Non-plugin rules should pass through + expect(frontendFilter.ruleMatches(regularRule)).toBe(true); + + // Plugin-provided rules should be filtered out + expect(frontendFilter.ruleMatches(pluginRule)).toBe(false); }); }); @@ -681,20 +705,7 @@ describe('grafana-managed rules', () => { expect(frontendFilter.groupMatches(group)).toBe(true); }); - it('should still apply always-frontend filters (labels, namespace)', () => { - const rule = mockGrafanaPromAlertingRule({ - name: 'High CPU Usage', - labels: { severity: 'critical' }, - alerts: [], - }); - - // Labels filter should still work - const { frontendFilter: labelFilter } = getGrafanaFilter(getFilter({ labels: ['severity=warning'] })); - expect(labelFilter.ruleMatches(rule)).toBe(false); - - const { frontendFilter: labelFilter2 } = getGrafanaFilter(getFilter({ labels: ['severity=critical'] })); - expect(labelFilter2.ruleMatches(rule)).toBe(true); - + it('should still apply always-frontend filters (namespace)', () => { // Namespace filter should still work const group: PromRuleGroupDTO = { name: 'Test Group', @@ -791,9 +802,13 @@ describe('grafana-managed rules', () => { expect(hasGrafanaClientSideFilters(getFilter({ dataSourceNames: ['prometheus'] }))).toBe(false); }); + it('should return false for labels (handled by backend when feature toggle is enabled)', () => { + expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(false); + }); + it('should return true for client-side only filters', () => { expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(true); - expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(true); + expect(hasGrafanaClientSideFilters(getFilter({ plugins: 'hide' }))).toBe(true); }); it('should return false for backend-only filters (state, health, contactPoint)', () => { @@ -816,12 +831,13 @@ describe('grafana-managed rules', () => { expect(hasGrafanaClientSideFilters(getFilter({ ruleHealth: RuleHealth.Ok }))).toBe(false); expect(hasGrafanaClientSideFilters(getFilter({ contactPoint: 'my-contact-point' }))).toBe(false); - // Should return true for: frontend-handled filters + // Should return true for: frontend-handled filters (labels, namespace, plugins) expect(hasGrafanaClientSideFilters(getFilter({ freeFormWords: ['cpu'] }))).toBe(true); expect(hasGrafanaClientSideFilters(getFilter({ ruleName: 'alert' }))).toBe(true); expect(hasGrafanaClientSideFilters(getFilter({ groupName: 'test-group' }))).toBe(true); expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(true); expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(true); + expect(hasGrafanaClientSideFilters(getFilter({ plugins: 'hide' }))).toBe(true); }); }); @@ -840,12 +856,13 @@ describe('grafana-managed rules', () => { expect(hasGrafanaClientSideFilters(getFilter({ ruleHealth: RuleHealth.Ok }))).toBe(false); expect(hasGrafanaClientSideFilters(getFilter({ contactPoint: 'my-contact-point' }))).toBe(false); - // Should return true for: always-frontend filters only (namespace, labels) + // Should return true for: always-frontend filters only (namespace, plugins) expect(hasGrafanaClientSideFilters(getFilter({ namespace: 'production' }))).toBe(true); - expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(true); + expect(hasGrafanaClientSideFilters(getFilter({ plugins: 'hide' }))).toBe(true); - // Should return false for: backend-handled dataSourceNames when feature toggles are enabled + // Should return false for: backend-handled filters when both feature toggles are enabled expect(hasGrafanaClientSideFilters(getFilter({ dataSourceNames: ['prometheus'] }))).toBe(false); + expect(hasGrafanaClientSideFilters(getFilter({ labels: ['severity=critical'] }))).toBe(false); }); }); }); diff --git a/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.ts b/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.ts index c0fd9fea4d8..96ee951ee37 100644 --- a/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.ts +++ b/public/app/features/alerting/unified/rule-list/hooks/grafanaFilter.ts @@ -1,8 +1,11 @@ +import { attempt, isError } from 'lodash'; + import { PromRuleDTO, PromRuleGroupDTO } from 'app/types/unified-alerting-dto'; import { GrafanaPromRulesOptions } from '../../api/prometheusApi'; import { shouldUseBackendFilters, shouldUseFullyCompatibleBackendFilters } from '../../featureToggles'; import { RulesFilter } from '../../search/rulesSearchParser'; +import { parseMatcher } from '../../utils/matchers'; import { buildTitleSearch, normalizeFilterState } from './filterNormalization'; import { @@ -75,6 +78,12 @@ export function getGrafanaFilter(filterState: Partial) { hasInvalidDataSourceNames = datasourceUids.length === 0; } + // Convert labels to JSON-encoded matchers for backend filtering + const ruleMatchersBackendFilter: string[] | undefined = + ruleFilterConfig.labels || normalizedFilterState.labels.length === 0 + ? undefined + : labelMatchersToBackendFormat(normalizedFilterState.labels); + const backendFilter: GrafanaPromRulesOptions = { state: normalizedFilterState.ruleState ? [normalizedFilterState.ruleState] : [], health: normalizedFilterState.ruleHealth ? [normalizedFilterState.ruleHealth] : [], @@ -85,6 +94,7 @@ export function getGrafanaFilter(filterState: Partial) { dashboardUid: ruleFilterConfig.dashboardUid ? undefined : normalizedFilterState.dashboardUid, searchGroupName: groupFilterConfig.groupName ? undefined : normalizedFilterState.groupName, datasources: ruleFilterConfig.dataSourceNames ? undefined : datasourceUids, + ruleMatchers: ruleMatchersBackendFilter, }; return { @@ -115,7 +125,7 @@ function buildGrafanaFilterConfigs() { ruleState: null, ruleType: useBackendFilters || useFullyCompatibleBackendFilters ? null : ruleTypeFilter, dataSourceNames: useBackendFilters || useFullyCompatibleBackendFilters ? null : dataSourceNamesFilter, - labels: labelsFilter, + labels: useBackendFilters ? null : labelsFilter, ruleHealth: null, dashboardUid: useBackendFilters || useFullyCompatibleBackendFilters ? null : dashboardUidFilter, plugins: pluginsFilter, @@ -129,3 +139,21 @@ function buildGrafanaFilterConfigs() { return { ruleFilterConfig, groupFilterConfig }; } + +/** + * Converts label matchers to JSON-encoded strings for backend filtering. + * Invalid matchers are logged and filtered out. + */ +function labelMatchersToBackendFormat(labels: string[]): string[] { + return labels.reduce((acc, label) => { + const result = attempt(() => JSON.stringify(parseMatcher(label))); + + if (isError(result)) { + console.warn('Failed to parse label matcher:', label, result); + } else { + acc.push(result); + } + + return acc; + }, []); +} diff --git a/public/app/features/alerting/unified/rule-list/paginationLimits.test.ts b/public/app/features/alerting/unified/rule-list/paginationLimits.test.ts index 2e1db699883..5d6b7c97782 100644 --- a/public/app/features/alerting/unified/rule-list/paginationLimits.test.ts +++ b/public/app/features/alerting/unified/rule-list/paginationLimits.test.ts @@ -74,6 +74,7 @@ describe('paginationLimits', () => { { ruleHealth: RuleHealth.Ok }, { contactPoint: 'slack' }, { dataSourceNames: ['prometheus'] }, + { labels: ['severity=critical'] }, ])( 'should return rule limit for grafana + large limit for datasource when only backend filters are used: %p', (filterState) => { @@ -86,7 +87,6 @@ describe('paginationLimits', () => { it.each>([ { namespace: 'production' }, - { labels: ['severity=critical'] }, { ruleState: PromAlertingRuleState.Firing, namespace: 'production' }, ])('should return large limits for both when frontend filters are used: %p', (filterState) => { const { grafanaManagedLimit, datasourceManagedLimit } = getFilteredRulesLimits(getFilter(filterState)); @@ -157,6 +157,7 @@ describe('paginationLimits', () => { { ruleHealth: RuleHealth.Ok }, { contactPoint: 'slack' }, { dataSourceNames: ['prometheus'] }, + { labels: ['severity=critical'] }, ])( 'should return rule limit for grafana + large limit for datasource when only backend filters are used: %p', (filterState) => { @@ -167,7 +168,7 @@ describe('paginationLimits', () => { } ); - it.each>([{ namespace: 'production' }, { labels: ['severity=critical'] }])( + it.each>([{ namespace: 'production' }])( 'should return large limits for both when frontend filters are used: %p', (filterState) => { const { grafanaManagedLimit, datasourceManagedLimit } = getFilteredRulesLimits(getFilter(filterState)); diff --git a/public/app/features/alerting/unified/triage/scene/TriageScene.tsx b/public/app/features/alerting/unified/triage/scene/TriageScene.tsx index d5c7c96d71b..598af13c43d 100644 --- a/public/app/features/alerting/unified/triage/scene/TriageScene.tsx +++ b/public/app/features/alerting/unified/triage/scene/TriageScene.tsx @@ -58,6 +58,8 @@ export const triageScene = new EmbeddedSceneWithContext({ baseFilters: [], layout: 'combobox', expressionBuilder: prometheusExpressionBuilder, + // Filter out __name__ from options as this is the metric name not a filterable label + tagKeyRegexFilter: /^(?!__name__$).*/, }), ], }), diff --git a/public/app/features/alerting/unified/triage/scene/dataTransform.ts b/public/app/features/alerting/unified/triage/scene/dataTransform.ts index d8677cad946..303742bbf93 100644 --- a/public/app/features/alerting/unified/triage/scene/dataTransform.ts +++ b/public/app/features/alerting/unified/triage/scene/dataTransform.ts @@ -33,7 +33,7 @@ export function convertToWorkbenchRows(series: DataFrame[], groupBy: string[] = const ruleUIDIndex = fieldIndex.get('grafana_rule_uid'); // These should always exist due to validation above, but handle gracefully - if (!alertnameIndex || !folderIndex || !ruleUIDIndex) { + if (alertnameIndex === undefined || folderIndex === undefined || ruleUIDIndex === undefined) { return []; } diff --git a/public/app/features/alerting/unified/triage/scene/expressionBuilder.ts b/public/app/features/alerting/unified/triage/scene/expressionBuilder.ts index ff3d01f73e4..18360552379 100644 --- a/public/app/features/alerting/unified/triage/scene/expressionBuilder.ts +++ b/public/app/features/alerting/unified/triage/scene/expressionBuilder.ts @@ -4,9 +4,12 @@ import { AdHocFilterWithLabels } from '@grafana/scenes'; * Custom expression builder for Prometheus that properly handles regex operators. * Unlike the default builder, this doesn't escape regex metacharacters when using =~ or !~ * operators, allowing users to enter raw regex patterns. + * + * Note: __name__ is excluded from filters as it represents the metric name itself, + * not a label, and should be handled separately in query construction. */ export function prometheusExpressionBuilder(filters: AdHocFilterWithLabels[]): string { - const applicableFilters = filters.filter((f) => !f.nonApplicable && !f.hidden); + const applicableFilters = filters.filter((f) => !f.nonApplicable && !f.hidden && f.key !== '__name__'); return applicableFilters.map(renderFilter).join(','); } diff --git a/public/app/features/alerting/unified/types/alerting.ts b/public/app/features/alerting/unified/types/alerting.ts index f8dcdd8c111..c6fe667982a 100644 --- a/public/app/features/alerting/unified/types/alerting.ts +++ b/public/app/features/alerting/unified/types/alerting.ts @@ -149,6 +149,12 @@ export interface NotificationChannelOption { required: boolean; secure: boolean; secureFieldKey?: string; + /** + * protected indicates that only administrators or users with + * "alert.notifications.receivers.protected:write" permission + * are allowed to update this field + * */ + protected?: boolean; selectOptions?: Array> | null; defaultValue?: SelectableValue; showWhen: { field: string; is: string | boolean }; diff --git a/public/app/features/alerting/unified/utils/k8s/constants.ts b/public/app/features/alerting/unified/utils/k8s/constants.ts index 1eb3c371d59..cf297261733 100644 --- a/public/app/features/alerting/unified/utils/k8s/constants.ts +++ b/public/app/features/alerting/unified/utils/k8s/constants.ts @@ -21,6 +21,8 @@ export enum K8sAnnotations { AccessAdmin = 'grafana.com/access/canAdmin', /** Annotation key that indicates that the calling user is able to delete this entity */ AccessDelete = 'grafana.com/access/canDelete', + /** Annotation key that indicates that the calling user is able to modify protected fields of this entity */ + AccessModifyProtected = 'grafana.com/access/canModifyProtected', } /** diff --git a/public/app/features/alerting/unified/utils/k8s/utils.ts b/public/app/features/alerting/unified/utils/k8s/utils.ts index 8aecb9dd46b..48ec5685a69 100644 --- a/public/app/features/alerting/unified/utils/k8s/utils.ts +++ b/public/app/features/alerting/unified/utils/k8s/utils.ts @@ -42,6 +42,9 @@ export const canAdminEntity = (k8sEntity: EntityToCheck) => export const canDeleteEntity = (k8sEntity: EntityToCheck) => getAnnotation(k8sEntity, K8sAnnotations.AccessDelete) === 'true'; +export const canModifyProtectedEntity = (k8sEntity: EntityToCheck) => + getAnnotation(k8sEntity, K8sAnnotations.AccessModifyProtected) === 'true'; + /** * Escape \ and = characters for field selectors. * The Kubernetes API Machinery will decode those automatically. diff --git a/public/app/features/browse-dashboards/BrowseDashboardsPage.tsx b/public/app/features/browse-dashboards/BrowseDashboardsPage.tsx index 921c67ba9cb..e177fcf9fa2 100644 --- a/public/app/features/browse-dashboards/BrowseDashboardsPage.tsx +++ b/public/app/features/browse-dashboards/BrowseDashboardsPage.tsx @@ -27,6 +27,7 @@ import { BrowseFilters } from './components/BrowseFilters'; import { BrowseView } from './components/BrowseView'; import CreateNewButton from './components/CreateNewButton'; import { FolderActionsButton } from './components/FolderActionsButton'; +import { RecentlyViewedDashboards } from './components/RecentlyViewedDashboards'; import { SearchView } from './components/SearchView'; import { getFolderPermissions } from './permissions'; import { useHasSelection } from './state/hooks'; @@ -178,6 +179,8 @@ const BrowseDashboardsPage = memo(({ queryParams }: { queryParams: Record + {/* only show recently viewed dashboards when in root */} + {!folderUID && }
{ + if (!evaluateBooleanFlag('recentlyViewedDashboards', false)) { + return []; + } + return getRecentlyViewedDashboards(MAX_RECENT); + }, []); + + if (!evaluateBooleanFlag('recentlyViewedDashboards', false)) { + return null; + } + + return ( + + Recently viewed + + } + isOpen={true} + className={styles.title} + contentClassName={styles.content} + > + {/* placeholder */} + {loading && } + {/* TODO: Better empty state https://github.com/grafana/grafana/issues/114804 */} + {!loading && recentDashboards.length === 0 && ( + {t('browse-dashboards.recently-viewed.empty', 'Nothing viewed yet')} + )} + + {/* TODO: implement actual card content */} + {!loading && recentDashboards.length > 0 && ( + <> + {recentDashboards.map((dash) => ( +
+ {dash.name} +
+ ))} + + )} +
+ ); +} + +const getStyles = (theme: GrafanaTheme2) => { + const accent = theme.visualization.getColorByName('purple'); // or your own hex + + return { + title: css({ + background: `linear-gradient(90deg, ${accent} 0%, #e478eaff 100%)`, + WebkitTextFillColor: 'transparent', + backgroundClip: 'text', + color: 'transparent', + '& button svg': { + color: accent, + }, + }), + content: css({ + paddingTop: theme.spacing(0), + }), + }; +}; diff --git a/public/app/features/browse-dashboards/components/utils.ts b/public/app/features/browse-dashboards/components/utils.ts index a6c97e4788f..e1a3d5b5a02 100644 --- a/public/app/features/browse-dashboards/components/utils.ts +++ b/public/app/features/browse-dashboards/components/utils.ts @@ -1,6 +1,9 @@ import { config } from '@grafana/runtime'; import { contextSrv } from 'app/core/services/context_srv'; +import impressionSrv from 'app/core/services/impression_srv'; import { ResourceRef } from 'app/features/provisioning/components/BulkActions/useBulkActionJob'; +import { getGrafanaSearcher } from 'app/features/search/service/searcher'; +import { DashboardQueryResult } from 'app/features/search/service/types'; import { DashboardTreeSelection, DashboardViewItemWithUIItems, BrowseDashboardsPermissions } from '../types'; @@ -60,3 +63,36 @@ export function canSelectItems(permissions: BrowseDashboardsPermissions) { const canSelectDashboards = canEditDashboards || canDeleteDashboards; return Boolean(canSelectFolders || canSelectDashboards); } + +/** + * Returns dashboard search results ordered the same way the user opened them. + */ +export async function getRecentlyViewedDashboards(maxItems = 5): Promise { + try { + const recentlyOpened = (await impressionSrv.getDashboardOpened()).slice(0, maxItems); + if (!recentlyOpened.length) { + return []; + } + + const searchResults = await getGrafanaSearcher().search({ + kind: ['dashboard'], + limit: recentlyOpened.length, + uid: recentlyOpened, + }); + + const dashboards = searchResults.view.toArray(); + // Keep dashboards in the same order the user opened them. + // When a UID is missing from the search response + // push it to the end instead of letting indexOf return -1 + const order = (uid: string) => { + const idx = recentlyOpened.indexOf(uid); + return idx === -1 ? recentlyOpened.length : idx; + }; + + dashboards.sort((a, b) => order(a.uid) - order(b.uid)); + return dashboards; + } catch (error) { + console.error('Failed to load recently viewed dashboards', error); + return []; + } +} diff --git a/public/app/features/browse-dashboards/types.ts b/public/app/features/browse-dashboards/types.ts index 960cd9713da..44f87d4a07a 100644 --- a/public/app/features/browse-dashboards/types.ts +++ b/public/app/features/browse-dashboards/types.ts @@ -44,6 +44,7 @@ export interface DashboardsTreeItem { - const orderA = recentUids.indexOf(resultA.uid); - const orderB = recentUids.indexOf(resultB.uid); - return orderA - orderB; - }); + const recentResults = await getRecentlyViewedDashboards(MAX_RECENT_DASHBOARDS); const recentDashboardActions: CommandPaletteAction[] = recentResults.map((item) => { const { url, name } = item; // items are backed by DataFrameView, so must hold the url in a closure diff --git a/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneRenderer.tsx b/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneRenderer.tsx index 80ec361476a..7ce42744241 100644 --- a/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneRenderer.tsx +++ b/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneRenderer.tsx @@ -76,12 +76,12 @@ export function DashboardEditPaneRenderer({ editPane, dashboard, isDocked }: Pro data-testid={selectors.pages.Dashboard.Sidebar.optionsButton} active={selectedObject === dashboard ? true : false} /> - dashboard.openV2SchemaEditor()} - /> + /> */} )} diff --git a/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneSplitter.tsx b/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneSplitter.tsx index 091e4805bae..735edd1767f 100644 --- a/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneSplitter.tsx +++ b/public/app/features/dashboard-scene/edit-pane/DashboardEditPaneSplitter.tsx @@ -1,14 +1,15 @@ import { css, cx } from '@emotion/css'; -import React, { useEffect } from 'react'; +import React, { useEffect, useLayoutEffect } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { config, useChromeHeaderHeight } from '@grafana/runtime'; import { useSceneObjectState } from '@grafana/scenes'; import { ElementSelectionContext, useSidebar, useStyles2, Sidebar } from '@grafana/ui'; -import { AppChromeUpdate } from 'app/core/components/AppChrome/AppChromeUpdate'; import NativeScrollbar, { DivScrollElement } from 'app/core/components/NativeScrollbar'; +import { useGrafana } from 'app/core/context/GrafanaContext'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; +import { KioskMode } from 'app/types/dashboard'; import { DashboardScene } from '../scene/DashboardScene'; import { NavToolbarActions } from '../scene/NavToolbarActions'; @@ -29,10 +30,9 @@ export function DashboardEditPaneSplitter({ dashboard, isEditing, body, controls const headerHeight = useChromeHeaderHeight(); const { editPane } = dashboard.state; const styles = useStyles2(getStyles, headerHeight ?? 0); - const hasUid = Boolean(dashboard.state.uid); - const canStar = Boolean(dashboard.state.meta.canStar); - - //const [isCollapsed, setIsCollapsed] = useEditPaneCollapsed(); + const { chrome } = useGrafana(); + const { kioskMode } = chrome.useState(); + const isInKioskMode = kioskMode === KioskMode.Full; if (!config.featureToggles.dashboardNewLayouts) { return ( @@ -46,6 +46,11 @@ export function DashboardEditPaneSplitter({ dashboard, isEditing, body, controls ); } + /** + * Adds star button and left side actions to app chrome breadcrumb area + */ + useUpdateAppChromeActions(dashboard); + /** * Enable / disable selection based on dashboard isEditing state */ @@ -59,12 +64,6 @@ export function DashboardEditPaneSplitter({ dashboard, isEditing, body, controls const { selectionContext, openPane } = useSceneObjectState(editPane, { shouldActivateOrKeepAlive: true }); - const onBodyRef = (ref: HTMLDivElement | null) => { - if (ref) { - dashboard.onSetScrollRef(new DivScrollElement(ref)); - } - }; - const sidebarContext = useSidebar({ hasOpenPane: Boolean(openPane), contentMargin: 1, @@ -88,39 +87,77 @@ export function DashboardEditPaneSplitter({ dashboard, isEditing, body, controls editPane.clearSelection(); }; + const onBodyRef = (ref: HTMLDivElement | null) => { + if (ref) { + dashboard.onSetScrollRef(new DivScrollElement(ref)); + } + }; + + function renderBody() { + // In kiosk mode the full document body scrolls so we don't need to wrap in our own scrollbar + if (isInKioskMode) { + return ( +
+ {body} +
+ ); + } + + return ( +
+
+ {body} +
+ + + + +
+ ); + } + return (
- - {hasUid && canStar && } - {hasUid && canStar && } - {renderDynamicNavActions()} - - } - /> -
+
{controls}
-
-
- {body} -
- - - -
+ {renderBody()}
); } +function useUpdateAppChromeActions(dashboard: DashboardScene) { + const { chrome } = useGrafana(); + + useLayoutEffect(() => { + const hasUid = Boolean(dashboard.state.uid); + const canStar = Boolean(dashboard.state.meta.canStar); + + const breadcrumbActions = ( + <> + {hasUid && canStar && } + {hasUid && canStar && } + {renderDynamicNavActions()} + + ); + + chrome.update({ breadcrumbActions }); + + return () => { + chrome.update({ breadcrumbActions: undefined }); + }; + }, [chrome, dashboard]); +} + function renderDynamicNavActions() { const dashboard = getDashboardSrv().getCurrent()!; const showProps = { dashboard }; @@ -152,13 +189,17 @@ function getStyles(theme: GrafanaTheme2, headerHeight: number) { bodyWrapper: css({ label: 'body-wrapper', display: 'flex', - flexDirection: 'row', + flexDirection: 'column', flexGrow: 1, position: 'relative', flex: '1 1 0', overflow: 'hidden', }), - bodyWithToolbar: css({ + bodyWrapperKiosk: css({ + padding: theme.spacing(0, 2, 2, 2), + overflow: 'unset', + }), + scrollContainer: css({ display: 'flex', flexDirection: 'column', flexGrow: 1, @@ -191,11 +232,6 @@ function getStyles(theme: GrafanaTheme2, headerHeight: number) { // Because the edit pane splitter handle area adds padding we can reduce it here paddingRight: theme.spacing(1), }), - editPane: css({ - flexDirection: 'column', - // borderLeft: `1px solid ${theme.colors.border.weak}`, - // background: theme.colors.background.primary, - }), controlsWrapperSticky: css({ [theme.breakpoints.up('md')]: { position: 'sticky', diff --git a/public/app/features/dashboard-scene/edit-pane/DashboardEditableElement.tsx b/public/app/features/dashboard-scene/edit-pane/DashboardEditableElement.tsx index c68696e439d..e7ef490960d 100644 --- a/public/app/features/dashboard-scene/edit-pane/DashboardEditableElement.tsx +++ b/public/app/features/dashboard-scene/edit-pane/DashboardEditableElement.tsx @@ -59,9 +59,9 @@ export class DashboardEditableElement implements EditableDashboardElement { }; } - public getOutlineChildren(): SceneObject[] { + public getOutlineChildren(isEditing: boolean): SceneObject[] { const { $variables, body } = this.dashboard.state; - return [$variables!, ...body.getOutlineChildren()]; + return isEditing ? [$variables!, ...body.getOutlineChildren()] : body.getOutlineChildren(); } public useEditPaneOptions = useEditPaneOptions.bind(this, this.dashboard); diff --git a/public/app/features/dashboard-scene/edit-pane/DashboardOutline.tsx b/public/app/features/dashboard-scene/edit-pane/DashboardOutline.tsx index de80db73254..10bb180a4b1 100644 --- a/public/app/features/dashboard-scene/edit-pane/DashboardOutline.tsx +++ b/public/app/features/dashboard-scene/edit-pane/DashboardOutline.tsx @@ -51,11 +51,16 @@ function DashboardOutlineNode({ sceneObject, editPane, isEditing, depth, index } const noTitleText = t('dashboard.outline.tree-item.no-title', ''); - const children = editableElement.getOutlineChildren?.() ?? []; const elementInfo = editableElement.getEditableElementInfo(); const instanceName = elementInfo.instanceName === '' ? noTitleText : elementInfo.instanceName; const outlineRename = useOutlineRename(editableElement, isEditing); const isContainer = editableElement.getOutlineChildren ? true : false; + const visibleChildren = useMemo(() => { + const children = editableElement.getOutlineChildren?.(isEditing) ?? []; + return isEditing + ? children + : children.filter((child) => !getEditableElementFor(child)?.getEditableElementInfo().isHidden); + }, [editableElement, isEditing]); const onNodeClicked = (e: React.MouseEvent) => { e.stopPropagation(); @@ -74,6 +79,10 @@ function DashboardOutlineNode({ sceneObject, editPane, isEditing, depth, index } setIsCollapsed(!isCollapsed); }; + if (elementInfo.isHidden && !isEditing) { + return null; + } + return ( // todo: add proper keyboard navigation // eslint-disable-next-line jsx-a11y/click-events-have-key-events @@ -130,8 +139,8 @@ function DashboardOutlineNode({ sceneObject, editPane, isEditing, depth, index } {isContainer && !isCollapsed && (
    - {children.length > 0 ? ( - children.map((child, i) => ( + {visibleChildren.length > 0 ? ( + visibleChildren.map((child, i) => ( ({ - description: t('dashboard.variable.hide.action', 'Change variable hide option'), - prop: 'hide', - }), + changeVariableHideValue({ source, oldValue, newValue }: EditActionProps) { + const variableSet = source.parent; + const variablesBeforeChange = + variableSet instanceof SceneVariableSet ? [...(variableSet.state.variables ?? [])] : undefined; + + dashboardEditActions.edit({ + description: t('dashboard.variable.hide.action', 'Change variable hide option'), + source, + perform: () => { + source.setState({ hide: newValue }); + // Updating the variables set since components that show/hide variables subscribe to the variable set, not the individual variables. + if (variableSet instanceof SceneVariableSet) { + variableSet.setState({ variables: [...(variableSet.state.variables ?? [])] }); + } + }, + undo: () => { + source.setState({ hide: oldValue }); + if (variableSet instanceof SceneVariableSet && variablesBeforeChange) { + variableSet.setState({ variables: variablesBeforeChange }); + } + }, + }); + }, moveElement(props: MoveElementActionHelperProps) { const { movedObject, source, perform, undo } = props; diff --git a/public/app/features/dashboard-scene/inspect/InspectJsonTab.test.tsx b/public/app/features/dashboard-scene/inspect/InspectJsonTab.test.tsx index 9b1d53a6cd9..36337a6ddef 100644 --- a/public/app/features/dashboard-scene/inspect/InspectJsonTab.test.tsx +++ b/public/app/features/dashboard-scene/inspect/InspectJsonTab.test.tsx @@ -190,7 +190,7 @@ describe('InspectJsonTab', () => { expect(obj.kind).toEqual('Panel'); expect(obj.spec.id).toEqual(12); expect(obj.spec.data.kind).toEqual('QueryGroup'); - expect(tab.isEditable()).toBe(false); + expect(tab.isEditable()).toBe(true); }); }); diff --git a/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx b/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx index 6085174b9af..648f6de57ef 100644 --- a/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx +++ b/public/app/features/dashboard-scene/inspect/InspectJsonTab.tsx @@ -17,7 +17,7 @@ import { VizPanel, } from '@grafana/scenes'; import { LibraryPanel } from '@grafana/schema/'; -import { Button, CodeEditor, Field, Select, useStyles2 } from '@grafana/ui'; +import { Alert, Button, CodeEditor, Field, Select, useStyles2 } from '@grafana/ui'; import { isDashboardV2Spec } from 'app/features/dashboard/api/utils'; import { getPanelDataFrames } from 'app/features/dashboard/components/HelpWizard/utils'; import { PanelModel } from 'app/features/dashboard/state/PanelModel'; @@ -27,6 +27,7 @@ import { getPrettyJSON } from 'app/features/inspector/utils/utils'; import { reportPanelInspectInteraction } from 'app/features/search/page/reporting'; import { DashboardGridItem } from '../scene/layout-default/DashboardGridItem'; +import { buildVizPanel } from '../serialization/layoutSerializers/utils'; import { buildGridItemForPanel } from '../serialization/transformSaveModelToScene'; import { gridItemToPanel, vizPanelToPanel } from '../serialization/transformSceneToSaveModel'; import { vizPanelToSchemaV2 } from '../serialization/transformSceneToSaveModelSchemaV2'; @@ -37,6 +38,7 @@ import { getQueryRunnerFor, isLibraryPanel, } from '../utils/utils'; +import { isPanelKindV2 } from '../v2schema/validation'; export type ShowContent = 'panel-json' | 'panel-data' | 'data-frames'; @@ -45,6 +47,7 @@ export interface InspectJsonTabState extends SceneObjectState { source: ShowContent; jsonText: string; onClose: () => void; + error?: string; } export class InspectJsonTab extends SceneObjectBase { @@ -102,38 +105,77 @@ export class InspectJsonTab extends SceneObjectBase { } public onChangeSource = (value: SelectableValue) => { - this.setState({ source: value.value!, jsonText: getJsonText(value.value!, this.state.panelRef.resolve()) }); + this.setState({ + source: value.value!, + jsonText: getJsonText(value.value!, this.state.panelRef.resolve()), + error: undefined, + }); }; public onApplyChange = () => { const panel = this.state.panelRef.resolve(); const dashboard = getDashboardSceneFor(panel); - const jsonObj = JSON.parse(this.state.jsonText); - - const panelModel = new PanelModel(jsonObj); - const gridItem = buildGridItemForPanel(panelModel); - const newState = sceneUtils.cloneSceneObjectState(gridItem.state); - - if (!(panel.parent instanceof DashboardGridItem)) { - console.error('Cannot update state of panel', panel, gridItem); + let jsonObj: unknown; + try { + jsonObj = JSON.parse(this.state.jsonText); + } catch (e) { + this.setState({ + error: t('dashboard-scene.inspect-json-tab.error-invalid-json', 'Invalid JSON'), + }); return; } - this.state.onClose(); + if (isDashboardV2Spec(dashboard.getSaveModel())) { + if (!isPanelKindV2(jsonObj)) { + this.setState({ + error: t( + 'dashboard-scene.inspect-json-tab.error-invalid-v2-panel', + 'Panel JSON did not pass validation. Please check the JSON and try again.' + ), + }); + return; + } + const vizPanel = buildVizPanel(jsonObj, jsonObj.spec.id); - if (!dashboard.state.isEditing) { - dashboard.onEnterEditMode(); + if (!dashboard.state.isEditing) { + dashboard.onEnterEditMode(); + } + + reportPanelInspectInteraction(InspectTab.JSON, 'apply', { + panel_type_changed: panel.state.pluginId !== jsonObj.spec.vizConfig.group, + panel_id_changed: getPanelIdForVizPanel(panel) !== jsonObj.spec.id, + panel_grid_pos_changed: false, // Grid cant be edited from inspect in v2 panels. + panel_targets_changed: hasQueriesChanged(getQueryRunnerFor(panel), getQueryRunnerFor(vizPanel.state.$data)), + }); + + panel.setState(vizPanel.state); + this.state.onClose(); + } else { + const panelModel = new PanelModel(jsonObj); + const gridItem = buildGridItemForPanel(panelModel); + const newState = sceneUtils.cloneSceneObjectState(gridItem.state); + + if (!(panel.parent instanceof DashboardGridItem)) { + console.error('Cannot update state of panel', panel, gridItem); + return; + } + + this.state.onClose(); + + if (!dashboard.state.isEditing) { + dashboard.onEnterEditMode(); + } + + panel.parent.setState(newState); + + //Report relevant updates + reportPanelInspectInteraction(InspectTab.JSON, 'apply', { + panel_type_changed: panel.state.pluginId !== panelModel.type, + panel_id_changed: getPanelIdForVizPanel(panel) !== panelModel.id, + panel_grid_pos_changed: hasGridPosChanged(panel.parent.state, newState), + panel_targets_changed: hasQueriesChanged(getQueryRunnerFor(panel), getQueryRunnerFor(newState.$data)), + }); } - - panel.parent.setState(newState); - - //Report relevant updates - reportPanelInspectInteraction(InspectTab.JSON, 'apply', { - panel_type_changed: panel.state.pluginId !== panelModel.type, - panel_id_changed: getPanelIdForVizPanel(panel) !== panelModel.id, - panel_grid_pos_changed: hasGridPosChanged(panel.parent.state, newState), - panel_targets_changed: hasQueriesChanged(getQueryRunnerFor(panel), getQueryRunnerFor(newState.$data)), - }); }; public onCodeEditorBlur = (value: string) => { @@ -152,11 +194,6 @@ export class InspectJsonTab extends SceneObjectBase { return false; } - // V2 dashboard panels are not editable from the inspect - if (isDashboardV2Spec(getDashboardSceneFor(panel).getSaveModel())) { - return false; - } - // Only support normal grid items for now and not repeated items if (panel.parent instanceof DashboardGridItem && panel.parent.isRepeated()) { return false; @@ -170,14 +207,14 @@ export class InspectJsonTab extends SceneObjectBase { } function InspectJsonTabComponent({ model }: SceneComponentProps) { - const { source: show, jsonText } = model.useState(); + const { source: show, jsonText, error } = model.useState(); const styles = useStyles2(getPanelInspectorStyles2); const options = model.getOptions(); return (
    - + void; @@ -67,17 +63,3 @@ export function CustomVariableEditor({ variable, onRunQuery }: CustomVariableEdi /> ); } - -export function getCustomVariableOptions(variable: SceneVariable): OptionsPaneItemDescriptor[] { - if (!(variable instanceof CustomVariable)) { - return []; - } - - return [ - new OptionsPaneItemDescriptor({ - title: t('dashboard.edit-pane.variable.custom-options.values', 'Values separated by comma'), - id: 'custom-variable-values', - render: ({ props }) => , - }), - ]; -} diff --git a/public/app/features/dashboard-scene/settings/variables/editors/CustomVariableEditor/getCustomVariableOptions.tsx b/public/app/features/dashboard-scene/settings/variables/editors/CustomVariableEditor/getCustomVariableOptions.tsx index 5033ebb1407..7dea9f83ec3 100644 --- a/public/app/features/dashboard-scene/settings/variables/editors/CustomVariableEditor/getCustomVariableOptions.tsx +++ b/public/app/features/dashboard-scene/settings/variables/editors/CustomVariableEditor/getCustomVariableOptions.tsx @@ -1,4 +1,3 @@ -import { t } from '@grafana/i18n'; import { CustomVariable, SceneVariable } from '@grafana/scenes'; import { OptionsPaneItemDescriptor } from '../../../../../dashboard/components/PanelEditor/OptionsPaneItemDescriptor'; @@ -12,7 +11,6 @@ export function getCustomVariableOptions(variable: SceneVariable): OptionsPaneIt return [ new OptionsPaneItemDescriptor({ - title: t('dashboard.edit-pane.variable.custom-options.values', 'Values separated by comma'), id: 'custom-variable-values', render: ({ props }) => , }), diff --git a/public/app/features/dashboard-scene/utils/tracking.test.ts b/public/app/features/dashboard-scene/utils/tracking.test.ts index 45bee1f4583..5fb968a4148 100644 --- a/public/app/features/dashboard-scene/utils/tracking.test.ts +++ b/public/app/features/dashboard-scene/utils/tracking.test.ts @@ -16,6 +16,11 @@ jest.mock('@grafana/runtime', () => ({ dashboardNewLayouts: true, }, }, + getDataSourceSrv: () => ({ + getInstanceSettings: () => { + return { apiVersion: 'v1', meta: { multiValueFilterOperators: true } }; + }, + }), })); // mock useSaveDashboardMutation @@ -72,7 +77,7 @@ describe('dashboard tracking', () => { isScene: true, tabCount: 4, rowCount: 2, - templateVariableCount: 2, + templateVariableCount: 4, maxNestingLevel: 3, panel_type_timeseries_count: 6, panels_count: 6, @@ -89,6 +94,22 @@ describe('dashboard tracking', () => { uid: 'dashboard-test', variable_type_custom_count: 1, variable_type_query_count: 1, + variable_type_datasource_count: 1, + variable_type_adhoc_count: 1, + varsWithDataSource: [ + { + datasource: 'cloudwatch', + type: 'query', + }, + { + datasource: 'opensearch', + type: 'adhoc', + }, + { + datasource: 'bigquery', + type: 'datasource', + }, + ], hasEditPermissions: true, hasSavePermissions: true, }); diff --git a/public/app/features/dashboard-scene/v2schema/validation.test.ts b/public/app/features/dashboard-scene/v2schema/validation.test.ts new file mode 100644 index 00000000000..6afb42eeb94 --- /dev/null +++ b/public/app/features/dashboard-scene/v2schema/validation.test.ts @@ -0,0 +1,60 @@ +import { + defaultPanelKind, + defaultQueryGroupKind, + defaultPanelQueryKind, + defaultVizConfigKind, +} from '@grafana/schema/dist/esm/schema/dashboard/v2'; + +import { isPanelKindV2 } from './validation'; + +describe('v2schema validation', () => { + it('isPanelKindV2 returns true for a minimal valid PanelKind', () => { + const panel = defaultPanelKind(); + // Ensure minimal required properties exist (defaults should be fine) + panel.spec.vizConfig = defaultVizConfigKind(); + panel.spec.data = defaultQueryGroupKind(); + + expect(isPanelKindV2(panel)).toBe(true); + }); + + it('returns false when kind is not "Panel"', () => { + const panel = defaultPanelKind(); + // @ts-expect-error intentional invalid kind for test + panel.kind = 'NotAPanel'; + expect(isPanelKindV2(panel)).toBe(false); + }); + + it('returns false when data kind is wrong', () => { + const panel = defaultPanelKind(); + // @ts-expect-error intentional invalid kind for test + panel.spec.data = { kind: 'Wrong', spec: {} }; + expect(isPanelKindV2(panel)).toBe(false); + }); + + it('returns false when queries contain invalid entries', () => { + const panel = defaultPanelKind(); + panel.spec.data = defaultQueryGroupKind(); + // @ts-expect-error push an invalid query shape + panel.spec.data.spec.queries = [{}]; + expect(isPanelKindV2(panel)).toBe(false); + + // Ensure a valid query shape passes + panel.spec.data.spec.queries = [defaultPanelQueryKind()]; + expect(isPanelKindV2(panel)).toBe(true); + }); + + it('returns false when vizConfig.group is not a string', () => { + const panel = defaultPanelKind(); + panel.spec.vizConfig = defaultVizConfigKind(); + // @ts-expect-error force wrong type + panel.spec.vizConfig.group = 42; + expect(isPanelKindV2(panel)).toBe(false); + }); + + it('returns false when transparent is not a boolean', () => { + const panel = defaultPanelKind(); + // @ts-expect-error wrong type + panel.spec.transparent = 'yes'; + expect(isPanelKindV2(panel)).toBe(false); + }); +}); diff --git a/public/app/features/dashboard-scene/v2schema/validation.ts b/public/app/features/dashboard-scene/v2schema/validation.ts new file mode 100644 index 00000000000..b256f9b1a43 --- /dev/null +++ b/public/app/features/dashboard-scene/v2schema/validation.ts @@ -0,0 +1,137 @@ +import { + PanelKind, + QueryGroupKind, + VizConfigKind, + PanelQueryKind, + TransformationKind, +} from '@grafana/schema/dist/esm/schema/dashboard/v2'; + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isPanelQueryKind(value: unknown): value is PanelQueryKind { + if (!isObject(value)) { + return false; + } + if (value.kind !== 'PanelQuery' || !isObject(value.spec)) { + return false; + } + // Minimal checks for query spec; accept additional properties + if (typeof value.spec.refId !== 'string') { + return false; + } + if (typeof value.spec.hidden !== 'boolean') { + return false; + } + // value.spec.query is an opaque "DataQueryKind" which is { kind: string, spec: Record } + const q = value.spec.query; + if (!isObject(q) || typeof q.kind !== 'string' || !isObject(q.spec)) { + return false; + } + return true; +} + +function isTransformationKind(value: unknown): value is TransformationKind { + if (!isObject(value)) { + return false; + } + if (typeof value.kind !== 'string') { + return false; + } + if (!isObject(value.spec)) { + return false; + } + return true; +} + +function isQueryGroupKind(value: unknown): value is QueryGroupKind { + if (!isObject(value)) { + return false; + } + if (value.kind !== 'QueryGroup' || !isObject(value.spec)) { + return false; + } + const spec = value.spec; + if (!Array.isArray(spec.queries) || !spec.queries.every(isPanelQueryKind)) { + return false; + } + if (!Array.isArray(spec.transformations) || !spec.transformations.every(isTransformationKind)) { + return false; + } + if (!isObject(spec.queryOptions)) { + return false; + } + return true; +} + +function isVizConfigKind(value: unknown): value is VizConfigKind { + if (!isObject(value)) { + return false; + } + if (value.kind !== 'VizConfig') { + return false; + } + if (typeof value.group !== 'string') { + return false; + } + if (typeof value.version !== 'string') { + return false; + } + if (!isObject(value.spec)) { + return false; + } + const spec = value.spec; + if (!isObject(spec.options)) { + return false; + } + if (!isObject(spec.fieldConfig)) { + return false; + } + // Minimal fieldConfig shape (defaults/overrides may be empty) + if (!isObject(spec.fieldConfig)) { + return false; + } + return true; +} + +export function isPanelKindV2(value: unknown): value is PanelKind { + if (!isObject(value)) { + return false; + } + if (value.kind !== 'Panel') { + return false; + } + if (!isObject(value.spec)) { + return false; + } + const spec = value.spec; + if (typeof spec.id !== 'number') { + return false; + } + if (typeof spec.title !== 'string') { + return false; + } + if (typeof spec.description !== 'string') { + return false; + } + if (!Array.isArray(spec.links)) { + return false; + } + if (!isQueryGroupKind(spec.data)) { + return false; + } + if (!isVizConfigKind(spec.vizConfig)) { + return false; + } + if (spec.transparent !== undefined && typeof spec.transparent !== 'boolean') { + return false; + } + return true; +} + +export function validatePanelKindV2(value: unknown): asserts value is PanelKind { + if (!isPanelKindV2(value)) { + throw new Error('Provided JSON is not a valid v2 Panel spec'); + } +} diff --git a/public/app/features/dashboard/api/ResponseTransformers.ts b/public/app/features/dashboard/api/ResponseTransformers.ts index b6fcba03de3..5a536074efe 100644 --- a/public/app/features/dashboard/api/ResponseTransformers.ts +++ b/public/app/features/dashboard/api/ResponseTransformers.ts @@ -528,6 +528,56 @@ export function getPanelQueries(targets: DataQuery[], panelDatasource: DataSourc }); } +/** + * Known Panel properties from the Panel schema (dashboard_kind.cue). + * These should NOT be passed to Angular migration handlers. + * Only "unknown" Angular-specific properties should be passed. + */ +const knownPanelProperties = new Set([ + 'type', + 'id', + 'pluginVersion', + 'targets', + 'title', + 'description', + 'transparent', + 'datasource', + 'gridPos', + 'links', + 'repeat', + 'repeatDirection', + 'maxPerRow', + 'maxDataPoints', + 'transformations', + 'interval', + 'timeFrom', + 'timeShift', + 'hideTimeOverride', + 'timeCompare', + 'libraryPanel', + 'cacheTimeout', + 'queryCachingTTL', + 'options', + 'fieldConfig', + 'autoMigrateFrom', +]); + +/** + * Extracts only the Angular-specific options from a panel, + * filtering out all known Panel schema properties. + * This is used to pass just the Angular options to migration handlers + * (e.g., sparkline, valueName, format for singlestat). + */ +function extractAngularOptions(panel: Panel): Record { + const result: Record = {}; + for (const [key, value] of Object.entries(panel)) { + if (!knownPanelProperties.has(key)) { + result[key] = value; + } + } + return result; +} + export function buildPanelKind(p: Panel): PanelKind { // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/consistent-type-assertions const queries = getPanelQueries((p.targets as any) || [], p.datasource ?? { type: '', uid: '' }); @@ -557,6 +607,23 @@ export function buildPanelKind(p: Panel): PanelKind { fieldConfig.defaults.thresholds.steps[0]!.value = null; } + // Build options with Angular migration data if needed (matches backend behavior) + // autoMigrateFrom is set during v0->v1 migration when Angular panels are converted + const { autoMigrateFrom } = p; + let options = p.options ?? {}; + + // When autoMigrateFrom is present, compose __angularMigration with only Angular-specific options + // This filters out known Panel schema properties, passing only the Angular options to migration handlers + if (autoMigrateFrom) { + options = { + ...options, + __angularMigration: { + autoMigrateFrom, + originalOptions: extractAngularOptions(p), + }, + }; + } + const panelKind: PanelKind = { kind: 'Panel', spec: { @@ -569,7 +636,7 @@ export function buildPanelKind(p: Panel): PanelKind { version: p.pluginVersion ?? '', spec: { fieldConfig: p.fieldConfig || defaultFieldConfigSource(), - options: p.options ?? {}, + options, }, }, links: @@ -1268,6 +1335,16 @@ function colorIdToEnumv1(colorId: FieldColorModeId): FieldColorModeIdV1 { return FieldColorModeIdV1.ContinuousGreens; case 'continuous-purples': return FieldColorModeIdV1.ContinuousPurples; + case 'continuous-viridis': + return FieldColorModeIdV1.ContinuousViridis; + case 'continuous-magma': + return FieldColorModeIdV1.ContinuousMagma; + case 'continuous-plasma': + return FieldColorModeIdV1.ContinuousPlasma; + case 'continuous-inferno': + return FieldColorModeIdV1.ContinuousInferno; + case 'continuous-cividis': + return FieldColorModeIdV1.ContinuousCividis; case 'fixed': return FieldColorModeIdV1.Fixed; case 'shades': diff --git a/public/app/features/dashboard/api/ResponseTransformersToBackend.test.ts b/public/app/features/dashboard/api/ResponseTransformersToBackend.test.ts index 45a310403e4..2ca8d2a2411 100644 --- a/public/app/features/dashboard/api/ResponseTransformersToBackend.test.ts +++ b/public/app/features/dashboard/api/ResponseTransformersToBackend.test.ts @@ -1,12 +1,13 @@ import { readdirSync, readFileSync } from 'fs'; import path from 'path'; -import { mockDataSource } from 'app/features/alerting/unified/mocks'; -import { setupDataSources } from 'app/features/alerting/unified/testSetup/datasources'; +import { Spec as DashboardV2Spec } from '@grafana/schema/dist/esm/schema/dashboard/v2'; import { normalizeBackendOutputForFrontendComparison } from 'app/features/dashboard-scene/serialization/serialization-test-utils'; -import { MIXED_DATASOURCE_NAME } from 'app/plugins/datasource/mixed/MixedDataSource'; +import { transformSaveModelSchemaV2ToScene } from 'app/features/dashboard-scene/serialization/transformSaveModelSchemaV2ToScene'; +import { transformSaveModelToScene } from 'app/features/dashboard-scene/serialization/transformSaveModelToScene'; +import { transformSceneToSaveModelSchemaV2 } from 'app/features/dashboard-scene/serialization/transformSceneToSaveModelSchemaV2'; -import { ensureV2Response } from './ResponseTransformers'; +import { DashboardWithAccessInfo } from './types'; // Mock the config to provide datasource information jest.mock('@grafana/runtime', () => { @@ -14,46 +15,87 @@ jest.mock('@grafana/runtime', () => { ...jest.requireActual('@grafana/runtime').config, defaultDatasource: 'default-ds-uid', datasources: { - 'default-ds-uid': { - meta: { id: 'prometheus' }, - name: 'default-ds-uid', - }, - 'non-default-test-ds-uid': { - meta: { id: 'loki' }, - name: 'non-default-test-ds-uid', + '-- Grafana --': { + type: 'grafana', + uid: '-- Grafana --', + name: 'Grafana', + meta: { id: 'grafana' }, }, 'existing-ref-uid': { + type: 'prometheus', + uid: 'existing-ref-uid', + name: 'Prometheus', meta: { id: 'prometheus' }, - name: 'existing-ref-uid', }, - 'existing-target-uid': { - meta: { id: 'elasticsearch' }, - name: 'existing-target-uid', - }, - 'existing-ref': { - meta: { id: 'prometheus' }, - name: 'existing-ref', - }, - '-- Mixed --': { - meta: { id: 'mixed' }, - name: '-- Mixed --', - }, - 'influx-uid': { + 'influxdb-uid': { + type: 'influxdb', + uid: 'influxdb-uid', + name: 'InfluxDB', meta: { id: 'influxdb' }, - name: 'influx-uid', }, 'cloudwatch-uid': { + type: 'cloudwatch', + uid: 'cloudwatch-uid', + name: 'CloudWatch', meta: { id: 'cloudwatch' }, - name: 'cloudwatch-uid', }, - '-- Grafana --': { - meta: { id: 'grafana' }, - name: '-- Grafana --', + 'elasticsearch-uid': { + type: 'elasticsearch', + uid: 'elasticsearch-uid', + name: 'Elasticsearch', + meta: { id: 'elasticsearch' }, + }, + 'loki-uid': { + type: 'loki', + uid: 'loki-uid', + name: 'Loki', + meta: { id: 'loki' }, + }, + 'default-ds-uid': { + type: 'prometheus', + uid: 'default-ds-uid', + name: 'Default Prometheus', + meta: { id: 'prometheus' }, + }, + 'existing-target-uid': { + type: 'elasticsearch', + uid: 'existing-target-uid', + name: 'Elasticsearch Target', + meta: { id: 'elasticsearch' }, + }, + 'non-default-test-ds-uid': { + type: 'loki', + uid: 'non-default-test-ds-uid', + name: 'Loki Test', + meta: { id: 'loki' }, + }, + '-- Mixed --': { + type: 'mixed', + uid: '-- Mixed --', + name: '-- Mixed --', + meta: { id: 'mixed' }, + }, + 'influx-uid': { + type: 'influxdb', + uid: 'influx-uid', + name: 'InfluxDB Test', + meta: { id: 'influxdb' }, + }, + 'cloudwatch-uid-alt': { + type: 'cloudwatch', + uid: 'cloudwatch-uid', + name: 'CloudWatch Test', + meta: { id: 'cloudwatch' }, + }, + 'existing-ref': { + type: 'prometheus', + uid: 'existing-ref', + name: 'Existing Ref Name', + meta: { id: 'prometheus' }, }, }, - apps: {}, featureToggles: { - dashboardScene: true, + dashboardNewLayouts: true, kubernetesDashboards: true, }, }; @@ -65,79 +107,20 @@ jest.mock('@grafana/runtime', () => { }); /* - * Frontend Conversion Test Design Explanation: + * V1 to V2 Dashboard Transformation Comparison Test (via ResponseTransformers) * - * This test verifies that the frontend ensureV2Response function correctly converts - * dashboard data to v2beta1 format. The test uses input files from the backend test suite - * and compares the frontend conversion results with expected backend conversion results. + * This test compares frontend and backend transformations of dashboard data from v1 to v2 format. + * It uses the same test data as the backend conversion tests and verifies that the frontend + * transformation produces equivalent results to the backend transformation. * - * Note: The frontend ensureV2Response function is designed to convert legacy dashboard - * format to v2 format, while the backend handles Kubernetes resource format conversions. - * This test focuses on verifying the frontend conversion logic works correctly. + * The test follows the same approach as transformSaveModelV1ToV2.test.ts: + * - Frontend path: v1beta1 spec -> Scene -> v2beta1 + * - Backend path: v2beta1 output -> Scene -> v2beta1 (normalized) */ -// Set up the same datasources as backend test provider to ensure consistency -const dataSources = { - default: mockDataSource({ - name: 'default-ds-uid', - uid: 'default-ds-uid', - type: 'prometheus', - isDefault: true, - }), - nonDefault: mockDataSource({ - name: 'Non Default Test Datasource Name', - uid: 'non-default-test-ds-uid', - type: 'loki', - isDefault: false, - }), - existingRef: mockDataSource({ - name: 'Existing Ref Name', - uid: 'existing-ref-uid', - type: 'prometheus', - isDefault: false, - }), - existingTarget: mockDataSource({ - name: 'Existing Target Name', - uid: 'existing-target-uid', - type: 'elasticsearch', - isDefault: false, - }), - existingRefAlt: mockDataSource({ - name: 'Existing Ref Name', - uid: 'existing-ref', - type: 'prometheus', - isDefault: false, - }), - mixed: mockDataSource({ - name: MIXED_DATASOURCE_NAME, - uid: '-- Mixed --', - type: 'mixed', - isDefault: false, - }), - influx: mockDataSource({ - name: 'InfluxDB Test', - uid: 'influx-uid', - type: 'influxdb', - isDefault: false, - }), - cloudwatch: mockDataSource({ - name: 'CloudWatch Test', - uid: 'cloudwatch-uid', - type: 'cloudwatch', - isDefault: false, - }), - grafana: mockDataSource({ - name: '-- Grafana --', - uid: '-- Grafana --', - type: 'grafana', - isDefault: false, - }), -}; - -describe('Backend / Frontend result comparison', () => { +describe('V1 to V2 Dashboard Transformation Comparison (ResponseTransformers)', () => { beforeEach(() => { jest.clearAllMocks(); - setupDataSources(...Object.values(dataSources)); // Mock console methods to avoid test failures from expected warnings jest.spyOn(console, 'error').mockImplementation(() => {}); @@ -182,48 +165,67 @@ describe('Backend / Frontend result comparison', () => { const v1beta1Inputs = jsonInputs.filter((inputFile) => inputFile.startsWith('v1beta1.')); v1beta1Inputs.forEach((inputFile) => { - it(`should convert ${inputFile} spec to match backend conversion`, async () => { + it(`compare ${inputFile} from v1beta1 to v2beta1 backend and frontend conversions`, async () => { const jsonInput = JSON.parse(readFileSync(path.join(inputDir, inputFile), 'utf8')); // Find the corresponding v2beta1 output file const outputFileName = inputFile.replace('.json', `.${LATEST_API_VERSION.split('/')[1]}.json`); const outputFilePath = path.join(outputDir, outputFileName); - // Check if the expected output file exists - try { - const backendOutput = JSON.parse(readFileSync(outputFilePath, 'utf8')); - expect(backendOutput.apiVersion).toBe(LATEST_API_VERSION); + const backendOutput = JSON.parse(readFileSync(outputFilePath, 'utf8')); + expect(backendOutput.apiVersion).toBe(LATEST_API_VERSION); - // Create dashboard models using frontend conversion - // ensureV2Response expects DashboardWithAccessInfo object - const frontendOutput = ensureV2Response({ - ...jsonInput, - kind: 'DashboardWithAccessInfo', - access: {}, - }); + // Backend path: Load backend output into Scene, then serialize back to v2beta1 + // This normalizes the backend output through the same Scene + const sceneBackend = transformSaveModelSchemaV2ToScene({ + spec: backendOutput.spec, + metadata: backendOutput.metadata, + apiVersion: backendOutput.apiVersion, + access: {}, + kind: 'DashboardWithAccessInfo', + } as DashboardWithAccessInfo); + const backendOutputAfterLoadedByScene = transformSceneToSaveModelSchemaV2(sceneBackend, false); - // Verify both outputs have valid spec structures - expect(frontendOutput.spec).toBeDefined(); - expect(backendOutput.spec).toBeDefined(); + // Frontend path: v1beta1 spec -> Scene -> v2beta1 + // Extract the spec from v1beta1 format and use it as the dashboard data + // Remove snapshot field to prevent isSnapshot() from returning true + const dashboardSpec = { ...jsonInput.spec }; + delete dashboardSpec.snapshot; - // Normalize backend output to account for differences in library panel repeat handling - // Backend sets repeat from library panel definition, frontend only sets it when explicit on instance - const inputPanels = jsonInput.spec?.panels || []; - const normalizedBackendSpec = normalizeBackendOutputForFrontendComparison(backendOutput.spec, inputPanels); + // Wrap in DashboardDTO structure that transformSaveModelToScene expects + const scene = transformSaveModelToScene({ + dashboard: dashboardSpec, + meta: { + isNew: false, + isFolder: false, + canSave: true, + canEdit: true, + canDelete: false, + canShare: false, + canStar: false, + canAdmin: false, + isSnapshot: false, + provisioned: false, + version: 1, + }, + }); - // Compare the spec structures - expect(normalizedBackendSpec).toEqual(frontendOutput.spec); + const frontendOutput = transformSceneToSaveModelSchemaV2(scene, false); - // Verify the conversion doesn't throw errors and produces a valid structure - expect(() => JSON.stringify(frontendOutput)).not.toThrow(); - } catch (error) { - if (error instanceof Error && error.message.includes('ENOENT')) { - // Skip test if output file doesn't exist - console.warn(`Skipping test for ${inputFile} - no corresponding v2beta1 output file found`); - return; - } - throw error; - } + // Verify both outputs have valid spec structures + expect(frontendOutput).toBeDefined(); + expect(backendOutputAfterLoadedByScene).toBeDefined(); + + // Normalize backend output to account for differences in library panel repeat handling + // Backend sets repeat from library panel definition, frontend only sets it when explicit on instance + const inputPanels = jsonInput.spec?.panels || []; + const normalizedBackendOutput = normalizeBackendOutputForFrontendComparison( + backendOutputAfterLoadedByScene, + inputPanels + ); + + // Compare the spec structures + expect(normalizedBackendOutput).toEqual(frontendOutput); }); }); }); diff --git a/public/app/features/dashboard/components/RepeatRowSelect/RepeatRowSelect.tsx b/public/app/features/dashboard/components/RepeatRowSelect/RepeatRowSelect.tsx index de68a822e3a..94cbecec75c 100644 --- a/public/app/features/dashboard/components/RepeatRowSelect/RepeatRowSelect.tsx +++ b/public/app/features/dashboard/components/RepeatRowSelect/RepeatRowSelect.tsx @@ -2,7 +2,7 @@ import { useCallback, useMemo } from 'react'; import { SelectableValue } from '@grafana/data'; import { t } from '@grafana/i18n'; -import { SceneObject, sceneGraph } from '@grafana/scenes'; +import { LocalValueVariable, SceneObject, sceneGraph } from '@grafana/scenes'; import { Combobox, ComboboxOption, Select } from '@grafana/ui'; import { useSelector } from 'app/types/store'; @@ -59,10 +59,18 @@ export const RepeatRowSelect2 = ({ sceneContext, repeat, id, onChange }: Props2) const variables = sceneVars.useState().variables; const variableOptions = useMemo(() => { - const options: ComboboxOption[] = variables.map((item) => ({ - label: item.state.name, - value: item.state.name, - })); + const options: ComboboxOption[] = variables + .filter((item) => { + if (sceneContext.parent) { + // filter out local value variables (which are only set on repeated items) + return !(sceneGraph.lookupVariable(item.state.name, sceneContext.parent) instanceof LocalValueVariable); + } + return true; + }) + .map((item) => ({ + label: item.state.name, + value: item.state.name, + })); options.unshift({ label: t('dashboard.repeat-row-select2.variable-options.label.disable-repeating', 'Disable repeating'), @@ -70,7 +78,7 @@ export const RepeatRowSelect2 = ({ sceneContext, repeat, id, onChange }: Props2) }); return options; - }, [variables]); + }, [sceneContext, variables]); const onSelectChange = useCallback((value: ComboboxOption | null) => value && onChange(value.value), [onChange]); @@ -79,7 +87,7 @@ export const RepeatRowSelect2 = ({ sceneContext, repeat, id, onChange }: Props2) return ( } const dashboards = await fetchProvisionedDashboards(ds.type); + + if (dashboards.length > 0) { + DashboardLibraryInteractions.loaded({ + numberOfItems: dashboards.length, + contentKinds: [CONTENT_KINDS.DATASOURCE_DASHBOARD], + datasourceTypes: [ds.type], + sourceEntryPoint: SOURCE_ENTRY_POINTS.DATASOURCE_PAGE, + eventLocation: EVENT_LOCATIONS.EMPTY_DASHBOARD, + }); + } + return dashboards; }, [datasourceUid]); diff --git a/public/app/features/dashboard/dashgrid/PanelStateWrapper.tsx b/public/app/features/dashboard/dashgrid/PanelStateWrapper.tsx index 20c702edd8b..7087c9c611c 100644 --- a/public/app/features/dashboard/dashgrid/PanelStateWrapper.tsx +++ b/public/app/features/dashboard/dashgrid/PanelStateWrapper.tsx @@ -17,6 +17,7 @@ import { PanelData, PanelPlugin, PanelPluginMeta, + PluginContextProvider, SetPanelAttentionEvent, TimeRange, toDataFrameDTO, @@ -524,27 +525,29 @@ export class PanelStateWrapper extends PureComponent { return ( <> - - {this.state.errorMessage === undefined && ( - - )} + + + {this.state.errorMessage === undefined && ( + + )} + ); diff --git a/public/app/features/dashboard/routes.ts b/public/app/features/dashboard/routes.ts index 84e7d514b99..57702d1a35d 100644 --- a/public/app/features/dashboard/routes.ts +++ b/public/app/features/dashboard/routes.ts @@ -24,6 +24,7 @@ export const getPublicDashboardRoutes = (): RouteDescriptor[] => { { path: '/public-dashboards/:accessToken', pageClass: 'page-dashboard', + allowAnonymous: true, routeName: DashboardRoutes.Public, chromeless: true, component: SafeDynamicImport( diff --git a/public/app/features/dashboard/state/DashboardMigratorSingleVersion.test.ts b/public/app/features/dashboard/state/DashboardMigratorSingleVersion.test.ts index 33d9a339e62..f6f2fbe2be6 100644 --- a/public/app/features/dashboard/state/DashboardMigratorSingleVersion.test.ts +++ b/public/app/features/dashboard/state/DashboardMigratorSingleVersion.test.ts @@ -127,7 +127,6 @@ describe('Backend / Frontend single version migration result comparison', () => for (const nestedPanel of panel.panels) { const panelPluginToMigrateTo = getPanelPluginToMigrateTo(nestedPanel); if (panelPluginToMigrateTo) { - // @ts-expect-error - we are using the type from the frontend migration result nestedPanel.autoMigrateFrom = nestedPanel.type; nestedPanel.type = panelPluginToMigrateTo; } diff --git a/public/app/features/dashboard/state/DashboardMigratorToBackend.test.ts b/public/app/features/dashboard/state/DashboardMigratorToBackend.test.ts index 5666fa3710d..dfb980579ab 100644 --- a/public/app/features/dashboard/state/DashboardMigratorToBackend.test.ts +++ b/public/app/features/dashboard/state/DashboardMigratorToBackend.test.ts @@ -94,7 +94,6 @@ describe('Backend / Frontend result comparison', () => { for (const nestedPanel of panel.panels) { const panelPluginToMigrateTo = getPanelPluginToMigrateTo(nestedPanel); if (panelPluginToMigrateTo) { - // @ts-expect-error - we are using the type from the frontend migration result nestedPanel.autoMigrateFrom = nestedPanel.type; nestedPanel.type = panelPluginToMigrateTo; } diff --git a/public/app/features/dashboard/utils/tracking.test.ts b/public/app/features/dashboard/utils/tracking.test.ts index a8e9fb1ec8a..c02ae06d1fc 100644 --- a/public/app/features/dashboard/utils/tracking.test.ts +++ b/public/app/features/dashboard/utils/tracking.test.ts @@ -20,9 +20,9 @@ describe('trackDashboardLoaded', () => { ], templating: { list: [ - { type: 'query', name: 'Query 1' }, + { type: 'query', name: 'Query 1', datasource: { type: 'prometheus' } }, { type: 'interval', name: 'Interval 1' }, - { type: 'query', name: 'Query 2' }, + { type: 'query', name: 'Query 2', datasource: { type: 'cloudwatch' } }, ], }, timepicker: { @@ -52,6 +52,10 @@ describe('trackDashboardLoaded', () => { panel_type_geomap_count: 2, settings_nowdelay: '1m', settings_livenow: true, + varsWithDataSource: [ + { type: 'query', datasource: 'prometheus' }, + { type: 'query', datasource: 'cloudwatch' }, + ], }); }); }); diff --git a/public/app/features/dashboard/utils/tracking.ts b/public/app/features/dashboard/utils/tracking.ts index 3dc32eb05db..cffc7999fff 100644 --- a/public/app/features/dashboard/utils/tracking.ts +++ b/public/app/features/dashboard/utils/tracking.ts @@ -1,5 +1,10 @@ import { VariableModel } from '@grafana/schema/dist/esm/index'; -import { VariableKind } from '@grafana/schema/dist/esm/schema/dashboard/v2'; +import { + AdhocVariableKind, + DatasourceVariableKind, + QueryVariableKind, + VariableKind, +} from '@grafana/schema/dist/esm/schema/dashboard/v2'; import { DashboardInteractions } from 'app/features/dashboard-scene/utils/interactions'; import { DashboardModel } from '../state/DashboardModel'; @@ -41,12 +46,23 @@ export function getPanelPluginCounts(panels: string[]) { } export function getV1SchemaVariables(variableList: VariableModel[]) { - return variableList - .map((v) => v.type) - .reduce((r: Record, k) => { - r[variableName(k)] = 1 + r[variableName(k)] || 1; - return r; - }, {}); + return { + // Count variable types + ...variableList.reduce>((variables, current) => { + variables[variableName(current.type)] = 1 + (variables[variableName(current.type)] || 0); + return variables; + }, {}), + // List of variables with data source types + varsWithDataSource: variableList.reduce>((variablesWithDs, current) => { + if (current.datasource?.type) { + variablesWithDs.push({ + type: current.type, + datasource: current.datasource.type, + }); + } + return variablesWithDs; + }, []), + }; } function mapNewToOldTypes(type: VariableKind['kind']): VariableModel['type'] | undefined { @@ -73,14 +89,34 @@ function mapNewToOldTypes(type: VariableKind['kind']): VariableModel['type'] | u } export function getV2SchemaVariables(variableList: VariableKind[]) { - return variableList - .map((v) => mapNewToOldTypes(v.kind)) - .filter((v) => v !== undefined) - .reduce((r: Record, k) => { - r[variableName(k)] = 1 + r[variableName(k)] || 1; - return r; - }, {}); + return { + // Count variable types + ...variableList.reduce>((variables, current) => { + const type = mapNewToOldTypes(current.kind); + if (type) { + variables[variableName(type)] = 1 + (variables[variableName(type)] || 0); + } + return variables; + }, {}), + // List of variables with data source types + varsWithDataSource: variableList.reduce>((variablesWithDs, current) => { + let datasource = ''; + const type = mapNewToOldTypes(current.kind); + datasource = getDatasourceFromVar(current); + if (datasource && type) { + variablesWithDs.push({ type, datasource }); + } + return variablesWithDs; + }, []), + }; } export const variableName = (type: string) => `variable_type_${type}_count`; const panelName = (type: string) => `panel_type_${type}_count`; + +const isAdhocVar: (v: VariableKind) => v is AdhocVariableKind = (v) => v.kind === 'AdhocVariable'; +const isDatasourceVar: (v: VariableKind) => v is DatasourceVariableKind = (v) => v.kind === 'DatasourceVariable'; +const isQueryVar: (v: VariableKind) => v is QueryVariableKind = (v) => v.kind === 'QueryVariable'; + +const getDatasourceFromVar = (v: VariableKind) => + isAdhocVar(v) ? v.group : isDatasourceVar(v) ? v.spec.pluginId : isQueryVar(v) ? v.spec?.query.group : ''; diff --git a/public/app/features/explore/Logs/Logs.tsx b/public/app/features/explore/Logs/Logs.tsx index 84470d73a61..1ff012f3fee 100644 --- a/public/app/features/explore/Logs/Logs.tsx +++ b/public/app/features/explore/Logs/Logs.tsx @@ -789,7 +789,6 @@ const UnthemedLogs: React.FunctionComponent = (props: Props) => { logOptionsStorageKey={SETTING_KEY_ROOT} timeZone={timeZone} displayedFields={displayedFields} - onPermalinkClick={onPermalinkClick} onClickShowField={showField} onClickHideField={hideField} /> diff --git a/public/app/features/explore/Logs/LogsTableWrap.tsx b/public/app/features/explore/Logs/LogsTableWrap.tsx index ff8cceaadcf..cde546d92ba 100644 --- a/public/app/features/explore/Logs/LogsTableWrap.tsx +++ b/public/app/features/explore/Logs/LogsTableWrap.tsx @@ -19,7 +19,7 @@ import { t } from '@grafana/i18n'; import { reportInteraction } from '@grafana/runtime'; import { getDragStyles, InlineField, Select, useStyles2 } from '@grafana/ui'; import { - getSidebarWidth, + getFieldSelectorWidth, LogsTableFieldSelector, MIN_WIDTH, } from 'app/features/logs/components/fieldSelector/FieldSelector'; @@ -279,7 +279,7 @@ export function LogsTableWrap(props: Props) { // The panel state is updated when the user interacts with the multi-select sidebar }, [currentDataFrame, getColumnsFromProps]); - const [sidebarWidth, setSidebarWidth] = useState(getSidebarWidth(SETTING_KEY_ROOT)); + const [sidebarWidth, setSidebarWidth] = useState(getFieldSelectorWidth(SETTING_KEY_ROOT)); const tableWidth = props.width - sidebarWidth; const styles = useStyles2(getStyles, height, sidebarWidth); diff --git a/public/app/features/explore/utils/supplementaryQueries.ts b/public/app/features/explore/utils/supplementaryQueries.ts index a705c8193fb..45ffe4a5f08 100644 --- a/public/app/features/explore/utils/supplementaryQueries.ts +++ b/public/app/features/explore/utils/supplementaryQueries.ts @@ -129,7 +129,7 @@ export const getSupplementaryQueryProvider = ( dsRequest.requestId = `${dsRequest.requestId || ''}_${i}`; dsRequest.targets = targets; - if (hasSupplementaryQuerySupport(datasource, type)) { + if (hasSupplementaryQuerySupport(datasource, type, dsRequest)) { if (datasource.getDataProvider) { return datasource.getDataProvider(type, dsRequest); } else if (datasource.getSupplementaryRequest) { diff --git a/public/app/features/folders/state/navModel.test.ts b/public/app/features/folders/state/navModel.test.ts new file mode 100644 index 00000000000..de615cabb8c --- /dev/null +++ b/public/app/features/folders/state/navModel.test.ts @@ -0,0 +1,95 @@ +import { config } from '@grafana/runtime'; +import { contextSrv } from 'app/core/services/context_srv'; +import { ManagerKind } from 'app/features/apiserver/types'; +import { AccessControlAction } from 'app/types/accessControl'; +import { FolderDTO } from 'app/types/folders'; + +import { buildNavModel, getAlertingTabID } from './navModel'; + +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + config: { + unifiedAlertingEnabled: true, + }, +})); + +jest.mock('app/core/services/context_srv', () => ({ + contextSrv: { + hasPermission: jest.fn(), + }, +})); + +describe('buildNavModel', () => { + const mockFolder: FolderDTO = { + uid: 'test-folder-uid', + title: 'Test Folder', + url: '/dashboards/f/test-folder-uid', + id: 1, + created: '', + createdBy: '', + hasAcl: false, + updated: '', + updatedBy: '', + canSave: true, + canEdit: true, + canAdmin: true, + canDelete: true, + version: 0, + }; + + beforeEach(() => { + jest.clearAllMocks(); + (contextSrv.hasPermission as jest.Mock).mockReturnValue(true); + config.unifiedAlertingEnabled = true; + }); + + describe('Alerts tab visibility', () => { + it('should show Alerts tab for regular (non-managed) folders when user has permissions', () => { + const navModel = buildNavModel(mockFolder); + const alertingTab = navModel.children?.find((child) => child.id === getAlertingTabID(mockFolder.uid)); + + expect(alertingTab).toBeDefined(); + expect(alertingTab?.text).toContain('Alert rules'); + }); + + it('should hide Alerts tab for Git-synced folders', () => { + const gitSyncedFolder: FolderDTO = { + ...mockFolder, + managedBy: ManagerKind.Repo, + }; + + const navModel = buildNavModel(gitSyncedFolder); + const alertingTab = navModel.children?.find((child) => child.id === getAlertingTabID(mockFolder.uid)); + + expect(alertingTab).toBeUndefined(); + }); + + it('should hide Alerts tab when user lacks AlertingRuleRead permission', () => { + (contextSrv.hasPermission as jest.Mock).mockReturnValue(false); + + const navModel = buildNavModel(mockFolder); + const alertingTab = navModel.children?.find((child) => child.id === getAlertingTabID(mockFolder.uid)); + + expect(alertingTab).toBeUndefined(); + expect(contextSrv.hasPermission).toHaveBeenCalledWith(AccessControlAction.AlertingRuleRead); + }); + + it('should hide Alerts tab when unified alerting is disabled', () => { + config.unifiedAlertingEnabled = false; + + const navModel = buildNavModel(mockFolder); + const alertingTab = navModel.children?.find((child) => child.id === getAlertingTabID(mockFolder.uid)); + + expect(alertingTab).toBeUndefined(); + }); + + it('should show Alerts tab for regular folders with all conditions met', () => { + const navModel = buildNavModel(mockFolder); + const alertingTab = navModel.children?.find((child) => child.id === getAlertingTabID(mockFolder.uid)); + + expect(alertingTab).toBeDefined(); + expect(alertingTab?.icon).toBe('bell'); + expect(alertingTab?.url).toBe(`${mockFolder.url}/alerting`); + }); + }); +}); diff --git a/public/app/features/folders/state/navModel.ts b/public/app/features/folders/state/navModel.ts index dd53189785e..1a4dffef993 100644 --- a/public/app/features/folders/state/navModel.ts +++ b/public/app/features/folders/state/navModel.ts @@ -52,7 +52,11 @@ export function buildNavModel(folder: FolderDTO | FolderParent, parentsArg?: Fol }); } - if (contextSrv.hasPermission(AccessControlAction.AlertingRuleRead) && config.unifiedAlertingEnabled) { + if ( + !isProvisioned && + contextSrv.hasPermission(AccessControlAction.AlertingRuleRead) && + config.unifiedAlertingEnabled + ) { model.children!.push({ active: false, icon: 'bell', diff --git a/public/app/features/library-panels/components/LibraryPanelCard/LibraryPanelCard.tsx b/public/app/features/library-panels/components/LibraryPanelCard/LibraryPanelCard.tsx index 1faa611d888..ebf2c37ea41 100644 --- a/public/app/features/library-panels/components/LibraryPanelCard/LibraryPanelCard.tsx +++ b/public/app/features/library-panels/components/LibraryPanelCard/LibraryPanelCard.tsx @@ -39,7 +39,7 @@ const LibraryPanelCardComponent = ({ libraryPanel, onClick, onDelete, showSecond title={libraryPanel.name} description={libraryPanel.description} plugin={panelPlugin} - onClick={() => onClick?.(libraryPanel)} + onSelect={() => onClick?.(libraryPanel)} onDelete={showSecondaryActions ? () => setShowDeletionModal(true) : undefined} > diff --git a/public/app/features/library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch.test.tsx b/public/app/features/library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch.test.tsx index 7cb1a99a864..941dca5416d 100644 --- a/public/app/features/library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch.test.tsx +++ b/public/app/features/library-panels/components/LibraryPanelsSearch/LibraryPanelsSearch.test.tsx @@ -252,7 +252,7 @@ describe('LibraryPanelsSearch', () => { } ); - const card = () => screen.getByLabelText(/plugin visualization item time series/i); + const card = () => screen.getByTestId(/plugin visualization item time series/i); expect(screen.queryByText(/you haven\'t created any library panels yet/i)).not.toBeInTheDocument(); expect(card()).toBeInTheDocument(); @@ -293,7 +293,7 @@ describe('LibraryPanelsSearch', () => { } ); - const card = () => screen.getByLabelText(/plugin visualization item time series/i); + const card = () => screen.getByTestId(/plugin visualization item time series/i); expect(screen.queryByText(/you haven\'t created any library panels yet/i)).not.toBeInTheDocument(); expect(card()).toBeInTheDocument(); diff --git a/public/app/features/live/dashboard/types.ts b/public/app/features/live/dashboard/types.ts index 447fc2c9101..cffe686fc27 100644 --- a/public/app/features/live/dashboard/types.ts +++ b/public/app/features/live/dashboard/types.ts @@ -8,7 +8,6 @@ export enum DashboardEventAction { export interface DashboardEvent { uid: string; action: DashboardEventAction; - userId?: number; message?: string; sessionId?: string; timestamp?: number; diff --git a/public/app/features/logs/components/fieldSelector/FieldSelector.tsx b/public/app/features/logs/components/fieldSelector/FieldSelector.tsx index 44b1ff0f85c..d68cf5340c9 100644 --- a/public/app/features/logs/components/fieldSelector/FieldSelector.tsx +++ b/public/app/features/logs/components/fieldSelector/FieldSelector.tsx @@ -35,7 +35,7 @@ export const LogListFieldSelector = ({ containerElement, dataFrames, logs }: Log const { displayedFields, onClickShowField, onClickHideField, setDisplayedFields, logOptionsStorageKey } = useLogListContext(); const [sidebarHeight, setSidebarHeight] = useState(220); - const [sidebarWidth, setSidebarWidth] = useState(getSidebarWidth(logOptionsStorageKey)); + const [sidebarWidth, setSidebarWidth] = useState(getFieldSelectorWidth(logOptionsStorageKey)); const dragStyles = useStyles2(getDragStyles); useLayoutEffect(() => { @@ -74,7 +74,7 @@ export const LogListFieldSelector = ({ containerElement, dataFrames, logs }: Log }, [setSidebarWidthWrapper]); const expand = useCallback(() => { - const width = getSidebarWidth(logOptionsStorageKey); + const width = getFieldSelectorWidth(logOptionsStorageKey); setSidebarWidthWrapper(width < 2 * MIN_WIDTH ? DEFAULT_WIDTH : width); reportInteraction('logs_field_selector_expand_clicked', { mode: 'logs', @@ -205,7 +205,7 @@ export const LogsTableFieldSelector = ({ }, [setSidebarWidthWrapper]); const expand = useCallback(() => { - const width = getSidebarWidth(SETTING_KEY_ROOT); + const width = getFieldSelectorWidth(SETTING_KEY_ROOT); setSidebarWidthWrapper(width < 2 * MIN_WIDTH ? DEFAULT_WIDTH : width); reportInteraction('logs_field_selector_expand_clicked', { mode: 'table', @@ -436,7 +436,7 @@ function getSuggestedFields(logs: LogListModel[], displayedFields: string[], def return suggestedFields; } -export function getSidebarWidth(logOptionsStorageKey?: string): number { +export function getFieldSelectorWidth(logOptionsStorageKey?: string): number { const width = (logOptionsStorageKey ? parseInt(store.get(`${logOptionsStorageKey}.fieldSelector.width`) ?? DEFAULT_WIDTH, 10) @@ -445,7 +445,7 @@ export function getSidebarWidth(logOptionsStorageKey?: string): number { return width < MIN_WIDTH ? MIN_WIDTH : width; } -export function getSidebarState(logOptionsStorageKey?: string): boolean | undefined { +export function getFieldSelectorState(logOptionsStorageKey?: string): boolean | undefined { if (!logOptionsStorageKey) { return undefined; } diff --git a/public/app/features/logs/components/panel/InfiniteScroll.tsx b/public/app/features/logs/components/panel/InfiniteScroll.tsx index 3c7de64b6be..4508682df57 100644 --- a/public/app/features/logs/components/panel/InfiniteScroll.tsx +++ b/public/app/features/logs/components/panel/InfiniteScroll.tsx @@ -72,7 +72,7 @@ export const InfiniteScroll = ({ const lastEvent = useRef(null); const countRef = useRef(0); const lastLogOfPage = useRef([]); - const styles = useStyles2(getStyles, virtualization); + const styles = useStyles2(getStyles, virtualization, displayedFields); const resetStateTimeout = useRef | null>(null); const scrollToLogLineRef = useRef(undefined); const noScrollRef = useRef(undefined); @@ -256,7 +256,11 @@ export const InfiniteScroll = ({ if (props.visibleStartIndex === 0) { noScrollRef.current = scrollElement.scrollHeight <= scrollElement.clientHeight; } - if (noScrollRef.current || infiniteLoaderState === 'loading' || infiniteLoaderState === 'out-of-bounds') { + if (noScrollRef.current) { + setInfiniteLoaderState('idle'); + return; + } + if (infiniteLoaderState === 'loading' || infiniteLoaderState === 'out-of-bounds') { return; } const lastLogIndex = logs.length - 1; @@ -267,7 +271,7 @@ export const InfiniteScroll = ({ setInfiniteLoaderState('idle'); } }, - [infiniteLoaderState, logs.length, scrollElement] + [infiniteLoaderState, logs, scrollElement] ); const getItemKey = useCallback((index: number) => (logs[index] ? logs[index].uid : index.toString()), [logs]); diff --git a/public/app/features/logs/components/panel/LogDetailsContext.tsx b/public/app/features/logs/components/panel/LogDetailsContext.tsx index de0c044911e..d3526e2bcb4 100644 --- a/public/app/features/logs/components/panel/LogDetailsContext.tsx +++ b/public/app/features/logs/components/panel/LogDetailsContext.tsx @@ -3,7 +3,7 @@ import { createContext, ReactNode, useCallback, useContext, useEffect, useState import { LogRowModel, store } from '@grafana/data'; -import { getSidebarWidth } from '../fieldSelector/FieldSelector'; +import { getFieldSelectorWidth } from '../fieldSelector/FieldSelector'; import { LogLineDetailsMode } from './LogLineDetails'; import { LogListModel } from './processing'; @@ -56,6 +56,7 @@ export interface Props { logs: LogRowModel[]; logOptionsStorageKey?: string; showControls: boolean; + showFieldSelector?: boolean; } export const LogDetailsContextProvider = ({ @@ -68,12 +69,13 @@ export const LogDetailsContextProvider = ({ : getDefaultDetailsMode(containerElement), logs, showControls, + showFieldSelector, }: Props) => { const [showDetails, setShowDetails] = useState([]); const [currentLog, setCurrentLog] = useState(undefined); const [detailsWidth, setDetailsWidthState] = useState( - getDetailsWidth(containerElement, logOptionsStorageKey, undefined, detailsModeProp, showControls) + getDetailsWidth(containerElement, logOptionsStorageKey, undefined, detailsModeProp, showControls, showFieldSelector) ); const [detailsMode, setDetailsMode] = useState( detailsModeProp ?? getDefaultDetailsMode(containerElement) @@ -101,8 +103,10 @@ export const LogDetailsContextProvider = ({ // Sync log details inline and sidebar width useEffect(() => { - setDetailsWidthState(getDetailsWidth(containerElement, logOptionsStorageKey, undefined, detailsMode, showControls)); - }, [containerElement, detailsMode, logOptionsStorageKey, showControls]); + setDetailsWidthState( + getDetailsWidth(containerElement, logOptionsStorageKey, undefined, detailsMode, showControls, showFieldSelector) + ); + }, [containerElement, detailsMode, logOptionsStorageKey, showControls, showFieldSelector]); // Sync log details width useEffect(() => { @@ -111,13 +115,20 @@ export const LogDetailsContextProvider = ({ } const handleResize = debounce(() => { setDetailsWidthState((detailsWidth) => - getDetailsWidth(containerElement, logOptionsStorageKey, detailsWidth, detailsMode, showControls) + getDetailsWidth( + containerElement, + logOptionsStorageKey, + detailsWidth, + detailsMode, + showControls, + showFieldSelector + ) ); }, 50); const observer = new ResizeObserver(() => handleResize()); observer.observe(containerElement); return () => observer.disconnect(); - }, [containerElement, detailsMode, logOptionsStorageKey, showControls, showDetails]); + }, [containerElement, detailsMode, logOptionsStorageKey, showControls, showDetails, showFieldSelector]); const closeDetails = useCallback(() => { showDetails.forEach((log) => removeDetailsScrollPosition(log)); @@ -158,7 +169,10 @@ export const LogDetailsContextProvider = ({ return; } - const maxWidth = containerElement.clientWidth - getSidebarWidth(logOptionsStorageKey) - LOG_LIST_MIN_WIDTH; + const maxWidth = + containerElement.clientWidth - + (showFieldSelector ? getFieldSelectorWidth(logOptionsStorageKey) : 0) - + LOG_LIST_MIN_WIDTH; if (width > maxWidth) { return; } @@ -166,7 +180,7 @@ export const LogDetailsContextProvider = ({ store.set(`${logOptionsStorageKey}.detailsWidth`, width); setDetailsWidthState(width); }, - [containerElement, logOptionsStorageKey] + [containerElement, logOptionsStorageKey, showFieldSelector] ); return ( @@ -196,12 +210,14 @@ export function getDetailsWidth( logOptionsStorageKey?: string, currentWidth?: number, detailsMode: LogLineDetailsMode = 'sidebar', - showControls?: boolean + showControls?: boolean, + showFieldSelector?: boolean ) { if (!containerElement) { return 0; } - const availableWidth = containerElement.clientWidth - getSidebarWidth(logOptionsStorageKey); + const availableWidth = + containerElement.clientWidth - (showFieldSelector ? getFieldSelectorWidth(logOptionsStorageKey) : 0); if (detailsMode === 'inline') { return availableWidth - getScrollbarWidth() - (showControls ? LOG_LIST_CONTROLS_WIDTH : 0); } diff --git a/public/app/features/logs/components/panel/LogLine.tsx b/public/app/features/logs/components/panel/LogLine.tsx index 292f35ea75a..a1914607600 100644 --- a/public/app/features/logs/components/panel/LogLine.tsx +++ b/public/app/features/logs/components/panel/LogLine.tsx @@ -202,7 +202,7 @@ const LogLineComponent = memo( {/* A button element could be used but in Safari it prevents text selection. Fallback available for a11y in LogLineMenu */} {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */}
    + {' '} ); @@ -448,12 +448,12 @@ const LogLineBody = ({ log, styles }: { log: LogListModel; styles: LogLineStyles highlightClassName={styles.matchHighLight} /> ) : ( - {log.body} + {log.body} ); } return ( - + {' '} ); @@ -468,7 +468,30 @@ export function getGridTemplateColumns(dimensions: LogFieldDimension[], displaye } export type LogLineStyles = ReturnType; -export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtualization) => { +export const getStyles = ( + theme: GrafanaTheme2, + virtualization: LogLineVirtualization | undefined = undefined, + displayedFields: string[] = [] +) => { + const base = tinycolor(theme.colors.background.primary); + + let maxContrast = theme.isDark + ? tinycolor(theme.colors.text.maxContrast).darken(10).toRgbString() + : tinycolor(theme.colors.text.maxContrast).lighten(10).toRgbString(); + let colorDefault = theme.isDark + ? theme.colors.text.primary + : tinycolor(theme.colors.text.maxContrast).lighten(30).toRgbString(); + const contrast1 = tinycolor.readability(base, maxContrast); + const contrast2 = tinycolor.readability(base, colorDefault); + + if (!displayedFields.length || (displayedFields.length === 1 && displayedFields.includes(LOG_LINE_BODY_FIELD_NAME))) { + colorDefault = theme.colors.text.primary; + maxContrast = theme.colors.text.primary; + } else if (contrast1 < contrast2) { + colorDefault = maxContrast; + maxContrast = theme.colors.text.primary; + } + const colors = { critical: '#B877D9', error: theme.colors.error.text, @@ -477,8 +500,9 @@ export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtuali trace: '#6ed0e0', info: '#6CCF8E', metadata: theme.colors.text.secondary, - default: theme.colors.text.primary, + default: colorDefault, parsedField: theme.colors.text.secondary, + logLineBody: maxContrast, }; const hoverColor = tinycolor(theme.colors.background.canvas).darken(11).toRgbString(); @@ -490,8 +514,6 @@ export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtuali gap: theme.spacing(0.5), flexDirection: 'row', fontFamily: theme.typography.fontFamilyMonospace, - fontSize: theme.typography.fontSize, - lineHeight: theme.typography.body.lineHeight, wordBreak: 'break-all', '&:hover': { background: hoverColor, @@ -509,7 +531,7 @@ export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtuali }, '& .log-syntax-highlight': { '.log-token-string': { - color: colors.default, + color: colors.logLineBody, }, '.log-token-duration': { color: theme.colors.success.text, @@ -540,6 +562,9 @@ export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtuali color: theme.components.textHighlight.text, backgroundColor: theme.components.textHighlight.background, }, + '&.log-line-body': { + color: colors.logLineBody, + }, }, '& .no-highlighting': { color: theme.colors.text.primary, @@ -553,6 +578,10 @@ export const getStyles = (theme: GrafanaTheme2, virtualization?: LogLineVirtuali fontSize: theme.typography.bodySmall.fontSize, lineHeight: theme.typography.bodySmall.lineHeight, }), + fontSizeDefault: css({ + fontSize: theme.typography.fontSize, + lineHeight: theme.typography.body.lineHeight, + }), detailsDisplayed: css({ background: tinycolor(theme.colors.background.canvas) .darken(theme.isDark ? 2 : 5) diff --git a/public/app/features/logs/components/panel/LogLineDetails.test.tsx b/public/app/features/logs/components/panel/LogLineDetails.test.tsx index dafc055ce0d..cee12e10d8b 100644 --- a/public/app/features/logs/components/panel/LogLineDetails.test.tsx +++ b/public/app/features/logs/components/panel/LogLineDetails.test.tsx @@ -20,6 +20,7 @@ import { setPluginLinksHook } from '@grafana/runtime'; import { createTempoDatasource } from 'app/plugins/datasource/tempo/test/mocks'; import { LOG_LINE_BODY_FIELD_NAME } from '../LogDetailsBody'; +import { getFieldSelectorWidth } from '../fieldSelector/FieldSelector'; import { createLogLine } from '../mocks/logRow'; import { emptyContextData, LogDetailsContext, LogDetailsContextData } from './LogDetailsContext'; @@ -27,6 +28,10 @@ import { LogLineDetails, Props } from './LogLineDetails'; import { LogListContext, LogListContextData } from './LogListContext'; import { defaultValue } from './__mocks__/LogListContext'; +jest.mock('../fieldSelector/FieldSelector'); + +jest.mocked(getFieldSelectorWidth).mockReturnValue(220); + jest.mock('@grafana/assistant', () => { return { ...jest.requireActual('@grafana/assistant'), @@ -79,6 +84,7 @@ const setup = ( }, timeZone: 'browser', showControls: true, + showFieldSelector: true, ...(propOverrides || {}), }; @@ -775,4 +781,24 @@ describe('LogLineDetails', () => { expect(screen.getByText('value')).toBeInTheDocument(); expect(screen.getByText('Open service overview for label')).toBeInTheDocument(); }); + + describe('Width regressions', () => { + test('should consider Fields Selector width when enabled', () => { + jest.mocked(getFieldSelectorWidth).mockClear(); + + setup({ showFieldSelector: true }, { labels: { key1: 'label1', key2: 'label2' } }); + expect(screen.getByText('Log line')).toBeInTheDocument(); + expect(screen.getByText('Fields')).toBeInTheDocument(); + expect(getFieldSelectorWidth).toHaveBeenCalled(); + }); + + test('should not consider Fields Selector width when disabled', () => { + jest.mocked(getFieldSelectorWidth).mockClear(); + + setup({ showFieldSelector: false }, { labels: { key1: 'label1', key2: 'label2' } }); + expect(screen.getByText('Log line')).toBeInTheDocument(); + expect(screen.getByText('Fields')).toBeInTheDocument(); + expect(getFieldSelectorWidth).not.toHaveBeenCalled(); + }); + }); }); diff --git a/public/app/features/logs/components/panel/LogLineDetails.tsx b/public/app/features/logs/components/panel/LogLineDetails.tsx index 19639e61f8c..bc5a961cbd7 100644 --- a/public/app/features/logs/components/panel/LogLineDetails.tsx +++ b/public/app/features/logs/components/panel/LogLineDetails.tsx @@ -7,7 +7,7 @@ import { t } from '@grafana/i18n'; import { reportInteraction } from '@grafana/runtime'; import { getDragStyles, Icon, Tab, TabsBar, useStyles2 } from '@grafana/ui'; -import { getSidebarWidth } from '../fieldSelector/FieldSelector'; +import { getFieldSelectorWidth } from '../fieldSelector/FieldSelector'; import { getDetailsScrollPosition, saveDetailsScrollPosition, useLogDetailsContext } from './LogDetailsContext'; import { LogLineDetailsComponent } from './LogLineDetailsComponent'; @@ -22,12 +22,13 @@ export interface Props { timeRange: TimeRange; timeZone: string; showControls: boolean; + showFieldSelector: boolean | undefined; } export type LogLineDetailsMode = 'inline' | 'sidebar'; export const LogLineDetails = memo( - ({ containerElement, focusLogLine, logs, timeRange, timeZone, showControls }: Props) => { + ({ containerElement, focusLogLine, logs, timeRange, timeZone, showControls, showFieldSelector }: Props) => { const { noInteractions, logOptionsStorageKey } = useLogListContext(); const { detailsWidth, setDetailsWidth } = useLogDetailsContext(); const styles = useStyles2(getStyles, 'sidebar', showControls); @@ -48,7 +49,10 @@ export const LogLineDetails = memo( } }, [noInteractions]); - const maxWidth = containerElement.clientWidth - getSidebarWidth(logOptionsStorageKey) - LOG_LIST_MIN_WIDTH; + const maxWidth = + containerElement.clientWidth - + (showFieldSelector ? getFieldSelectorWidth(logOptionsStorageKey) : 0) - + LOG_LIST_MIN_WIDTH; return ( { // Default displayed fields expect(screen.getByText('Log line')).toBeInTheDocument(); - expect(screen.getByText('OTel attributes')).toBeInTheDocument(); + expect(screen.getByText('Log attributes')).toBeInTheDocument(); // Suggested field expect(screen.getByText('scope_name')).toBeInTheDocument(); diff --git a/public/app/features/logs/components/panel/LogList.tsx b/public/app/features/logs/components/panel/LogList.tsx index 8a8a9b085dc..3c51af0342b 100644 --- a/public/app/features/logs/components/panel/LogList.tsx +++ b/public/app/features/logs/components/panel/LogList.tsx @@ -219,6 +219,7 @@ export const LogList = ({ logs={logs} logOptionsStorageKey={logOptionsStorageKey} showControls={showControls} + showFieldSelector={showFieldSelector} > )}
    @@ -550,7 +552,7 @@ const LogListComponent = ({ function getStyles( theme: GrafanaTheme2, dimensions: LogFieldDimension[], - displayedFields: string[], + displayedFields: string[] = [], { showTime }: { showTime: boolean } ) { const columns = showTime ? dimensions : dimensions.filter((_, index) => index > 0); diff --git a/public/app/features/logs/components/panel/LogListContext.tsx b/public/app/features/logs/components/panel/LogListContext.tsx index a917b0eac56..139f40ea98e 100644 --- a/public/app/features/logs/components/panel/LogListContext.tsx +++ b/public/app/features/logs/components/panel/LogListContext.tsx @@ -27,7 +27,7 @@ import { config, getDataSourceSrv } from '@grafana/runtime'; import { PopoverContent } from '@grafana/ui'; import { checkLogsError, checkLogsSampled, downloadLogs as download, DownloadFormat } from '../../utils'; -import { getSidebarState } from '../fieldSelector/FieldSelector'; +import { getFieldSelectorState } from '../fieldSelector/FieldSelector'; import { getDisplayedFieldsForLogs } from '../otel/formats'; import { getDefaultDetailsMode, getDetailsWidth } from './LogDetailsContext'; @@ -245,7 +245,7 @@ export const LogListContextProvider = ({ dedupStrategy, fontSize, forceEscape: logListState.forceEscape, - fieldSelectorOpen: getSidebarState(logOptionsStorageKey), + fieldSelectorOpen: getFieldSelectorState(logOptionsStorageKey), showTime, showUniqueLabels, syntaxHighlighting, diff --git a/public/app/features/logs/components/panel/processing.ts b/public/app/features/logs/components/panel/processing.ts index 0f3ea0ac6b1..dcb391c8e07 100644 --- a/public/app/features/logs/components/panel/processing.ts +++ b/public/app/features/logs/components/panel/processing.ts @@ -364,7 +364,7 @@ export function getNormalizedFieldName(field: string) { if (field === LOG_LINE_BODY_FIELD_NAME) { return t('logs.log-line-details.log-line-field', 'Log line'); } else if (field === OTEL_LOG_LINE_ATTRIBUTES_FIELD_NAME) { - return t('logs.log-line-details.log-attributes-field', 'OTel attributes'); + return t('logs.log-line-details.log-attributes-field', 'Log attributes'); } return field; } diff --git a/public/app/features/manage-dashboards/DashboardImportPage.tsx b/public/app/features/manage-dashboards/DashboardImportPage.tsx index fd286a33f2f..b640035c2de 100644 --- a/public/app/features/manage-dashboards/DashboardImportPage.tsx +++ b/public/app/features/manage-dashboards/DashboardImportPage.tsx @@ -94,17 +94,14 @@ class UnthemedDashboardImport extends PureComponent { const json = JSON.parse(String(result)); if (json.spec?.elements) { - dispatch(importDashboardV2Json(json.spec)); - return; + return dispatch(importDashboardV2Json(json.spec)); } else if (json.elements) { - dispatch(importDashboardV2Json(json)); - return; + return dispatch(importDashboardV2Json(json)); } // check if it's a v1 resource format if (json.spec) { - this.props.importDashboardJson(json.spec); - return; + return this.props.importDashboardJson(json.spec); } this.props.importDashboardJson(json); @@ -123,20 +120,26 @@ class UnthemedDashboardImport extends PureComponent { const dashboard = JSON.parse(formData.dashboardJson); + if ((dashboard.spec?.elements || dashboard.elements) && !config.featureToggles.dashboardNewLayouts) { + return appEvents.emit(AppEvents.alertError, [ + 'Import failed', + 'Dashboard using new layout cannot be imported because the feature is not enabled', + ]); + } + // check if it's a v2 resource format if (dashboard.spec?.elements) { - dispatch(importDashboardV2Json(dashboard.spec)); - return; - // check if it's just a v2 spec - } else if (dashboard.elements) { - dispatch(importDashboardV2Json(dashboard)); - return; + return dispatch(importDashboardV2Json(dashboard.spec)); + } + + // check if it's just a v2 spec + if (dashboard.elements) { + return dispatch(importDashboardV2Json(dashboard)); } // check if it's a v1 resource format if (dashboard.spec) { - this.props.importDashboardJson(dashboard.spec); - return; + return this.props.importDashboardJson(dashboard.spec); } this.props.importDashboardJson(dashboard); diff --git a/public/app/features/panel/components/VizTypePicker/PanelTypeCard.tsx b/public/app/features/panel/components/VizTypePicker/PanelTypeCard.tsx index 2125e645e60..3a5c55d2c1b 100644 --- a/public/app/features/panel/components/VizTypePicker/PanelTypeCard.tsx +++ b/public/app/features/panel/components/VizTypePicker/PanelTypeCard.tsx @@ -1,5 +1,4 @@ import { css, cx } from '@emotion/css'; -import { MouseEventHandler } from 'react'; import * as React from 'react'; import Skeleton from 'react-loading-skeleton'; @@ -14,11 +13,12 @@ interface Props { isCurrent: boolean; plugin: PanelPluginMeta; title: string; - onClick: MouseEventHandler; + onSelect: (withModKey?: boolean) => void; onDelete?: () => void; disabled?: boolean; showBadge?: boolean; description?: string; + tabIndex?: number; } const IMAGE_SIZE = 38; @@ -27,12 +27,13 @@ const PanelTypeCardComponent = ({ isCurrent, title, plugin, - onClick, + onSelect, onDelete, disabled, showBadge, description, children, + tabIndex = 0, }: React.PropsWithChildren) => { const styles = useStyles2(getStyles); @@ -44,13 +45,22 @@ const PanelTypeCardComponent = ({ }); return ( - // TODO: fix keyboard a11y - // eslint-disable-next-line jsx-a11y/click-events-have-key-events
    onSelect(ev.metaKey || ev.ctrlKey || ev.altKey)} + role="button" + tabIndex={0} + onKeyDown={ + isDisabled + ? undefined + : (ev) => { + if (ev.key === 'Enter' || ev.key === ' ') { + ev.preventDefault(); + onSelect(ev.metaKey || ev.ctrlKey || ev.altKey); + } + } + } title={ isCurrent ? t('panel.panel-type-card.title-click-to-close', 'Click again to close this section') : plugin.name } diff --git a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx index cf9fafd0b9b..7248dbcc1e5 100644 --- a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx +++ b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestionCard.tsx @@ -34,8 +34,9 @@ export function VisualizationSuggestionCard({ className: cx(className, styles.vizBox), 'data-testid': selectors.components.VisualizationPreview.card(suggestion.name), style: outerStyles, + tabIndex: -1, // selection is handled by parent container ...restProps, - }; + } satisfies HTMLAttributes & { 'data-testid': string }; let content: ReactNode; diff --git a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx index e60e91bcd96..e93e74f358d 100644 --- a/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx +++ b/public/app/features/panel/components/VizTypePicker/VisualizationSuggestions.tsx @@ -1,5 +1,5 @@ import { css } from '@emotion/css'; -import { useState, useEffect, useCallback, useMemo } from 'react'; +import { Fragment, useState, useEffect, useCallback, useMemo } from 'react'; import { useAsync, useMeasure } from 'react-use'; import { @@ -30,7 +30,17 @@ export interface Props { export function VisualizationSuggestions({ onChange, data, panel }: Props) { const styles = useStyles2(getStyles); - const { value: suggestions, loading, error } = useAsync(() => getAllSuggestions(data), [data]); + const { + value: suggestions, + loading, + error, + } = useAsync(async () => { + if (!hasData(data)) { + return []; + } + + return await getAllSuggestions(data); + }, [data]); const [suggestionHash, setSuggestionHash] = useState(null); const [firstCardRef, { width }] = useMeasure(); const [firstCardHash, setFirstCardHash] = useState(null); @@ -89,7 +99,7 @@ export function VisualizationSuggestions({ onChange, data, panel }: Props) { } }, [suggestions, suggestionHash, firstCardHash, isNewVizSuggestionsEnabled, isUnconfiguredPanel, applySuggestion]); - if (loading) { + if (loading || !data) { return (
    @@ -120,16 +130,12 @@ export function VisualizationSuggestions({ onChange, data, panel }: Props) { ); } - if (!data) { - return null; - } - return (
    {isNewVizSuggestionsEnabled - ? suggestionsByVizType.map(([vizType, vizTypeSuggestions]) => ( - <> -
    + ? suggestionsByVizType.map(([vizType, vizTypeSuggestions], groupIndex) => ( + +
    {vizType?.info && } {vizType?.name || t('panel.visualization-suggestions.unknown-viz-type', 'Unknown visualization type')} @@ -141,10 +147,21 @@ export function VisualizationSuggestions({ onChange, data, panel }: Props) {
    { + if (ev.key === 'Enter' || ev.key === ' ') { + ev.preventDefault(); + applySuggestion(suggestion, isNewVizSuggestionsEnabled && !isCardSelected); + } + }} ref={index === 0 ? firstCardRef : undefined} > {isCardSelected && (
    ); })} - + )) : suggestions?.map((suggestion, index) => (
    diff --git a/public/app/features/panel/components/VizTypePicker/VizTypePicker.tsx b/public/app/features/panel/components/VizTypePicker/VizTypePicker.tsx index 8bf12da90c8..f9d3ae7d92c 100644 --- a/public/app/features/panel/components/VizTypePicker/VizTypePicker.tsx +++ b/public/app/features/panel/components/VizTypePicker/VizTypePicker.tsx @@ -41,16 +41,16 @@ export function VizTypePicker({ pluginId, searchQuery, onChange, trackSearch }: return (
    - {filteredPluginTypes.map((plugin) => ( + {filteredPluginTypes.map((plugin, idx) => ( + onSelect={(withModKey) => onChange({ pluginId: plugin.id, - withModKey: e.metaKey || e.ctrlKey || e.altKey, + withModKey, }) } /> diff --git a/public/app/features/panel/components/VizTypePicker/VizTypePickerPlugin.tsx b/public/app/features/panel/components/VizTypePicker/VizTypePickerPlugin.tsx index 1ece804df3b..fc277b8f77c 100644 --- a/public/app/features/panel/components/VizTypePicker/VizTypePickerPlugin.tsx +++ b/public/app/features/panel/components/VizTypePicker/VizTypePickerPlugin.tsx @@ -1,5 +1,3 @@ -import { MouseEventHandler } from 'react'; - import { PanelPluginMeta } from '@grafana/data'; import { PanelTypeCard } from './PanelTypeCard'; @@ -7,17 +5,17 @@ import { PanelTypeCard } from './PanelTypeCard'; interface Props { isCurrent: boolean; plugin: PanelPluginMeta; - onClick: MouseEventHandler; + onSelect: (withModKey?: boolean) => void; disabled: boolean; } -export const VizTypePickerPlugin = ({ isCurrent, plugin, onClick, disabled }: Props) => { +export const VizTypePickerPlugin = ({ isCurrent, plugin, onSelect, disabled }: Props) => { return ( { - if (!_pluginCache) { - _pluginCache = []; + // list of plugins to load is determined by the feature flag + const pluginIds: string[] = config.featureToggles.externalVizSuggestions + ? getAllPanelPluginMeta() + .filter((panel) => panel.suggestions) + .map((m) => m.id) + : panelsToCheckFirst; - // list of plugins to load is determined by the feature flag - const pluginIds: string[] = config.featureToggles.externalVizSuggestions - ? getAllPanelPluginMeta() - .filter((panel) => panel.suggestions) - .map((m) => m.id) - : panelsToCheckFirst; + // import the plugins in parallel using Promise.allSettled + const plugins: PanelPlugin[] = []; + const settledPromises = await Promise.allSettled(pluginIds.map((id) => importPanelPlugin(id))); + for (let i = 0; i < settledPromises.length; i++) { + const settled = settledPromises[i]; - // import the plugins in parallel using Promise.allSettled - const settledPromises = await Promise.allSettled(pluginIds.map((id) => importPanelPlugin(id))); - for (let i = 0; i < settledPromises.length; i++) { - const settled = settledPromises[i]; - - if (settled.status === 'fulfilled') { - _pluginCache.push(settled.value); - } - // TODO: do we want to somehow log if there were errors loading some of the plugins? + if (settled.status === 'fulfilled') { + plugins.push(settled.value); } + // TODO: do we want to somehow log if there were errors loading some of the plugins? } - if (_pluginCache.length === 0) { + if (plugins.length === 0) { throw new Error('No panel plugins with visualization suggestions found'); } - return _pluginCache; + return plugins; } /** @@ -83,7 +79,7 @@ export function sortSuggestions(suggestions: PanelPluginVisualizationSuggestion[ if (mappedA && dataSummary.hasPreferredVisualisationType(mappedA)) { return -1; } - const mappedB = mapPreferredVisualisationTypeToPlugin(a.pluginId); + const mappedB = mapPreferredVisualisationTypeToPlugin(b.pluginId); if (mappedB && dataSummary.hasPreferredVisualisationType(mappedB)) { return 1; } @@ -101,9 +97,8 @@ export function sortSuggestions(suggestions: PanelPluginVisualizationSuggestion[ export async function getAllSuggestions(data?: PanelData): Promise { const dataSummary = getPanelDataSummary(data?.series); const list: PanelPluginVisualizationSuggestion[] = []; - const plugins = await getPanelsWithSuggestions(); - for (const plugin of plugins) { + for (const plugin of await getPanelsWithSuggestions()) { const suggestions = plugin.getSuggestions(dataSummary); if (suggestions) { list.push(...suggestions); diff --git a/public/app/features/plugins/admin/api.ts b/public/app/features/plugins/admin/api.ts index 74a072ba054..aa5bc32f183 100644 --- a/public/app/features/plugins/admin/api.ts +++ b/public/app/features/plugins/admin/api.ts @@ -8,6 +8,7 @@ import { LocalPlugin, RemotePlugin, CatalogPluginDetails, + CatalogPluginInsights, Version, PluginVersion, InstancePlugin, @@ -47,6 +48,21 @@ export async function getPluginDetails(id: string): Promise { + if (!version) { + throw new Error('Version is required'); + } + try { + const insights = await getBackendSrv().get(`${GCOM_API_ROOT}/plugins/${id}/versions/${version}/insights`); + return insights; + } catch (error) { + if (isFetchError(error)) { + error.isHandled = true; + } + throw error; + } +} + export async function getRemotePlugins(): Promise { try { const { items: remotePlugins }: { items: RemotePlugin[] } = await getBackendSrv().get(`${GCOM_API_ROOT}/plugins`, { diff --git a/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx b/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx index da4eef2f0d4..0ffc93f8f77 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPage.test.tsx @@ -62,10 +62,12 @@ const plugin: CatalogPlugin = { angularDetected: false, isFullyInstalled: true, accessControl: {}, + insights: { id: 1, name: 'test-plugin', version: '1.0.0', insights: [] }, }; jest.mock('../state/hooks', () => ({ useGetSingle: jest.fn(), + useGetPluginInsights: jest.fn(), useFetchStatus: jest.fn().mockReturnValue({ isLoading: false }), useFetchDetailsStatus: () => ({ isLoading: false }), useIsRemotePluginsAvailable: () => false, diff --git a/public/app/features/plugins/admin/components/PluginDetailsPage.tsx b/public/app/features/plugins/admin/components/PluginDetailsPage.tsx index 0e651a8e4bf..b135321e558 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPage.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPage.tsx @@ -16,11 +16,19 @@ import { PluginDetailsPanel } from '../components/PluginDetailsPanel'; import { PluginDetailsSignature } from '../components/PluginDetailsSignature'; import { usePluginDetailsTabs } from '../hooks/usePluginDetailsTabs'; import { usePluginPageExtensions } from '../hooks/usePluginPageExtensions'; -import { useGetSingle, useFetchStatus, useFetchDetailsStatus } from '../state/hooks'; +import { useGetSingle, useFetchStatus, useFetchDetailsStatus, useGetPluginInsights } from '../state/hooks'; import { PluginTabIds } from '../types'; import { PluginDetailsDeprecatedWarning } from './PluginDetailsDeprecatedWarning'; +function isPluginTabId(value: string | null): value is PluginTabIds { + if (!value) { + return false; + } + const validIds: string[] = Object.values(PluginTabIds); + return validIds.includes(value); +} + export type Props = { // The ID of the plugin pluginId: string; @@ -49,12 +57,13 @@ export function PluginDetailsPage({ }; const queryParams = new URLSearchParams(location.search); const plugin = useGetSingle(pluginId); // fetches the plugin settings for this Grafana instance + useGetPluginInsights(pluginId, plugin?.isInstalled ? plugin?.installedVersion : plugin?.latestVersion); + const isNarrowScreen = useMedia('(max-width: 600px)'); - const { navModel, activePageId } = usePluginDetailsTabs( - plugin, - queryParams.get('page') as PluginTabIds, - isNarrowScreen - ); + const pageParam = queryParams.get('page'); + const pageId = pageParam && isPluginTabId(pageParam) ? pageParam : undefined; + const { navModel, activePageId } = usePluginDetailsTabs(plugin, pageId, isNarrowScreen); + const { actions, info, subtitle } = usePluginPageExtensions(plugin); const { isLoading: isFetchLoading } = useFetchStatus(); const { isLoading: isFetchDetailsLoading } = useFetchDetailsStatus(); diff --git a/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx b/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx index eade37f559c..20787099842 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPanel.test.tsx @@ -1,11 +1,23 @@ +import userEvent from '@testing-library/user-event'; import { render, screen } from 'test/test-utils'; import { PluginSignatureStatus, PluginSignatureType, PluginType } from '@grafana/data'; +import { config } from '@grafana/runtime'; -import { CatalogPlugin } from '../types'; +import { CatalogPlugin, SCORE_LEVELS } from '../types'; import { PluginDetailsPanel } from './PluginDetailsPanel'; +jest.mock('@grafana/runtime', () => ({ + ...jest.requireActual('@grafana/runtime'), + config: { + ...jest.requireActual('@grafana/runtime').config, + featureToggles: { + pluginInsights: false, + }, + }, +})); + const mockPlugin: CatalogPlugin = { description: 'Test plugin description', downloads: 1000, @@ -185,4 +197,61 @@ describe('PluginDetailsPanel', () => { expect(regularLinks).toContainElement(raiseIssueLink); expect(regularLinks).not.toContainElement(websiteLink); }); + + it('should render plugin insights when plugin has insights', async () => { + config.featureToggles.pluginInsights = true; + const pluginWithInsights = { + ...mockPlugin, + insights: { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [ + { + name: 'security', + scoreValue: 90, + scoreLevel: SCORE_LEVELS.EXCELLENT, + items: [ + { + id: 'signature', + name: 'Signature verified', + level: 'ok' as const, + }, + ], + }, + ], + }, + }; + render(); + expect(screen.getByTestId('plugin-insights-container')).toBeInTheDocument(); + expect(screen.getByText('Plugin insights')).toBeInTheDocument(); + expect(screen.queryByText('Security')).toBeInTheDocument(); + await userEvent.click(screen.getByText('Security')); + expect(screen.getByTestId('plugin-insight-item-signature')).toBeInTheDocument(); + }); + + it('should not render plugin insights when plugin has no insights', () => { + const pluginWithoutInsights = { + ...mockPlugin, + insights: undefined, + }; + render(); + expect(screen.queryByTestId('plugin-insights-container')).not.toBeInTheDocument(); + expect(screen.queryByText('Plugin insights')).not.toBeInTheDocument(); + }); + + it('should not render plugin insights when insights array is empty', () => { + const pluginWithEmptyInsights = { + ...mockPlugin, + insights: { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [], + }, + }; + render(); + expect(screen.queryByTestId('plugin-insights-container')).not.toBeInTheDocument(); + expect(screen.queryByText('Plugin insights')).not.toBeInTheDocument(); + }); }); diff --git a/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx b/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx index 00211b61c6e..aa8b6c792ef 100644 --- a/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx +++ b/public/app/features/plugins/admin/components/PluginDetailsPanel.tsx @@ -3,7 +3,7 @@ import { useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { t, Trans } from '@grafana/i18n'; -import { reportInteraction } from '@grafana/runtime'; +import { config, reportInteraction } from '@grafana/runtime'; import { PageInfoItem } from '@grafana/runtime/internal'; import { Stack, @@ -22,6 +22,8 @@ import { formatDate } from 'app/core/internationalization/dates'; import { CatalogPlugin } from '../types'; +import { PluginInsights } from './PluginInsights'; + type Props = { pluginExtentionsInfo: PageInfoItem[]; plugin: CatalogPlugin; width?: string }; export function PluginDetailsPanel(props: Props): React.ReactElement | null { @@ -69,6 +71,11 @@ export function PluginDetailsPanel(props: Props): React.ReactElement | null { return ( <> + {config.featureToggles.pluginInsights && plugin.insights && plugin.insights?.insights?.length > 0 && ( + + + + )} {pluginExtentionsInfo.map((infoItem, index) => { diff --git a/public/app/features/plugins/admin/components/PluginInsights.test.tsx b/public/app/features/plugins/admin/components/PluginInsights.test.tsx new file mode 100644 index 00000000000..efd064c7172 --- /dev/null +++ b/public/app/features/plugins/admin/components/PluginInsights.test.tsx @@ -0,0 +1,171 @@ +import userEvent from '@testing-library/user-event'; +import { render, screen } from 'test/test-utils'; + +import { CatalogPluginInsights, InsightLevel, SCORE_LEVELS } from '../types'; + +import { PluginInsights } from './PluginInsights'; + +const mockPluginInsights: CatalogPluginInsights = { + id: 1, + name: 'test-plugin', + version: '1.0.0', + insights: [ + { + name: 'security', + scoreValue: 90, + scoreLevel: SCORE_LEVELS.EXCELLENT, + items: [ + { + id: 'signature', + name: 'Signature verified', + description: 'Plugin signature is valid', + level: 'ok' as InsightLevel, + }, + { + id: 'trackingscripts', + name: 'No unsafe JavaScript detected', + level: 'good' as InsightLevel, + }, + ], + }, + { + name: 'quality', + scoreValue: 60, + scoreLevel: SCORE_LEVELS.FAIR, + items: [ + { + id: 'metadatavalid', + name: 'Metadata is valid', + level: 'ok' as InsightLevel, + }, + { + id: 'code-rules', + name: 'Missing code rules', + description: 'Plugin lacks comprehensive code rules', + level: 'warning' as InsightLevel, + }, + ], + }, + ], +}; + +const mockPluginInsightsWithPoorLevel: CatalogPluginInsights = { + id: 3, + name: 'test-plugin-poor', + version: '0.8.0', + insights: [ + { + name: 'quality', + scoreValue: 35, + scoreLevel: SCORE_LEVELS.POOR, + items: [ + { + id: 'legacy-platform', + name: 'Quality issues detected', + level: 'warning' as InsightLevel, + }, + ], + }, + ], +}; + +describe('PluginInsights', () => { + it('should render plugin insights section', () => { + render(); + const insightsSection = screen.getByTestId('plugin-insights-container'); + expect(insightsSection).toBeInTheDocument(); + expect(screen.getByText('Plugin insights')).toBeInTheDocument(); + }); + + it('should render all insight categories with test ids', () => { + render(); + expect(screen.getByTestId('plugin-insight-security')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-quality')).toBeInTheDocument(); + }); + + it('should render category names with test ids', () => { + render(); + const securityCategory = screen.getByTestId('plugin-insight-security'); + const qualityCategory = screen.getByTestId('plugin-insight-quality'); + + expect(securityCategory).toBeInTheDocument(); + expect(securityCategory).toHaveTextContent('Security'); + expect(qualityCategory).toBeInTheDocument(); + expect(qualityCategory).toHaveTextContent('Quality'); + }); + + it('should render individual insight items with test ids', async () => { + render(); + await userEvent.click(screen.getByText('Security')); + expect(screen.getByTestId('plugin-insight-item-signature')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-item-trackingscripts')).toBeInTheDocument(); + await userEvent.click(screen.getByText('Quality')); + expect(screen.getByTestId('plugin-insight-item-metadatavalid')).toBeInTheDocument(); + expect(screen.getByTestId('plugin-insight-item-code-rules')).toBeInTheDocument(); + }); + + it('should display correct icons for Excellent score level', () => { + render(); + + const securityCategory = screen.getByTestId('plugin-insight-security'); + const securityIcon = securityCategory.querySelector('[data-testid="excellent-icon"]'); + expect(securityIcon).toBeInTheDocument(); + }); + + it('should display correct icons for Poor score levels', () => { + // Test Poor level - should show exclamation-triangle + render(); + const poorCategory = screen.getByTestId('plugin-insight-quality'); + const poorIcon = poorCategory.querySelector('[data-testid="poor-icon"]'); + expect(poorIcon).toBeInTheDocument(); + }); + + it('should handle multiple items with different insight levels', async () => { + const multiLevelInsights: CatalogPluginInsights = { + id: 5, + name: 'multi-level-plugin', + version: '2.0.0', + insights: [ + { + name: 'quality', + scoreValue: 75, + scoreLevel: SCORE_LEVELS.GOOD, + items: [ + { + id: 'code-rules', + name: 'Info level item', + level: 'info' as InsightLevel, + }, + { + id: 'sdk-usage', + name: 'OK level item', + level: 'ok' as InsightLevel, + }, + { + id: 'jsMap', + name: 'Good level item', + level: 'good' as InsightLevel, + }, + { + id: 'gosec', + name: 'Warning level item', + level: 'warning' as InsightLevel, + }, + { + id: 'legacy-builder', + name: 'Danger level item', + level: 'danger' as InsightLevel, + }, + ], + }, + ], + }; + render(); + await userEvent.click(screen.getByText('Quality')); + expect(screen.getByText('Info level item')).toBeInTheDocument(); + expect(screen.getByText('OK level item')).toBeInTheDocument(); + expect(screen.getByText('Good level item')).toBeInTheDocument(); + expect(screen.getByText('Warning level item')).toBeInTheDocument(); + expect(screen.getByText('Danger level item')).toBeInTheDocument(); + }); +}); diff --git a/public/app/features/plugins/admin/components/PluginInsights.tsx b/public/app/features/plugins/admin/components/PluginInsights.tsx new file mode 100644 index 00000000000..805bcf926bf --- /dev/null +++ b/public/app/features/plugins/admin/components/PluginInsights.tsx @@ -0,0 +1,140 @@ +import { css } from '@emotion/css'; +import { capitalize } from 'lodash'; +import { useState } from 'react'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { Trans } from '@grafana/i18n'; +import { reportInteraction } from '@grafana/runtime'; +import { Stack, Text, TextLink, CollapsableSection, Tooltip, Icon, useStyles2, useTheme2 } from '@grafana/ui'; + +import { CatalogPluginInsights } from '../types'; + +type Props = { pluginInsights: CatalogPluginInsights | undefined }; + +const PLUGINS_INSIGHTS_OPENED_EVENT_NAME = 'plugins_insights_opened'; + +export function PluginInsights(props: Props): React.ReactElement | null { + const { pluginInsights } = props; + const styles = useStyles2(getStyles); + const theme = useTheme2(); + const [openInsights, setOpenInsights] = useState>({}); + + const handleInsightToggle = (insightName: string, isOpen: boolean) => { + if (isOpen) { + reportInteraction(PLUGINS_INSIGHTS_OPENED_EVENT_NAME, { insight: insightName }); + } + setOpenInsights((prev) => ({ ...prev, [insightName]: isOpen })); + }; + + const tooltipInfo = ( + + + + + + All relevant signals are present and verified + + + + + + + + One or more signals are missing or need attention + + + +
    + + + Do you find Plugin Insights usefull? Please share your feedback{' '} + + here + + . + + +
    + ); + + return ( + <> + + + + Plugin insights + + + + + + {pluginInsights?.insights.map((insightItem, index) => { + return ( + + handleInsightToggle(insightItem.name, isOpen)} + label={ + + {insightItem.scoreLevel === 'Excellent' ? ( + + ) : ( + + )} + + {capitalize(insightItem.name)} + + + } + contentClassName={styles.pluginInsightsItems} + > + + {insightItem.items.map((item, idx) => ( + + + {item.level === 'good' ? ( + + ) : ( + + )} + + + {item.name} + + + ))} + + + + ); + })} + + + ); +} + +export const getStyles = (theme: GrafanaTheme2) => { + return { + pluginVersionDetails: css({ wordBreak: 'break-word' }), + pluginInsightsItems: css({ marginLeft: '26px', paddingTop: '0 !important' }), + pluginInsightsTooltipSeparator: css({ + border: 'none', + borderTop: `1px solid ${theme.colors.border.medium}`, + margin: `${theme.spacing(1)} 0`, + }), + }; +}; diff --git a/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts b/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts index 9ced4f20a84..3625b687f7b 100644 --- a/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts +++ b/public/app/features/plugins/admin/mocks/catalogPlugin.mock.ts @@ -34,6 +34,7 @@ export default { updatedAt: '2021-08-25T15:03:49.000Z', version: '4.2.2', error: undefined, + insights: { id: 1, name: 'alexanderzobnin-zabbix-app', version: '4.2.2', insights: [] }, details: { grafanaDependency: '>=8.0.0', pluginDependencies: [], @@ -381,6 +382,7 @@ export const datasourcePlugin = { angularDetected: false, isFullyInstalled: true, latestVersion: '1.20.0', + insights: { id: 2, name: 'grafana-redshift-datasource', version: '1.20.0', insights: [] }, details: { grafanaDependency: '>=8.0.0', pluginDependencies: [], diff --git a/public/app/features/plugins/admin/mocks/mockHelpers.ts b/public/app/features/plugins/admin/mocks/mockHelpers.ts index 6034e8860e9..d6e04186f77 100644 --- a/public/app/features/plugins/admin/mocks/mockHelpers.ts +++ b/public/app/features/plugins/admin/mocks/mockHelpers.ts @@ -31,6 +31,9 @@ export const getPluginsStateMock = (plugins: CatalogPlugin[] = []): ReducerState 'plugins/fetchDetails': { status: RequestStatus.Fulfilled, }, + 'plugins/fetchPluginInsights': { + status: RequestStatus.Fulfilled, + }, }, // Backward compatibility plugins: [], @@ -75,6 +78,11 @@ export const mockPluginApis = ({ return Promise.resolve({ items: versions }); } + // Mock plugin insights - return empty insights to avoid API call errors + if (path.includes('/insights')) { + return Promise.resolve({ id: 1, name: '', version: '', insights: [] }); + } + // Mock local plugin settings (installed) if necessary if (local && path === `${API_ROOT}/${local.id}/settings`) { return Promise.resolve(local); diff --git a/public/app/features/plugins/admin/state/actions.ts b/public/app/features/plugins/admin/state/actions.ts index 6be68111dd5..e9cf2d9d40d 100644 --- a/public/app/features/plugins/admin/state/actions.ts +++ b/public/app/features/plugins/admin/state/actions.ts @@ -13,6 +13,7 @@ import { getPluginErrors, getLocalPlugins, getPluginDetails, + getPluginInsights, installPlugin, uninstallPlugin, getInstancePlugins, @@ -165,6 +166,22 @@ export const fetchDetails = createAsyncThunk, stri } ); +export const fetchPluginInsights = createAsyncThunk, { id: string; version?: string }>( + `${STATE_PREFIX}/fetchPluginInsights`, + async ({ id, version }, thunkApi) => { + try { + const insights = await getPluginInsights(id, version); + + return { + id, + changes: { insights }, + }; + } catch (e) { + return thunkApi.rejectWithValue('Unknown error.'); + } + } +); + export const addPlugins = createAction(`${STATE_PREFIX}/addPlugins`); // 1. gets remote equivalents from the store (if there are any) @@ -265,7 +282,8 @@ export const panelPluginLoaded = createAction(`${STATE_PREFIX}/pane // TODO export const loadPanelPlugin = (id: string): ThunkResult> => { return async (dispatch, getStore) => { - let plugin = getStore().plugins.panels[id]; + const state = getStore(); + let plugin = state.plugins.panels[id]; if (!plugin) { plugin = await importPanelPlugin(id); diff --git a/public/app/features/plugins/admin/state/hooks.ts b/public/app/features/plugins/admin/state/hooks.ts index 2185ec99465..6eb47d7e1aa 100644 --- a/public/app/features/plugins/admin/state/hooks.ts +++ b/public/app/features/plugins/admin/state/hooks.ts @@ -6,7 +6,16 @@ import { useDispatch, useSelector } from 'app/types/store'; import { sortPlugins, Sorters, isPluginUpdatable } from '../helpers'; import { CatalogPlugin, PluginStatus } from '../types'; -import { fetchAll, fetchDetails, fetchRemotePlugins, install, uninstall, fetchAllLocal, unsetInstall } from './actions'; +import { + fetchAll, + fetchDetails, + fetchRemotePlugins, + install, + uninstall, + fetchAllLocal, + unsetInstall, + fetchPluginInsights, +} from './actions'; import { selectPlugins, selectById, @@ -44,13 +53,18 @@ export const useGetUpdatable = () => { }; }; -export const useGetSingle = (id: string): CatalogPlugin | undefined => { +export const useGetSingle = (id: string, version?: string): CatalogPlugin | undefined => { useFetchAll(); useFetchDetails(id); return useSelector((state) => selectById(state, id)); }; +export const useGetPluginInsights = (id: string, version: string | undefined): CatalogPlugin | undefined => { + useFetchPluginInsights(id, version); + return useSelector((state) => selectById(state, id)); +}; + export const useGetSingleLocalWithoutDetails = (id: string): CatalogPlugin | undefined => { useFetchAllLocal(); return useSelector((state) => selectById(state, id)); @@ -153,6 +167,17 @@ export const useFetchDetails = (id: string) => { }, [plugin]); // eslint-disable-line }; +export const useFetchPluginInsights = (id: string, version: string | undefined) => { + const dispatch = useDispatch(); + const plugin = useSelector((state) => selectById(state, id)); + const isNotFetching = !useSelector(selectIsRequestPending(fetchPluginInsights.typePrefix)); + const shouldFetch = isNotFetching && plugin && !plugin.insights && version; + + useEffect(() => { + shouldFetch && dispatch(fetchPluginInsights({ id, version })); + }, [plugin, version]); // eslint-disable-line +}; + export const useFetchDetailsLazy = () => { const dispatch = useDispatch(); diff --git a/public/app/features/plugins/admin/state/reducer.ts b/public/app/features/plugins/admin/state/reducer.ts index f2414a31405..e3d5bec5427 100644 --- a/public/app/features/plugins/admin/state/reducer.ts +++ b/public/app/features/plugins/admin/state/reducer.ts @@ -7,6 +7,7 @@ import { CatalogPlugin, ReducerState, RequestStatus } from '../types'; import { fetchDetails, + fetchPluginInsights, install, uninstall, loadPluginDashboards, @@ -63,6 +64,10 @@ const slice = createSlice({ .addCase(fetchDetails.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); }) + // Fetch Plugin Insights + .addCase(fetchPluginInsights.fulfilled, (state, action) => { + pluginsAdapter.updateOne(state.items, action.payload); + }) // Install .addCase(install.fulfilled, (state, action) => { pluginsAdapter.updateOne(state.items, action.payload); diff --git a/public/app/features/plugins/admin/types.ts b/public/app/features/plugins/admin/types.ts index 3cc66bba0b9..df4114101b4 100644 --- a/public/app/features/plugins/admin/types.ts +++ b/public/app/features/plugins/admin/types.ts @@ -55,6 +55,7 @@ export interface CatalogPlugin extends WithAccessControlMetadata { updatedAt: string; installedVersion?: string; details?: CatalogPluginDetails; + insights?: CatalogPluginInsights; error?: PluginErrorCode; angularDetected?: boolean; // instance plugins may not be fully installed, which means a new instance @@ -90,6 +91,54 @@ export interface CatalogPluginDetails { screenshots?: Screenshots[] | null; } +export type InsightLevel = 'ok' | 'warning' | 'danger' | 'good' | 'info'; + +export const SCORE_LEVELS = { + EXCELLENT: 'Excellent', + GOOD: 'Good', + FAIR: 'Fair', + POOR: 'Poor', + CRITICAL: 'Critical', +} as const; + +export type ScoreLevel = (typeof SCORE_LEVELS)[keyof typeof SCORE_LEVELS]; + +export const INSIGHT_CATEGORIES = { + SECURITY: 'security', + QUALITY: 'quality', + PERFORMANCE: 'performance', +} as const; + +export const INSIGHT_LEVELS = { + GOOD: 'good', + OK: 'ok', + WARNING: 'warning', + DANGER: 'danger', + INFO: 'info', +} as const; + +export interface InsightItem { + id: string; + name: string; + description?: string; + level: InsightLevel; + link?: string; +} + +export interface InsightCategory { + name: string; + items: InsightItem[]; + scoreValue: number; + scoreLevel: ScoreLevel; +} + +export interface CatalogPluginInsights { + id: number; + name: string; + version: string; + insights: InsightCategory[]; +} + export interface CatalogPluginInfo { logos: { large: string; small: string }; keywords: string[]; diff --git a/public/app/features/plugins/extensions/usePluginComponents.tsx b/public/app/features/plugins/extensions/usePluginComponents.tsx index c800bf08a31..c7f5b40815f 100644 --- a/public/app/features/plugins/extensions/usePluginComponents.tsx +++ b/public/app/features/plugins/extensions/usePluginComponents.tsx @@ -67,21 +67,15 @@ export function createComponentWithMeta( ): ComponentTypeWithExtensionMeta { const { component: Component, ...config } = registryItem; - function ComponentWithMeta(props: Props) { - return ; - } - - ComponentWithMeta.displayName = Component.displayName; - ComponentWithMeta.defaultProps = Component.defaultProps; - ComponentWithMeta.propTypes = Component.propTypes; - ComponentWithMeta.contextTypes = Component.contextTypes; - ComponentWithMeta.meta = { - pluginId: config.pluginId, - title: config.title ?? '', - description: config.description ?? '', - id: generateExtensionId(config.pluginId, extensionPointId, config.title), - type: PluginExtensionTypes.component, - } satisfies PluginExtensionComponentMeta; + const ComponentWithMeta: ComponentTypeWithExtensionMeta = Object.assign(Component, { + meta: { + pluginId: config.pluginId, + title: config.title ?? '', + description: config.description ?? '', + id: generateExtensionId(config.pluginId, extensionPointId, config.title), + type: PluginExtensionTypes.component, + } satisfies PluginExtensionComponentMeta, + }); return ComponentWithMeta; } diff --git a/public/app/features/plugins/sandbox/utils.ts b/public/app/features/plugins/sandbox/utils.ts index 9a411a32a3e..9a9edbc994d 100644 --- a/public/app/features/plugins/sandbox/utils.ts +++ b/public/app/features/plugins/sandbox/utils.ts @@ -78,11 +78,36 @@ export function unboxNearMembraneProxies(structure: unknown): unknown { if (Array.isArray(structure)) { return structure.map(unboxNearMembraneProxies); } + + if (isTransferable(structure)) { + return structure; + } + if (typeof structure === 'object') { return Object.keys(structure).reduce((acc, key) => { Reflect.set(acc, key, unboxNearMembraneProxies(Reflect.get(structure, key))); return acc; }, {}); } + return structure; } + +function isTransferable(structure: unknown): structure is Transferable { + // We should probably add all of the transferable types here. + // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects + return ( + structure instanceof ArrayBuffer || + structure instanceof OffscreenCanvas || + structure instanceof ImageBitmap || + structure instanceof MessagePort || + structure instanceof MediaSourceHandle || + structure instanceof ReadableStream || + structure instanceof WritableStream || + structure instanceof TransformStream || + structure instanceof AudioData || + structure instanceof VideoFrame || + structure instanceof RTCDataChannel || + structure instanceof ArrayBuffer + ); +} diff --git a/public/app/features/provisioning/GettingStarted/GettingStarted.tsx b/public/app/features/provisioning/GettingStarted/GettingStarted.tsx index d38c19c9fd5..888f48a26f0 100644 --- a/public/app/features/provisioning/GettingStarted/GettingStarted.tsx +++ b/public/app/features/provisioning/GettingStarted/GettingStarted.tsx @@ -22,7 +22,6 @@ const featureIni = `# In your custom.ini file [feature_toggles] provisioning = true -kubernetesDashboards = true ; use k8s from browser `; const ngrokExample = `ngrok http 3000 @@ -103,7 +102,7 @@ const getModalContent = (setupType: SetupType) => { ), description: t( 'provisioning.getting-started.step-description-enable-feature-toggles', - 'Add these settings to your custom.ini file to enable necessary features:' + 'Add the provisioning feature toggle to your custom.ini file. Note: kubernetesDashboards is enabled by default, but if you have explicitly disabled it, you will need to enable it in your Grafana settings or remove the override from your configuration.' ), code: featureIni, }, diff --git a/public/app/features/provisioning/GettingStarted/GettingStartedPage.tsx b/public/app/features/provisioning/GettingStarted/GettingStartedPage.tsx index adaf68a80ee..0235ae86e92 100644 --- a/public/app/features/provisioning/GettingStarted/GettingStartedPage.tsx +++ b/public/app/features/provisioning/GettingStarted/GettingStartedPage.tsx @@ -15,13 +15,10 @@ export default function GettingStartedPage({ items }: Props) { return ( diff --git a/public/app/features/provisioning/Job/JobSummary.tsx b/public/app/features/provisioning/Job/JobSummary.tsx index 0f9ba17db08..0dfecd9a616 100644 --- a/public/app/features/provisioning/Job/JobSummary.tsx +++ b/public/app/features/provisioning/Job/JobSummary.tsx @@ -33,6 +33,11 @@ const getSummaryColumns = () => [ header: 'Unchanged', cell: ({ row: { original: item } }: SummaryCell) => item.noop?.toString() || '-', }, + { + id: 'warnings', + header: 'Warnings', + cell: ({ row: { original: item } }: SummaryCell) => item.warning?.toString() || '-', + }, { id: 'errors', header: 'Errors', diff --git a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboard.tsx b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboard.tsx index fca774ef84c..5c3679ad795 100644 --- a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboard.tsx +++ b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboard.tsx @@ -10,10 +10,14 @@ export interface SaveProvisionedDashboardProps { dashboard: DashboardScene; drawer: SaveDashboardDrawer; changeInfo: DashboardChangeInfo; + saveAsCopy?: boolean; } -export function SaveProvisionedDashboard({ drawer, changeInfo, dashboard }: SaveProvisionedDashboardProps) { - const { isNew, defaultValues, workflowOptions, readOnly, repository } = useProvisionedDashboardData(dashboard); +export function SaveProvisionedDashboard({ drawer, changeInfo, dashboard, saveAsCopy }: SaveProvisionedDashboardProps) { + const { isNew, defaultValues, workflowOptions, readOnly, repository } = useProvisionedDashboardData( + dashboard, + saveAsCopy + ); if (!defaultValues) { return null; @@ -24,11 +28,12 @@ export function SaveProvisionedDashboard({ drawer, changeInfo, dashboard }: Save dashboard={dashboard} drawer={drawer} changeInfo={changeInfo} - isNew={isNew} + isNew={isNew || !!saveAsCopy} defaultValues={defaultValues} repository={repository} workflowOptions={workflowOptions} readOnly={readOnly} + saveAsCopy={saveAsCopy} /> ); } diff --git a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx index effa2e5c0e7..219bb521111 100644 --- a/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx +++ b/public/app/features/provisioning/components/Dashboards/SaveProvisionedDashboardForm.tsx @@ -6,7 +6,7 @@ import { AppEvents, locationUtil } from '@grafana/data'; import { Trans, t } from '@grafana/i18n'; import { getAppEvents, locationService, reportInteraction } from '@grafana/runtime'; import { Dashboard } from '@grafana/schema'; -import { Button, Field, Input, Stack, TextArea } from '@grafana/ui'; +import { Button, Field, Input, Stack, TextArea, Switch } from '@grafana/ui'; import { RepositoryView, Unstructured } from 'app/api/clients/provisioning/v0alpha1'; import kbn from 'app/core/utils/kbn'; import { Resource } from 'app/features/apiserver/types'; @@ -47,6 +47,7 @@ export function SaveProvisionedDashboardForm({ workflowOptions, readOnly, repository, + saveAsCopy, }: Props) { const navigate = useNavigate(); const appEvents = getAppEvents(); @@ -166,7 +167,15 @@ export function SaveProvisionedDashboardForm({ }); // Submit handler for saving the form data - const handleFormSubmit = async ({ title, description, repo, path, comment, ref }: ProvisionedDashboardFormData) => { + const handleFormSubmit = async ({ + title, + description, + repo, + path, + comment, + ref, + copyTags, + }: ProvisionedDashboardFormData) => { // Validate required fields if (!repo || !path) { console.error('Missing required fields for saving:', { repo, path }); @@ -185,7 +194,8 @@ export function SaveProvisionedDashboardForm({ isNew, title, description, - copyTags: true, + copyTags, + saveAsCopy, }); reportInteraction('grafana_provisioning_dashboard_save_submitted', { @@ -287,6 +297,12 @@ export function SaveProvisionedDashboardForm({ isNew={isNew} /> + {saveAsCopy && ( + + + + )} + - {folder.subScopeName && ( + {folder.subScopeName && !folder.disableSubScopeSelection && ( { + onClick={async (e) => { e.preventDefault(); e.stopPropagation(); if (folder.subScopeName && scopesSelectorService) { - scopesDashboardsService?.setNavigationScope(undefined, [folder.subScopeName]); - scopesSelectorService.changeScopes([folder.subScopeName]); + const activeSubScopePath = scopesDashboardsService?.state.navScopePath; + // Check if the active scope is a child of the current folder's scope + const activeScope = activeSubScopePath?.[activeSubScopePath.length - 1]; + const folderLocationInActivePath = activeSubScopePath?.indexOf(folder.subScopeName) ?? -1; + + await scopesDashboardsService?.setNavigationScope( + folderLocationInActivePath >= 0 ? folder.subScopeName : undefined, + undefined, + activeSubScopePath?.slice(folderLocationInActivePath + 1) ?? [] + ); + // Now changeScopes will skip fetchDashboards because navigationScope is set + scopesSelectorService.changeScopes( + folderLocationInActivePath >= 0 && activeScope ? [activeScope] : [folder.subScopeName], + undefined, + undefined, + false + ); } }} /> @@ -68,6 +85,7 @@ export function ScopesDashboardsTreeFolderItem({ {folder.expanded && (
    setInputState({ value, dirty: true })} /> +
    ); } @@ -49,6 +52,8 @@ export function ScopesDashboardsTreeSearch({ disabled, query, onChange }: Scopes const getStyles = (theme: GrafanaTheme2) => { return { container: css({ + display: 'flex', + gap: theme.spacing(1), flex: '0 1 auto', }), }; diff --git a/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.test.tsx b/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.test.tsx index 8dafc80c612..b697f69ab05 100644 --- a/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.test.tsx +++ b/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.test.tsx @@ -209,7 +209,7 @@ describe('ScopesNavigationTreeLink', () => { const link = screen.getByTestId('scopes-dashboards-test-id'); await userEvent.click(link); - expect(mockScopesDashboardsService.setNavigationScope).toHaveBeenCalledWith('currentScope'); + expect(mockScopesDashboardsService.setNavigationScope).toHaveBeenCalledWith('currentScope', undefined, undefined); }); it('should not set navigation scope when already set', async () => { diff --git a/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.tsx b/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.tsx index b7722edcf8c..67b1649ee3c 100644 --- a/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.tsx +++ b/public/app/features/scopes/dashboards/ScopesNavigationTreeLink.tsx @@ -8,16 +8,17 @@ import { Icon, useStyles2 } from '@grafana/ui'; import { useScopesServices } from '../ScopesContextProvider'; -import { isCurrentPath, normalizePath } from './scopeNavgiationUtils'; +import { isCurrentPath, normalizePath, serializeFolderPath } from './scopeNavgiationUtils'; export interface ScopesNavigationTreeLinkProps { subScope?: string; to: string; title: string; id: string; + subScopePath?: string[]; } -export function ScopesNavigationTreeLink({ subScope, to, title, id }: ScopesNavigationTreeLinkProps) { +export function ScopesNavigationTreeLink({ subScope, to, title, id, subScopePath }: ScopesNavigationTreeLinkProps) { const styles = useStyles2(getStyles); const linkIcon = useMemo(() => getLinkIcon(to), [to]); const locPathname = useLocation().pathname; @@ -25,7 +26,7 @@ export function ScopesNavigationTreeLink({ subScope, to, title, id }: ScopesNavi // Ignore query params const isCurrent = isCurrentPath(locPathname, to); - const handleClick = (e: React.MouseEvent) => { + const handleClick = async (e: React.MouseEvent) => { if (subScope) { e.preventDefault(); // Prevent default Link navigation @@ -39,11 +40,18 @@ export function ScopesNavigationTreeLink({ subScope, to, title, id }: ScopesNavi const searchParams = new URLSearchParams(url.search); if (!currentNavigationScope && currentScope) { searchParams.set('navigation_scope', currentScope); - services?.scopesDashboardsService?.setNavigationScope(currentScope); + await services?.scopesDashboardsService?.setNavigationScope( + currentScope, + undefined, + subScopePath && subScopePath.length > 0 ? subScopePath : undefined + ); } // Update query params with the new subScope searchParams.set('scopes', subScope); + + // Set nav_scope_path to the subScopePath + searchParams.set('nav_scope_path', subScopePath ? serializeFolderPath(subScopePath) : ''); // Remove scope_node and scope_parent since we're changing to a subScope searchParams.delete('scope_node'); searchParams.delete('scope_parent'); diff --git a/public/app/features/scopes/dashboards/scopeNavgiationUtils.test.ts b/public/app/features/scopes/dashboards/scopeNavgiationUtils.test.ts index ec927a3dc92..bd441b6088b 100644 --- a/public/app/features/scopes/dashboards/scopeNavgiationUtils.test.ts +++ b/public/app/features/scopes/dashboards/scopeNavgiationUtils.test.ts @@ -1,4 +1,11 @@ -import { getDashboardPathForComparison, isCurrentPath } from './scopeNavgiationUtils'; +import { + buildSubScopePath, + deserializeFolderPath, + getDashboardPathForComparison, + isCurrentPath, + serializeFolderPath, +} from './scopeNavgiationUtils'; +import { SuggestedNavigationsFoldersMap } from './types'; describe('scopeNavgiationUtils', () => { it('should return the correct path for a dashboard', () => { @@ -28,4 +35,194 @@ describe('scopeNavgiationUtils', () => { expect(isCurrentPath('/d/dashboardId/slug', '/d/dashboardId#hash')).toBe(true); expect(isCurrentPath('/d/dashboardId', '/d/dashboardId#hash')).toBe(true); }); + + describe('deserializeFolderPath', () => { + it('should return empty array for empty string', () => { + expect(deserializeFolderPath('')).toEqual([]); + }); + + it('should parse a simple comma-separated string', () => { + expect(deserializeFolderPath('mimir,loki')).toEqual(['mimir', 'loki']); + }); + + it('should handle single value', () => { + expect(deserializeFolderPath('mimir')).toEqual(['mimir']); + }); + + it('should trim whitespace around values', () => { + expect(deserializeFolderPath(' mimir , loki ')).toEqual(['mimir', 'loki']); + }); + + it('should handle URL-encoded strings', () => { + expect(deserializeFolderPath(encodeURIComponent('mimir,loki'))).toEqual(['mimir', 'loki']); + }); + + it('should handle URL-encoded strings with special characters', () => { + expect(deserializeFolderPath(encodeURIComponent('folder one,folder two'))).toEqual(['folder one', 'folder two']); + }); + + it('should fallback to split without decoding if decodeURIComponent fails', () => { + // Invalid URI sequence that would cause decodeURIComponent to throw + const invalidUri = '%E0%A4%A'; + expect(deserializeFolderPath(invalidUri)).toEqual(['%E0%A4%A']); + }); + }); + + describe('serializeFolderPath', () => { + it('should return empty string for empty array', () => { + expect(serializeFolderPath([])).toBe(''); + }); + + it('should serialize a simple array', () => { + expect(serializeFolderPath(['mimir', 'loki'])).toBe(encodeURIComponent('mimir,loki')); + }); + + it('should handle single value', () => { + expect(serializeFolderPath(['mimir'])).toBe('mimir'); + }); + + it('should handle values with spaces', () => { + expect(serializeFolderPath(['folder one', 'folder two'])).toBe(encodeURIComponent('folder one,folder two')); + }); + + it('should return empty string for null/undefined input', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(serializeFolderPath(null as any)).toBe(''); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(serializeFolderPath(undefined as any)).toBe(''); + }); + }); + + describe('serializeFolderPath and deserializeFolderPath round-trip', () => { + it('should round-trip simple paths', () => { + const original = ['mimir', 'loki']; + const serialized = serializeFolderPath(original); + const deserialized = deserializeFolderPath(serialized); + expect(deserialized).toEqual(original); + }); + + it('should round-trip paths with spaces', () => { + const original = ['folder one', 'folder two']; + const serialized = serializeFolderPath(original); + const deserialized = deserializeFolderPath(serialized); + expect(deserialized).toEqual(original); + }); + }); + + describe('buildSubScopePath', () => { + it('should return undefined when folders is empty', () => { + const folders: SuggestedNavigationsFoldersMap = {}; + expect(buildSubScopePath('mimir', folders)).toBeUndefined(); + }); + + it('should find subScope at root level', () => { + const folders: SuggestedNavigationsFoldersMap = { + 'Mimir Dashboards': { + title: 'Mimir Dashboards', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'mimir', + }, + }; + expect(buildSubScopePath('mimir', folders)).toEqual(['Mimir Dashboards']); + }); + + it('should find subScope in nested folders', () => { + const folders: SuggestedNavigationsFoldersMap = { + '': { + title: '', + expanded: true, + folders: { + 'Parent Folder': { + title: 'Parent Folder', + expanded: false, + folders: { + 'Mimir Dashboards': { + title: 'Mimir Dashboards', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'mimir', + }, + }, + suggestedNavigations: {}, + }, + }, + suggestedNavigations: {}, + }, + }; + expect(buildSubScopePath('mimir', folders)).toEqual(['', 'Parent Folder', 'Mimir Dashboards']); + }); + + it('should return undefined when subScope is not found', () => { + const folders: SuggestedNavigationsFoldersMap = { + '': { + title: '', + expanded: true, + folders: { + 'Loki Dashboards': { + title: 'Loki Dashboards', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'loki', + }, + }, + suggestedNavigations: {}, + }, + }; + expect(buildSubScopePath('mimir', folders)).toBeUndefined(); + }); + + it('should return first match when multiple folders have the same subScope', () => { + const folders: SuggestedNavigationsFoldersMap = { + 'Mimir Dashboards': { + title: 'Mimir Dashboards', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'mimir', + }, + 'Mimir Overview': { + title: 'Mimir Overview', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'mimir', + }, + }; + // Should return the first one found (order depends on Object.entries) + const result = buildSubScopePath('mimir', folders); + expect(result).toBeDefined(); + expect(result?.length).toBe(1); + }); + + it('should find deeply nested subScope', () => { + const folders: SuggestedNavigationsFoldersMap = { + level1: { + title: 'Level 1', + expanded: true, + folders: { + level2: { + title: 'Level 2', + expanded: true, + folders: { + level3: { + title: 'Level 3', + expanded: false, + folders: {}, + suggestedNavigations: {}, + subScopeName: 'deep-scope', + }, + }, + suggestedNavigations: {}, + }, + }, + suggestedNavigations: {}, + }, + }; + expect(buildSubScopePath('deep-scope', folders)).toEqual(['level1', 'level2', 'level3']); + }); + }); }); diff --git a/public/app/features/scopes/dashboards/scopeNavgiationUtils.ts b/public/app/features/scopes/dashboards/scopeNavgiationUtils.ts index fe6d458a312..9fa4e2e05c7 100644 --- a/public/app/features/scopes/dashboards/scopeNavgiationUtils.ts +++ b/public/app/features/scopes/dashboards/scopeNavgiationUtils.ts @@ -1,3 +1,5 @@ +import { SuggestedNavigationsFoldersMap } from './types'; + // Helper function to get the base path for a dashboard URL for comparison purposes. // e.g., /d/dashboardId/slug -> /d/dashboardId // /d/dashboardId -> /d/dashboardId @@ -5,12 +7,63 @@ export function getDashboardPathForComparison(pathname: string): string { return pathname.split('/').slice(0, 3).join('/'); } +/** + * Finds the path to a folder with the given subScopeName by searching recursively. + * @param subScope - The subScope name to find + * @param folders - The root folder structure to search + * @returns Array representing the path to the folder, or undefined if not found + */ +export function buildSubScopePath(subScope: string, folders: SuggestedNavigationsFoldersMap): string[] | undefined { + function findPath(currentFolders: SuggestedNavigationsFoldersMap, currentPath: string[]): string[] | undefined { + for (const [key, folder] of Object.entries(currentFolders)) { + const newPath = [...currentPath, key]; + if (folder.subScopeName === subScope) { + return newPath; + } + // Search in nested folders + const nestedPath = findPath(folder.folders, newPath); + if (nestedPath) { + return nestedPath; + } + } + return undefined; + } + + return findPath(folders, []); +} + export function normalizePath(path: string): string { // Remove query + hash + trailing slash (except root) const noQuery = path.split('?')[0].split('#')[0]; return noQuery !== '/' && noQuery.endsWith('/') ? noQuery.slice(0, -1) : noQuery; } +/** + * Deserializes a comma-separated folder path string into an array. + * Handles URL-encoded strings. + */ +export function deserializeFolderPath(navScopePath: string): string[] { + if (!navScopePath) { + return []; + } + try { + const decoded = decodeURIComponent(navScopePath); + return decoded.split(',').map((s) => s.trim()); + } catch { + return navScopePath.split(',').map((s) => s.trim()); + } +} + +/** + * Serializes a folder path array into a comma-separated string. + */ +export function serializeFolderPath(path: string[]): string { + if (!path) { + return ''; + } + return encodeURIComponent(path.join(',')); +} + // Pathname comes from location.pathname export function isCurrentPath(pathname: string, to: string): boolean { const isDashboard = to.startsWith('/d/'); diff --git a/public/app/features/scopes/dashboards/types.ts b/public/app/features/scopes/dashboards/types.ts index 18ee90296e6..2dcec3b70a0 100644 --- a/public/app/features/scopes/dashboards/types.ts +++ b/public/app/features/scopes/dashboards/types.ts @@ -5,6 +5,9 @@ export interface ScopeNavigationSpec { url: string; scope: string; subScope?: string; + preLoadSubScopeChildren?: boolean; + expandOnLoad?: boolean; + disableSubScopeSelection?: boolean; } export interface ScopeNavigationStatus { @@ -40,6 +43,8 @@ export interface SuggestedNavigationsFolder { suggestedNavigations: SuggestedNavigationsMap; subScopeName?: string; loading?: boolean; + disableSubScopeSelection?: boolean; + preLoadSubScopeChildren?: boolean; } export type SuggestedNavigationsFoldersMap = Record; diff --git a/public/app/features/scopes/selector/ScopesSelector.tsx b/public/app/features/scopes/selector/ScopesSelector.tsx index bc89c748814..8c67fa202de 100644 --- a/public/app/features/scopes/selector/ScopesSelector.tsx +++ b/public/app/features/scopes/selector/ScopesSelector.tsx @@ -6,7 +6,7 @@ import { Observable } from 'rxjs'; import { GrafanaTheme2 } from '@grafana/data'; import { Trans, t } from '@grafana/i18n'; import { useScopes } from '@grafana/runtime'; -import { Button, Drawer, ErrorBoundary, ErrorWithStack, IconButton, Spinner, Text, useStyles2 } from '@grafana/ui'; +import { Button, Drawer, ErrorBoundary, ErrorWithStack, Spinner, Text, useStyles2 } from '@grafana/ui'; import { getModKey } from 'app/core/utils/browser'; import { useScopesServices } from '../ScopesContextProvider'; @@ -54,8 +54,8 @@ export const ScopesSelector = () => { tree, scopes: scopesMap, } = selectorServiceState; - const { scopesService, scopesSelectorService, scopesDashboardsService } = services; - const { readOnly, drawerOpened, loading } = scopes.state; + const { scopesService, scopesSelectorService } = services; + const { readOnly, loading } = scopes.state; const { open, removeAllScopes, @@ -70,24 +70,8 @@ export const ScopesSelector = () => { const recentScopes = getRecentScopes(); - const dashboardsIconLabel = readOnly - ? t('scopes.dashboards.toggle.disabled', 'Suggested dashboards list is disabled due to read only mode') - : drawerOpened - ? t('scopes.dashboards.toggle.collapse', 'Collapse suggested dashboards list') - : t('scopes.dashboards.toggle.expand', 'Expand suggested dashboards list'); - return ( <> - - { await service.selectScope('test-scope-node'); await service.apply(); await service.removeAllScopes(); - expect(dashboardsService.setNavigationScope).toHaveBeenCalledWith(undefined); + expect(dashboardsService.setNavigationScope).toHaveBeenCalledWith(undefined, undefined, undefined); }); }); diff --git a/public/app/features/scopes/selector/ScopesSelectorService.ts b/public/app/features/scopes/selector/ScopesSelectorService.ts index 17f36639f59..abd837c7fb7 100644 --- a/public/app/features/scopes/selector/ScopesSelectorService.ts +++ b/public/app/features/scopes/selector/ScopesSelectorService.ts @@ -372,13 +372,7 @@ export class ScopesSelectorService extends ScopesServiceBase { - // Check if the selected scope has a redirect path - if (scopeNode && scopeNode.spec.redirectPath && typeof scopeNode.spec.redirectPath === 'string') { - locationService.push(scopeNode.spec.redirectPath); - return; - } - - // Redirect to first scopeNavigation if current URL isn't a scopeNavigation + // Check if we are currently on an active scope navigation const currentPath = locationService.getLocation().pathname; const activeScopeNavigation = this.dashboardsService.state.scopeNavigations.find((s) => { if (!('url' in s.spec) || typeof s.spec.url !== 'string') { @@ -387,6 +381,20 @@ export class ScopesSelectorService extends ScopesServiceBase 0) { // Redirect to the first available scopeNavigation const firstScopeNavigation = this.dashboardsService.state.scopeNavigations[0]; @@ -396,7 +404,9 @@ export class ScopesSelectorService extends ScopesServiceBase { this.applyScopes([], false); - this.dashboardsService.setNavigationScope(undefined); + this.dashboardsService.setNavigationScope(undefined, undefined, undefined); }; private addRecentScopes = (scopes: Scope[], parentNode?: ScopeNode, scopeNodeId?: string) => { diff --git a/public/app/features/scopes/selector/ScopesTree.test.tsx b/public/app/features/scopes/selector/ScopesTree.test.tsx new file mode 100644 index 00000000000..2ac4b647a5c --- /dev/null +++ b/public/app/features/scopes/selector/ScopesTree.test.tsx @@ -0,0 +1,248 @@ +import { render, screen } from '@testing-library/react'; + +import { ScopeNode } from '@grafana/data'; + +import { ScopesTree } from './ScopesTree'; +import { NodesMap, SelectedScope, TreeNode } from './types'; + +// Mock the ScopesContextProvider hook since it requires a full context setup +jest.mock('../ScopesContextProvider', () => ({ + useScopesServices: () => ({ + scopesSelectorService: { + closeAndApply: jest.fn(), + }, + }), +})); + +describe('ScopesTree', () => { + const mockFilterNode = jest.fn(); + const mockSelectScope = jest.fn(); + const mockDeselectScope = jest.fn(); + const mockToggleExpandedNode = jest.fn(); + + const createMockScopeNode = (name: string, parentName?: string): ScopeNode => ({ + metadata: { name }, + spec: { + title: `Title ${name}`, + nodeType: 'leaf', + linkType: 'scope', + linkId: `scope-${name}`, + parentName: parentName ?? '', + }, + }); + + const defaultScopeNodes: NodesMap = { + 'parent-container': { + metadata: { name: 'parent-container' }, + spec: { + title: 'Parent Container', + nodeType: 'container', + parentName: '', + }, + }, + 'child-1': createMockScopeNode('child-1', 'parent-container'), + 'child-2': createMockScopeNode('child-2', 'parent-container'), + }; + + const defaultTree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: { + 'child-1': { scopeNodeId: 'child-1', expanded: false, query: '' }, + 'child-2': { scopeNodeId: 'child-2', expanded: false, query: '' }, + }, + childrenLoaded: true, + }; + + const defaultProps = { + tree: defaultTree, + loadingNodeName: undefined, + selectedScopes: [] as SelectedScope[], + scopeNodes: defaultScopeNodes, + filterNode: mockFilterNode, + selectScope: mockSelectScope, + deselectScope: mockDeselectScope, + toggleExpandedNode: mockToggleExpandedNode, + }; + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('selectedNodesToShow logic', () => { + it('should not show selectedNodesToShow when no scopes are selected', () => { + render(); + + // Both child-1 and child-2 should be visible in the regular children list + expect(screen.getByText('Title child-1')).toBeInTheDocument(); + expect(screen.getByText('Title child-2')).toBeInTheDocument(); + }); + + it('should only consider first selected scope for selectedNodesToShow', () => { + const selectedScopes: SelectedScope[] = [ + { scopeId: 'scope-1', scopeNodeId: 'child-1' }, + { scopeId: 'scope-2', scopeNodeId: 'child-2' }, + ]; + + // Use a tree where child-1 is NOT in the children (to trigger selectedNodesToShow) + const tree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: { + // child-1 is NOT here, so it should appear in selectedNodesToShow + 'child-2': { scopeNodeId: 'child-2', expanded: false, query: '' }, + }, + childrenLoaded: true, + }; + + render(); + + // child-1 should be shown (from selectedNodesToShow - only first scope is considered) + expect(screen.getByText('Title child-1')).toBeInTheDocument(); + // child-2 should also be shown (from regular children) + expect(screen.getByText('Title child-2')).toBeInTheDocument(); + }); + + it('should not show selectedNodesToShow when first scope has no scopeNodeId', () => { + const selectedScopes: SelectedScope[] = [ + { scopeId: 'scope-1', scopeNodeId: undefined }, // No scopeNodeId + { scopeId: 'scope-2', scopeNodeId: 'child-2' }, + ]; + + // Tree with no children to make it obvious if selectedNodesToShow is populated + const tree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: {}, + childrenLoaded: true, + }; + + render(); + + // child-2 should NOT appear because only first scope is considered and it has no scopeNodeId + expect(screen.queryByText('Title child-2')).not.toBeInTheDocument(); + }); + + it('should not show selectedNodesToShow when first scope node is not in scopeNodes cache', () => { + const selectedScopes: SelectedScope[] = [ + { scopeId: 'scope-1', scopeNodeId: 'missing-node' }, // Node not in scopeNodes + { scopeId: 'scope-2', scopeNodeId: 'child-2' }, + ]; + + // Tree with no children + const tree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: {}, + childrenLoaded: true, + }; + + render(); + + // Neither should appear since first scope's node is missing from cache + expect(screen.queryByText('Title missing-node')).not.toBeInTheDocument(); + expect(screen.queryByText('Title child-2')).not.toBeInTheDocument(); + }); + + it('should not show selectedNodesToShow when tree scopeNodeId does not match first scope parent', () => { + const selectedScopes: SelectedScope[] = [ + { scopeId: 'scope-1', scopeNodeId: 'child-1' }, // child-1's parent is 'parent-container' + ]; + + // Tree with different scopeNodeId + const tree: TreeNode = { + scopeNodeId: 'different-container', // Different from child-1's parent + expanded: true, + query: '', + children: {}, + childrenLoaded: true, + }; + + const scopeNodes: NodesMap = { + ...defaultScopeNodes, + 'different-container': { + metadata: { name: 'different-container' }, + spec: { title: 'Different', nodeType: 'container', parentName: '' }, + }, + }; + + render(); + + // child-1 should NOT appear since tree's scopeNodeId doesn't match child-1's parent + expect(screen.queryByText('Title child-1')).not.toBeInTheDocument(); + }); + + it('should not duplicate scope in selectedNodesToShow if already in children', () => { + const selectedScopes: SelectedScope[] = [{ scopeId: 'scope-1', scopeNodeId: 'child-1' }]; + + // Tree already has child-1 in children + const tree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: { + 'child-1': { scopeNodeId: 'child-1', expanded: false, query: '' }, + 'child-2': { scopeNodeId: 'child-2', expanded: false, query: '' }, + }, + childrenLoaded: true, + }; + + render(); + + // child-1 should appear exactly once (in regular children, not duplicated) + const child1Elements = screen.getAllByText('Title child-1'); + expect(child1Elements).toHaveLength(1); + }); + }); + + describe('graceful handling of missing data', () => { + it('should not crash when scopeNodes is empty', () => { + const tree: TreeNode = { + scopeNodeId: '', + expanded: true, + query: '', + children: {}, + childrenLoaded: true, + }; + + render(); + + // Should render without crashing - search input should be present + expect(screen.getByRole('combobox')).toBeInTheDocument(); + }); + + it('should handle tree with children referencing missing nodes', () => { + const tree: TreeNode = { + scopeNodeId: 'parent-container', + expanded: true, + query: '', + children: { + 'existing-node': { scopeNodeId: 'existing-node', expanded: false, query: '' }, + 'missing-node': { scopeNodeId: 'missing-node', expanded: false, query: '' }, + }, + childrenLoaded: true, + }; + + const scopeNodes: NodesMap = { + 'parent-container': { + metadata: { name: 'parent-container' }, + spec: { title: 'Parent', nodeType: 'container', parentName: '' }, + }, + 'existing-node': createMockScopeNode('existing-node', 'parent-container'), + // 'missing-node' intentionally not included + }; + + // Should render without crashing + render(); + + // Existing node should be rendered + expect(screen.getByText('Title existing-node')).toBeInTheDocument(); + // Missing node should be gracefully skipped + expect(screen.queryByText('Title missing-node')).not.toBeInTheDocument(); + }); + }); +}); diff --git a/public/app/features/scopes/selector/ScopesTree.tsx b/public/app/features/scopes/selector/ScopesTree.tsx index dd2fd61184c..8178acd3368 100644 --- a/public/app/features/scopes/selector/ScopesTree.tsx +++ b/public/app/features/scopes/selector/ScopesTree.tsx @@ -55,21 +55,22 @@ export function ScopesTree({ const anyChildExpanded = childrenArray.some(({ expanded }) => expanded); // Nodes that are already selected (not applied) are always shown if we are in their category, even if they are - // filtered out by query filter + // filtered out by query filter. Only consider the first selected scope for this display logic. let selectedNodesToShow: TreeNode[] = []; - if (selectedScopes.length > 0 && selectedScopes[0].scopeNodeId) { - if (tree.scopeNodeId === scopeNodes[selectedScopes[0].scopeNodeId]?.spec.parentName) { - selectedNodesToShow = selectedScopes - // We filter out those which are still shown in the normal list of results - .filter((s) => !childrenArray.map((c) => c.scopeNodeId).includes(s.scopeNodeId!)) - .map((s) => ({ - // Because we had to check the parent with the use of scopeNodeId we know we have it. (we may not have it - // if the selected scopes are from url persistence, in which case we don't show them) - scopeNodeId: s.scopeNodeId!, - query: '', - expanded: false, - })); - } + const firstSelectedScope = selectedScopes[0]; + if ( + firstSelectedScope?.scopeNodeId && + scopeNodes[firstSelectedScope.scopeNodeId] && + tree.scopeNodeId === scopeNodes[firstSelectedScope.scopeNodeId]?.spec.parentName && + !childrenArray.map((c) => c.scopeNodeId).includes(firstSelectedScope.scopeNodeId) + ) { + selectedNodesToShow = [ + { + scopeNodeId: firstSelectedScope.scopeNodeId, + query: '', + expanded: false, + }, + ]; } const { highlightedId, ariaActiveDescendant, enableHighlighting, disableHighlighting } = useScopesHighlighting({ diff --git a/public/app/features/scopes/selector/ScopesTreeHeadline.tsx b/public/app/features/scopes/selector/ScopesTreeHeadline.tsx index 755fadf64b5..44ed80ce1bf 100644 --- a/public/app/features/scopes/selector/ScopesTreeHeadline.tsx +++ b/public/app/features/scopes/selector/ScopesTreeHeadline.tsx @@ -18,7 +18,7 @@ export function ScopesTreeHeadline({ anyChildExpanded, query, resultsNodes, scop if ( anyChildExpanded || - (resultsNodes.some((n) => scopeNodes[n.scopeNodeId].spec.nodeType === 'container') && !query) + (resultsNodes.some((n) => scopeNodes[n.scopeNodeId]?.spec.nodeType === 'container') && !query) ) { return null; } diff --git a/public/app/features/scopes/selector/ScopesTreeItemList.test.tsx b/public/app/features/scopes/selector/ScopesTreeItemList.test.tsx new file mode 100644 index 00000000000..a93bb456a83 --- /dev/null +++ b/public/app/features/scopes/selector/ScopesTreeItemList.test.tsx @@ -0,0 +1,136 @@ +import { render, screen } from '@testing-library/react'; + +import { ScopeNode } from '@grafana/data'; + +import { ScopesTreeItemList } from './ScopesTreeItemList'; +import { NodesMap, SelectedScope, TreeNode } from './types'; + +// Mock the ScopesContextProvider hook since it requires a full context setup +jest.mock('../ScopesContextProvider', () => ({ + useScopesServices: () => ({ + scopesSelectorService: { + closeAndApply: jest.fn(), + }, + }), +})); + +describe('ScopesTreeItemList', () => { + const mockFilterNode = jest.fn(); + const mockSelectScope = jest.fn(); + const mockDeselectScope = jest.fn(); + const mockToggleExpandedNode = jest.fn(); + + const defaultProps = { + anyChildExpanded: false, + lastExpandedNode: false, + loadingNodeName: undefined, + maxHeight: '100%', + selectedScopes: [] as SelectedScope[], + filterNode: mockFilterNode, + selectScope: mockSelectScope, + deselectScope: mockDeselectScope, + highlightedId: undefined, + id: 'test-tree', + toggleExpandedNode: mockToggleExpandedNode, + }; + + const createMockScopeNode = (name: string, parentName = 'parent'): ScopeNode => ({ + metadata: { name }, + spec: { + title: `Title ${name}`, + nodeType: 'leaf', + linkType: 'scope', + linkId: `scope-${name}`, + parentName, + }, + }); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('should render nothing when items array is empty', () => { + const { container } = render(); + + expect(container.firstChild).toBeNull(); + }); + + it('should render tree items when nodes are available', () => { + const items: TreeNode[] = [ + { scopeNodeId: 'node-1', expanded: false, query: '' }, + { scopeNodeId: 'node-2', expanded: false, query: '' }, + ]; + + const scopeNodes: NodesMap = { + 'node-1': createMockScopeNode('node-1'), + 'node-2': createMockScopeNode('node-2'), + parent: { + metadata: { name: 'parent' }, + spec: { title: 'Parent', nodeType: 'container', parentName: '' }, + }, + }; + + render(); + + expect(screen.getByText('Title node-1')).toBeInTheDocument(); + expect(screen.getByText('Title node-2')).toBeInTheDocument(); + }); + + it('should skip rendering items when node data is not available in scopeNodes', () => { + const items: TreeNode[] = [ + { scopeNodeId: 'node-1', expanded: false, query: '' }, + { scopeNodeId: 'missing-node', expanded: false, query: '' }, // This node doesn't exist in scopeNodes + { scopeNodeId: 'node-2', expanded: false, query: '' }, + ]; + + const scopeNodes: NodesMap = { + 'node-1': createMockScopeNode('node-1'), + 'node-2': createMockScopeNode('node-2'), + parent: { + metadata: { name: 'parent' }, + spec: { title: 'Parent', nodeType: 'container', parentName: '' }, + }, + // 'missing-node' is intentionally not included + }; + + render(); + + // Should render the available nodes + expect(screen.getByText('Title node-1')).toBeInTheDocument(); + expect(screen.getByText('Title node-2')).toBeInTheDocument(); + + // Should NOT crash and should skip the missing node + expect(screen.queryByText('Title missing-node')).not.toBeInTheDocument(); + }); + + it('should handle all items having missing node data gracefully', () => { + const items: TreeNode[] = [ + { scopeNodeId: 'missing-1', expanded: false, query: '' }, + { scopeNodeId: 'missing-2', expanded: false, query: '' }, + ]; + + const scopeNodes: NodesMap = {}; + + // Should not crash + const { container } = render(); + + // Container should have the tree div but no visible items rendered inside + expect(container.querySelector('[role="tree"]')).toBeInTheDocument(); + expect(screen.queryByRole('treeitem')).not.toBeInTheDocument(); + }); + + it('should handle empty string scopeNodeId gracefully', () => { + const items: TreeNode[] = [ + { scopeNodeId: '', expanded: false, query: '' }, // Empty string scopeNodeId + ]; + + const scopeNodes: NodesMap = {}; + + // Should not crash + const { container } = render(); + + // Should have tree container but no items + expect(container.querySelector('[role="tree"]')).toBeInTheDocument(); + expect(screen.queryByRole('treeitem')).not.toBeInTheDocument(); + }); +}); diff --git a/public/app/features/scopes/selector/ScopesTreeItemList.tsx b/public/app/features/scopes/selector/ScopesTreeItemList.tsx index 33d3a4e2b53..e28a8cda214 100644 --- a/public/app/features/scopes/selector/ScopesTreeItemList.tsx +++ b/public/app/features/scopes/selector/ScopesTreeItemList.tsx @@ -47,15 +47,20 @@ export function ScopesTreeItemList({ const children = (
    {items.map((childNode) => { + const node = scopeNodes[childNode.scopeNodeId]; + // Skip rendering if node data isn't available + if (!node) { + return null; + } const selected = - isNodeSelectable(scopeNodes[childNode.scopeNodeId]) && + isNodeSelectable(node) && selectedScopes.some((s) => { if (s.scopeNodeId) { // If we have scopeNodeId we only match based on that so even if the actual scope is the same we don't // mark different scopeNode as selected. return s.scopeNodeId === childNode.scopeNodeId; } else { - return s.scopeId === scopeNodes[childNode.scopeNodeId]?.spec.linkId; + return s.scopeId === node.spec.linkId; } }); return ( diff --git a/public/app/features/scopes/tests/dashboardsList.test.ts b/public/app/features/scopes/tests/dashboardsList.test.ts index 0fc77e74962..b4e091bfd6b 100644 --- a/public/app/features/scopes/tests/dashboardsList.test.ts +++ b/public/app/features/scopes/tests/dashboardsList.test.ts @@ -26,7 +26,6 @@ import { expectNoDashboardsForFilter, expectNoDashboardsForScope, expectNoDashboardsNoScopes, - expectNoDashboardsSearch, } from './utils/assertions'; import { alternativeDashboardWithRootFolder, @@ -304,14 +303,12 @@ describe('Dashboards list', () => { it('Shows a proper message when no scopes are selected', async () => { await toggleDashboards(); expectNoDashboardsNoScopes(); - expectNoDashboardsSearch(); }); it('Does not show the input when there are no dashboards found for scope', async () => { await updateScopes(scopesService, ['cloud']); await toggleDashboards(); expectNoDashboardsForScope(); - expectNoDashboardsSearch(); }); it('Shows the input and a message when there are no dashboards found for filter', async () => { diff --git a/public/app/features/search/tempI18nPhrases.ts b/public/app/features/search/tempI18nPhrases.ts index 73766e4bff6..926bf24ea73 100644 --- a/public/app/features/search/tempI18nPhrases.ts +++ b/public/app/features/search/tempI18nPhrases.ts @@ -2,7 +2,6 @@ // TODO: remove this when new Browse Dashboards UI is no longer feature flagged import { t } from '@grafana/i18n'; -import { config } from '@grafana/runtime'; export function getSearchPlaceholder(includePanels = false) { return includePanels @@ -11,9 +10,7 @@ export function getSearchPlaceholder(includePanels = false) { } export function getNewDashboardPhrase() { - return config.featureToggles.dashboardTemplates - ? t('search.dashboard-actions.empty-dashboard', 'Empty dashboard') - : t('search.dashboard-actions.new-dashboard', 'New dashboard'); + return t('search.dashboard-actions.new-dashboard', 'New dashboard'); } export function getNewTemplateDashboardPhrase() { diff --git a/public/app/features/teams/TeamGroupSync.test.tsx b/public/app/features/teams/TeamGroupSync.test.tsx index d3a83d9c5dc..8f0e98eda4c 100644 --- a/public/app/features/teams/TeamGroupSync.test.tsx +++ b/public/app/features/teams/TeamGroupSync.test.tsx @@ -1,26 +1,17 @@ -import { render, screen } from 'test/test-utils'; +import { render, screen, waitFor } from 'test/test-utils'; import { setBackendSrv } from '@grafana/runtime'; import { setupMockServer } from '@grafana/test-utils/server'; -import { MOCK_TEAMS } from '@grafana/test-utils/unstable'; +import { MOCK_TEAMS, MOCK_TEAM_GROUPS } from '@grafana/test-utils/unstable'; import { backendSrv } from 'app/core/services/backend_srv'; -import { TeamGroup, TeamState } from 'app/types/teams'; import TeamGroupSync from './TeamGroupSync'; -import { getMockTeamGroups } from './mocks/teamMocks'; setBackendSrv(backendSrv); setupMockServer(); -const setup = (preloadedTeamState?: Partial) => { - return render(, { - preloadedState: { - team: { - groups: [], - ...preloadedTeamState, - }, - }, - }); +const setup = () => { + return render(); }; describe('TeamGroupSync', () => { @@ -29,28 +20,37 @@ describe('TeamGroupSync', () => { expect(screen.getByRole('heading', { name: /External group sync/i })).toBeInTheDocument(); }); - it('should render groups table', () => { - setup({ groups: getMockTeamGroups(3) }); - expect(screen.getAllByRole('row')).toHaveLength(4); // 3 items plus table header + it('should render groups table', async () => { + setup(); + expect(await screen.findAllByRole('row')).toHaveLength(MOCK_TEAM_GROUPS.length + 1); // items plus table header }); it('should call add group', async () => { const { user } = setup(); - // Empty List CTA "Add group" button is second in the DOM order - await user.click(screen.getAllByRole('button', { name: /add group/i })[1]); + // Wait for the groups to load so the "Add group" button appears + await screen.findAllByRole('row'); + + await user.click(screen.getAllByRole('button', { name: /add group/i })[0]); expect(screen.getByRole('textbox', { name: /add external group/i })).toBeVisible(); await user.type(screen.getByRole('textbox', { name: /add external group/i }), 'test/group'); - await user.click(screen.getAllByRole('button', { name: /add group/i })[0]); + await user.click(screen.getAllByRole('button', { name: /add group/i })[1]); - expect(screen.getByRole('row', { name: /test\/group/i })).toBeInTheDocument(); + expect(await screen.findByRole('row', { name: /test\/group/i })).toBeInTheDocument(); }); it('should remove group', async () => { - const mockGroup: TeamGroup = { teamId: 1, groupId: 'someGroup' }; - const { user } = setup({ groups: [mockGroup] }); - await user.click(screen.getByRole('button', { name: 'Remove group someGroup' })); + const { user } = setup(); + const groupToRemove = MOCK_TEAM_GROUPS[0].groupId; - expect(screen.queryByRole('row', { name: /test\/group/i })).not.toBeInTheDocument(); + // Wait for group to be rendered + await screen.findByRole('row', { name: new RegExp(groupToRemove, 'i') }); + + // Remove group + await user.click(screen.getByRole('button', { name: `Remove group ${groupToRemove}` })); + + await waitFor(() => + expect(screen.queryByRole('row', { name: new RegExp(groupToRemove, 'i') })).not.toBeInTheDocument() + ); }); }); diff --git a/public/app/features/teams/TeamGroupSync.tsx b/public/app/features/teams/TeamGroupSync.tsx index 37887ee8d6a..66a227527dc 100644 --- a/public/app/features/teams/TeamGroupSync.tsx +++ b/public/app/features/teams/TeamGroupSync.tsx @@ -1,85 +1,63 @@ import { css, cx } from '@emotion/css'; -import { FormEventHandler, PureComponent } from 'react'; -import { connect, ConnectedProps } from 'react-redux'; +import { FormEventHandler, useState } from 'react'; +import { + TeamGroupDto, + useAddTeamGroupApiMutation, + useGetTeamGroupsApiQuery, + useRemoveTeamGroupApiQueryMutation, +} from '@grafana/api-clients/rtkq/legacy'; import { Trans, t } from '@grafana/i18n'; -import { Input, Tooltip, Icon, Button, useTheme2, InlineField, InlineFieldRow } from '@grafana/ui'; +import { Input, Tooltip, Icon, Button, useTheme2, InlineField, InlineFieldRow, useStyles2 } from '@grafana/ui'; import { SlideDown } from 'app/core/components/Animations/SlideDown'; import { CloseButton } from 'app/core/components/CloseButton/CloseButton'; import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA'; import { UpgradeBox, UpgradeContent, UpgradeContentProps } from 'app/core/components/Upgrade/UpgradeBox'; import { highlightTrial } from 'app/features/admin/utils'; -import { StoreState } from 'app/types/store'; -import { TeamGroup } from 'app/types/teams'; -import { addTeamGroup, loadTeamGroups, removeTeamGroup } from './state/actions'; -import { getTeamGroups } from './state/selectors'; - -function mapStateToProps(state: StoreState) { - return { - groups: getTeamGroups(state.team), - }; -} - -const mapDispatchToProps = { - loadTeamGroups, - addTeamGroup, - removeTeamGroup, -}; - -interface OwnProps { +interface Props { isReadOnly: boolean; teamUid: string; } -interface State { - isAdding: boolean; - newGroupId: string; -} - -const connector = connect(mapStateToProps, mapDispatchToProps); -export type Props = OwnProps & ConnectedProps; - const headerTooltip = `Sync LDAP, OAuth or SAML groups with your Grafana teams.`; -export class TeamGroupSync extends PureComponent { - constructor(props: Props) { - super(props); - this.state = { isAdding: false, newGroupId: '' }; - } +export const TeamGroupSync = ({ isReadOnly, teamUid }: Props) => { + const [isAddBoxVisible, setIsAddBoxVisible] = useState(false); + const [newGroupId, setNewGroupId] = useState(''); + const styles = useStyles2(getStyles); - componentDidMount() { - this.fetchTeamGroups(); - } + const { data: groups = [] } = useGetTeamGroupsApiQuery({ teamId: teamUid }); + const [addTeamGroup] = useAddTeamGroupApiMutation(); + const [removeTeamGroup] = useRemoveTeamGroupApiQueryMutation(); - async fetchTeamGroups() { - this.props.loadTeamGroups(this.props.teamUid); - } - - onToggleAdding = () => { - this.setState({ isAdding: !this.state.isAdding }); + const onToggleAdding = () => { + setIsAddBoxVisible(!isAddBoxVisible); }; - onNewGroupIdChanged: FormEventHandler = (event) => { - this.setState({ newGroupId: event.currentTarget.value }); + const onNewGroupIdChanged: FormEventHandler = (event) => { + setNewGroupId(event.currentTarget.value); }; - onAddGroup: FormEventHandler = (event) => { + const onAddGroup: FormEventHandler = async (event) => { event.preventDefault(); - this.props.addTeamGroup(this.props.teamUid, this.state.newGroupId); - this.setState({ isAdding: false, newGroupId: '' }); + await addTeamGroup({ teamId: teamUid, teamGroupMapping: { groupId: newGroupId } }); + setIsAddBoxVisible(false); + setNewGroupId(''); }; - onRemoveGroup = (group: TeamGroup) => { - this.props.removeTeamGroup(this.props.teamUid, group.groupId); + const onRemoveGroup = async (groupId: string | undefined) => { + if (!groupId) { + return; + } + await removeTeamGroup({ teamId: teamUid, groupId }); }; - isNewGroupValid() { - return this.state.newGroupId.length > 1; - } + const isNewGroupValid = () => { + return newGroupId.length > 1; + }; - renderGroup(group: TeamGroup) { - const { isReadOnly } = this.props; + const renderGroup = (group: TeamGroupDto) => { return (
{group.groupId}
- - - - - - {groups.map((group) => this.renderGroup(group))} -
- External Group ID - -
-
+ )}
- ); - } -} + + +
+ +
+ + + + + + +
+
+
+ + {groups.length === 0 && + !isAddBoxVisible && + (highlightTrial() ? ( + + ) : ( + + ))} + + {groups.length > 0 && ( +
+ + + + + + + {groups.map((group) => renderGroup(group))} +
+ External Group ID + +
+
+ )} +
+ ); +}; export const TeamSyncUpgradeContent = ({ action }: { action?: UpgradeContentProps['action'] }) => { const theme = useTheme2(); @@ -226,7 +196,7 @@ export const TeamSyncUpgradeContent = ({ action }: { action?: UpgradeContentProp /> ); }; -export default connect(mapStateToProps, mapDispatchToProps)(TeamGroupSync); +export default TeamGroupSync; const getStyles = () => ({ icon: css({ diff --git a/public/app/features/teams/mocks/teamMocks.ts b/public/app/features/teams/mocks/teamMocks.ts index d6472499cb2..d43f1c454b2 100644 --- a/public/app/features/teams/mocks/teamMocks.ts +++ b/public/app/features/teams/mocks/teamMocks.ts @@ -1,7 +1,7 @@ import { randomBytes } from 'crypto'; import { TeamPermissionLevel } from 'app/types/acl'; -import { Team, TeamMember, TeamGroup } from 'app/types/teams'; +import { Team, TeamMember } from 'app/types/teams'; function generateShortUid(): string { return randomBytes(3).toString('hex'); // Generate a short UID @@ -44,16 +44,3 @@ export const getMockTeamMember = (): TeamMember => { permission: TeamPermissionLevel.Member, }; }; - -export const getMockTeamGroups = (amount: number): TeamGroup[] => { - const groups: TeamGroup[] = []; - - for (let i = 1; i <= amount; i++) { - groups.push({ - groupId: `group-${i}`, - teamId: 1, - }); - } - - return groups; -}; diff --git a/public/app/features/teams/state/actions.ts b/public/app/features/teams/state/actions.ts deleted file mode 100644 index d0d05e0946c..00000000000 --- a/public/app/features/teams/state/actions.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { getBackendSrv } from '@grafana/runtime'; -import { ThunkResult } from 'app/types/store'; - -import { teamGroupsLoaded } from './reducers'; - -export function loadTeamGroups(teamUid: string): ThunkResult { - return async (dispatch) => { - const response = await getBackendSrv().get(`/api/teams/${teamUid}/groups`); - dispatch(teamGroupsLoaded(response)); - }; -} - -export function addTeamGroup(teamUid: string, groupId: string): ThunkResult { - return async (dispatch) => { - await getBackendSrv().post(`/api/teams/${teamUid}/groups`, { groupId: groupId }); - dispatch(loadTeamGroups(teamUid)); - }; -} - -export function removeTeamGroup(teamUid: string, groupId: string): ThunkResult { - return async (dispatch) => { - // need to use query parameter due to escaped characters in the request - await getBackendSrv().delete(`/api/teams/${teamUid}/groups?groupId=${encodeURIComponent(groupId)}`); - dispatch(loadTeamGroups(teamUid)); - }; -} diff --git a/public/app/features/teams/state/reducers.ts b/public/app/features/teams/state/reducers.ts deleted file mode 100644 index 50011316a72..00000000000 --- a/public/app/features/teams/state/reducers.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { createSlice, PayloadAction } from '@reduxjs/toolkit'; - -import { TeamState, TeamGroup } from 'app/types/teams'; - -export const initialTeamState: TeamState = { - groups: [], -}; - -const teamSlice = createSlice({ - name: 'team', - initialState: initialTeamState, - reducers: { - teamGroupsLoaded: (state, action: PayloadAction): TeamState => { - return { ...state, groups: action.payload }; - }, - }, -}); - -export const { teamGroupsLoaded } = teamSlice.actions; - -export const teamReducer = teamSlice.reducer; - -export default { - team: teamReducer, -}; diff --git a/public/app/features/teams/state/selectors.ts b/public/app/features/teams/state/selectors.ts deleted file mode 100644 index 4ada9ee8d46..00000000000 --- a/public/app/features/teams/state/selectors.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { TeamState } from 'app/types/teams'; - -export const getTeamGroups = (state: TeamState) => state.groups; diff --git a/public/app/plugins/datasource/dashboard/datasource.test.ts b/public/app/plugins/datasource/dashboard/datasource.test.ts index 2dcb17c63db..0491dfcd798 100644 --- a/public/app/plugins/datasource/dashboard/datasource.test.ts +++ b/public/app/plugins/datasource/dashboard/datasource.test.ts @@ -10,6 +10,7 @@ import { FieldType, DataFrame, AdHocVariableFilter, + DataTopic, } from '@grafana/data'; import { getPanelPlugin } from '@grafana/data/test'; import { setPluginImportUtils } from '@grafana/runtime'; @@ -774,8 +775,124 @@ describe('DashboardDatasource', () => { }); }); }); + + describe('Annotation Handling', () => { + it('should NOT include annotations from source panel in regular query response', async () => { + const { observable } = setupWithAnnotations({ refId: 'A', panelId: 1 }); + + let rsp: DataQueryResponse | undefined; + observable.subscribe({ next: (data) => (rsp = data) }); + + // Should only have series data, no annotations + expect(rsp?.data.length).toBe(1); + expect(rsp?.data[0].fields[0].values).toEqual([1, 2, 3]); + + // Verify no annotation frames are included + const annotationFrames = rsp?.data.filter((frame) => frame.meta?.dataTopic === DataTopic.Annotations); + expect(annotationFrames?.length).toBe(0); + }); + + it('should return annotations as series when query topic is DataTopic.Annotations', async () => { + const { observable } = setupWithAnnotations({ refId: 'A', panelId: 1, topic: DataTopic.Annotations }); + + let rsp: DataQueryResponse | undefined; + observable.subscribe({ next: (data) => (rsp = data) }); + + // Should return annotation data as series (with dataTopic changed to Series) + expect(rsp?.data.length).toBe(1); + expect(rsp?.data[0].name).toBe('Test Annotation'); + // The dataTopic should be changed to Series when querying for annotations + expect(rsp?.data[0].meta?.dataTopic).toBe(DataTopic.Series); + }); + + it('should not leak annotations when source panel has annotations and toggle is off', async () => { + // This test ensures that when annotations are toggled off at the dashboard level, + // DashboardDS panels don't continue showing them from the source panel's cached data + const { observable } = setupWithAnnotations({ refId: 'A', panelId: 1 }); + + let rsp: DataQueryResponse | undefined; + observable.subscribe({ next: (data) => (rsp = data) }); + + // Verify that annotations from source panel are NOT included in response + // This is critical for annotation toggle to work correctly on DashboardDS panels + const hasAnnotations = rsp?.data.some( + (frame) => frame.meta?.dataTopic === DataTopic.Annotations || frame.name === 'Test Annotation' + ); + expect(hasAnnotations).toBe(false); + }); + + it('should only return series data even when source has both series and annotations', async () => { + const { observable } = setupWithAnnotations({ refId: 'A', panelId: 1 }); + + let rsp: DataQueryResponse | undefined; + observable.subscribe({ next: (data) => (rsp = data) }); + + // All returned frames should be series data, not annotations + rsp?.data.forEach((frame) => { + expect(frame.meta?.dataTopic).not.toBe(DataTopic.Annotations); + }); + + // Should have the series data from the source panel + expect(rsp?.data[0].fields[0].values).toEqual([1, 2, 3]); + }); + }); }); +function setupWithAnnotations(query: DashboardQuery, requestId?: string) { + const annotationFrame: DataFrame = { + name: 'Test Annotation', + fields: [ + { name: 'time', type: FieldType.time, values: [1000, 2000], config: {} }, + { name: 'text', type: FieldType.string, values: ['Annotation 1', 'Annotation 2'], config: {} }, + ], + length: 2, + meta: { + dataTopic: DataTopic.Annotations, + }, + }; + + const sourceData = new SceneDataTransformer({ + $data: new SceneDataNode({ + data: { + series: [arrayToDataFrame([1, 2, 3])], + annotations: [annotationFrame], + state: LoadingState.Done, + timeRange: getDefaultTimeRange(), + }, + }), + transformations: [], + }); + + const scene = new SceneFlexLayout({ + children: [ + new SceneFlexItem({ + body: new VizPanel({ + key: getVizPanelKeyForPanelId(1), + $data: sourceData, + }), + }), + ], + }); + + const ds = new DashboardDatasource({} as DataSourceInstanceSettings); + + const observable = ds.query({ + timezone: 'utc', + targets: [query], + requestId: requestId ?? '', + interval: '', + intervalMs: 0, + range: getDefaultTimeRange(), + scopedVars: { + __sceneObject: new SafeSerializableSceneObject(scene), + }, + app: '', + startTime: 0, + }); + + return { observable, sourceData }; +} + function setup(query: DashboardQuery, requestId?: string) { const sourceData = new SceneDataTransformer({ $data: new SceneDataNode({ diff --git a/public/app/plugins/datasource/dashboard/datasource.ts b/public/app/plugins/datasource/dashboard/datasource.ts index 34a1781623f..63fefd10bb1 100644 --- a/public/app/plugins/datasource/dashboard/datasource.ts +++ b/public/app/plugins/datasource/dashboard/datasource.ts @@ -122,8 +122,9 @@ export class DashboardDatasource extends DataSourceApi { query: DashboardQuery, filters: AdHocVariableFilter[] ): DataFrame[] { - const annotations = data.annotations ?? []; + // When querying for annotations topic, return the source panel's annotations as series data if (query.topic === DataTopic.Annotations) { + const annotations = data.annotations ?? []; return annotations.map((frame) => ({ ...frame, meta: { @@ -131,34 +132,34 @@ export class DashboardDatasource extends DataSourceApi { dataTopic: DataTopic.Series, }, })); - } else { - const series = data.series.map((s) => { - return { - ...s, - fields: s.fields.map((field: Field) => ({ - ...field, - config: { - ...field.config, - // Enable AdHoc filtering for string and numeric fields only when per-panel setting is enabled - filterable: query.adHocFiltersEnabled - ? field.type === FieldType.string || field.type === FieldType.number - : field.config.filterable, - }, - state: { - ...field.state, - }, - })), - }; - }); - - if (!query.adHocFiltersEnabled || filters.length === 0) { - return [...series, ...annotations]; - } - - // Apply AdHoc filters to series data - const filteredSeries = series.map((frame) => this.applyAdHocFilters(frame, filters)); - return [...filteredSeries, ...annotations]; } + + // For regular queries, only return series data + const series = data.series.map((s) => { + return { + ...s, + fields: s.fields.map((field: Field) => ({ + ...field, + config: { + ...field.config, + // Enable AdHoc filtering for string and numeric fields only when per-panel setting is enabled + filterable: query.adHocFiltersEnabled + ? field.type === FieldType.string || field.type === FieldType.number + : field.config.filterable, + }, + state: { + ...field.state, + }, + })), + }; + }); + + if (!query.adHocFiltersEnabled || filters.length === 0) { + return series; + } + + // Apply AdHoc filters to series data + return series.map((frame) => this.applyAdHocFilters(frame, filters)); } /** diff --git a/public/app/plugins/datasource/elasticsearch/QueryBuilder.ts b/public/app/plugins/datasource/elasticsearch/QueryBuilder.ts index 22ed3d8d68e..3d36ee9a806 100644 --- a/public/app/plugins/datasource/elasticsearch/QueryBuilder.ts +++ b/public/app/plugins/datasource/elasticsearch/QueryBuilder.ts @@ -18,12 +18,12 @@ import { } from './dataquery.gen'; import { defaultBucketAgg, - defaultMetricAgg, findMetricById, highlightTags, defaultGeoHashPrecisionString, + queryTypeToMetricType, } from './queryDef'; -import { TermsQuery } from './types'; +import { QueryType, TermsQuery } from './types'; import { convertOrderByToMetricId, getScriptValue } from './utils'; // Omitting 1m, 1h, 1d for now, as these cover the main use cases for calendar_interval @@ -31,9 +31,11 @@ export const calendarIntervals: string[] = ['1w', '1M', '1q', '1y']; export class ElasticQueryBuilder { timeField: string; + defaultQueryMode?: QueryType; - constructor(options: { timeField: string }) { + constructor(options: { timeField: string; defaultQueryMode?: QueryType }) { this.timeField = options.timeField; + this.defaultQueryMode = options.defaultQueryMode; } getRangeFilter() { @@ -174,7 +176,10 @@ export class ElasticQueryBuilder { build(target: ElasticsearchDataQuery) { // make sure query has defaults; - target.metrics = target.metrics || [defaultMetricAgg()]; + if (!target.metrics || target.metrics.length === 0) { + const metricType = queryTypeToMetricType(this.defaultQueryMode); + target.metrics = [{ type: metricType, id: '1' }]; + } target.bucketAggs = target.bucketAggs || [defaultBucketAgg()]; target.timeField = this.timeField; let metric: MetricAggregation; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/EditorTypeSelector.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/EditorTypeSelector.tsx new file mode 100644 index 00000000000..c9d52ecd49d --- /dev/null +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/EditorTypeSelector.tsx @@ -0,0 +1,29 @@ +import { SelectableValue } from '@grafana/data'; +import { RadioButtonGroup } from '@grafana/ui'; + +import { useDispatch } from '../../hooks/useStatelessReducer'; +import { EditorType } from '../../types'; + +import { useQuery } from './ElasticsearchQueryContext'; +import { changeEditorTypeAndResetQuery } from './state'; + +const BASE_OPTIONS: Array> = [ + { value: 'builder', label: 'Builder' }, + { value: 'code', label: 'Code' }, +]; + +export const EditorTypeSelector = () => { + const query = useQuery(); + const dispatch = useDispatch(); + + // Default to 'builder' if editorType is empty + const editorType: EditorType = query.editorType === 'code' ? 'code' : 'builder'; + + const onChange = (newEditorType: EditorType) => { + dispatch(changeEditorTypeAndResetQuery(newEditorType)); + }; + + return ( + fullWidth={false} options={BASE_OPTIONS} value={editorType} onChange={onChange} /> + ); +}; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/ElasticsearchQueryContext.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/ElasticsearchQueryContext.tsx index 57092ae9477..44fac679a9e 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/ElasticsearchQueryContext.tsx +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/ElasticsearchQueryContext.tsx @@ -8,7 +8,7 @@ import { combineReducers, useStatelessReducer, DispatchContext } from '../../hoo import { createReducer as createBucketAggsReducer } from './BucketAggregationsEditor/state/reducer'; import { reducer as metricsReducer } from './MetricAggregationsEditor/state/reducer'; -import { aliasPatternReducer, queryReducer, initQuery } from './state'; +import { aliasPatternReducer, queryReducer, rawDSLQueryReducer, editorTypeReducer, initQuery } from './state'; const DatasourceContext = createContext(undefined); const QueryContext = createContext(undefined); @@ -40,9 +40,13 @@ export const ElasticsearchProvider = ({ [onChange, onRunQuery] ); - const reducer = combineReducers>({ + const reducer = combineReducers< + Pick + >({ query: queryReducer, + rawDSLQuery: rawDSLQueryReducer, alias: aliasPatternReducer, + editorType: editorTypeReducer, metrics: metricsReducer, bucketAggs: createBucketAggsReducer(datasource.timeField), }); @@ -62,10 +66,10 @@ export const ElasticsearchProvider = ({ // useStatelessReducer will then call `onChange` with the newly generated query useEffect(() => { if (shouldRunInit && isUninitialized) { - dispatch(initQuery()); + dispatch(initQuery(datasource.defaultQueryMode)); setShouldRunInit(false); } - }, [shouldRunInit, dispatch, isUninitialized]); + }, [shouldRunInit, dispatch, isUninitialized, datasource.defaultQueryMode]); if (isUninitialized) { return null; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/actions.ts b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/actions.ts index f304e4876c1..9adff8781b1 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/actions.ts +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/actions.ts @@ -11,6 +11,9 @@ export const changeMetricField = createAction<{ id: MetricAggregation['id']; fie export const changeMetricType = createAction<{ id: MetricAggregation['id']; type: MetricAggregation['type'] }>( '@metrics/change_type' ); +export const changeEditorType = createAction<{ id: MetricAggregation['id']; type: MetricAggregation['type'] }>( + '@metrics/change_type' +); export const changeMetricAttribute = createAction<{ metric: MetricAggregation; attribute: string; newValue: unknown }>( '@metrics/change_attr' ); diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/reducer.ts b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/reducer.ts index d44a57569f7..966bd71d6c8 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/reducer.ts +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/state/reducer.ts @@ -2,7 +2,7 @@ import { Action } from '@reduxjs/toolkit'; import { ElasticsearchDataQuery, MetricAggregation } from 'app/plugins/datasource/elasticsearch/dataquery.gen'; -import { defaultMetricAgg } from '../../../../queryDef'; +import { defaultMetricAgg, queryTypeToMetricType } from '../../../../queryDef'; import { removeEmpty } from '../../../../utils'; import { initQuery } from '../../state'; import { isMetricAggregationWithMeta, isMetricAggregationWithSettings, isPipelineAggregation } from '../aggregations'; @@ -162,7 +162,8 @@ export const reducer = ( if (state && state.length > 0) { return state; } - return [defaultMetricAgg('1')]; + const metricType = queryTypeToMetricType(action.payload); + return [{ type: metricType, id: '1' }]; } return state; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.test.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.test.tsx new file mode 100644 index 00000000000..915d35a3bf8 --- /dev/null +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.test.tsx @@ -0,0 +1,117 @@ +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { ElasticsearchDataQuery } from '../../dataquery.gen'; +import { useDispatch } from '../../hooks/useStatelessReducer'; +import { renderWithESProvider } from '../../test-helpers/render'; + +import { changeMetricType } from './MetricAggregationsEditor/state/actions'; +import { QueryTypeSelector } from './QueryTypeSelector'; + +jest.mock('../../hooks/useStatelessReducer'); + +describe('QueryTypeSelector', () => { + let dispatch: jest.Mock; + + beforeEach(() => { + dispatch = jest.fn(); + jest.mocked(useDispatch).mockReturnValue(dispatch); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should render radio buttons with correct options', () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [{ id: '1', type: 'count' }], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + renderWithESProvider(, { providerProps: { query } }); + + expect(screen.getByRole('radio', { name: 'Metrics' })).toBeInTheDocument(); + expect(screen.getByRole('radio', { name: 'Logs' })).toBeInTheDocument(); + expect(screen.getByRole('radio', { name: 'Raw Data' })).toBeInTheDocument(); + expect(screen.getByRole('radio', { name: 'Raw Document' })).toBeInTheDocument(); + }); + + it('should dispatch changeMetricType action when radio button is changed', async () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [{ id: '1', type: 'count' }], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + renderWithESProvider(, { providerProps: { query } }); + + const logsRadio = screen.getByRole('radio', { name: 'Logs' }); + await userEvent.click(logsRadio); + + expect(dispatch).toHaveBeenCalledWith(changeMetricType({ id: '1', type: 'logs' })); + }); + + it('should convert query type to metric type correctly for raw_data', async () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [{ id: '1', type: 'count' }], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + renderWithESProvider(, { providerProps: { query } }); + + const rawDataRadio = screen.getByRole('radio', { name: 'Raw Data' }); + await userEvent.click(rawDataRadio); + + expect(dispatch).toHaveBeenCalledWith(changeMetricType({ id: '1', type: 'raw_data' })); + }); + + it('should convert query type to metric type correctly for raw_document', async () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [{ id: '1', type: 'count' }], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + renderWithESProvider(, { providerProps: { query } }); + + const rawDocumentRadio = screen.getByRole('radio', { name: 'Raw Document' }); + await userEvent.click(rawDocumentRadio); + + expect(dispatch).toHaveBeenCalledWith(changeMetricType({ id: '1', type: 'raw_document' })); + }); + + it('should convert metrics query type to count metric type', async () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [{ id: '1', type: 'logs' }], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + renderWithESProvider(, { providerProps: { query } }); + + const metricsRadio = screen.getByRole('radio', { name: 'Metrics' }); + await userEvent.click(metricsRadio); + + expect(dispatch).toHaveBeenCalledWith(changeMetricType({ id: '1', type: 'count' })); + }); + + it('should return null when query has no metrics', () => { + const query: ElasticsearchDataQuery = { + refId: 'A', + query: '', + metrics: [], + bucketAggs: [{ type: 'date_histogram', id: '2' }], + }; + + const { container } = renderWithESProvider(, { providerProps: { query } }); + + expect(container.firstChild).toBeNull(); + }); +}); diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.tsx index bdfd1336d8b..207646a9514 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.tsx +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/QueryTypeSelector.tsx @@ -1,35 +1,14 @@ -import { SelectableValue } from '@grafana/data'; import { RadioButtonGroup } from '@grafana/ui'; -import { MetricAggregation } from '../../dataquery.gen'; +import { QUERY_TYPE_SELECTOR_OPTIONS } from '../../configuration/utils'; import { useDispatch } from '../../hooks/useStatelessReducer'; +import { queryTypeToMetricType } from '../../queryDef'; import { QueryType } from '../../types'; import { useQuery } from './ElasticsearchQueryContext'; import { changeMetricType } from './MetricAggregationsEditor/state/actions'; import { metricAggregationConfig } from './MetricAggregationsEditor/utils'; -const OPTIONS: Array> = [ - { value: 'metrics', label: 'Metrics' }, - { value: 'logs', label: 'Logs' }, - { value: 'raw_data', label: 'Raw Data' }, - { value: 'raw_document', label: 'Raw Document' }, -]; - -function queryTypeToMetricType(type: QueryType): MetricAggregation['type'] { - switch (type) { - case 'logs': - case 'raw_data': - case 'raw_document': - return type; - case 'metrics': - return 'count'; - default: - // should never happen - throw new Error(`invalid query type: ${type}`); - } -} - export const QueryTypeSelector = () => { const query = useQuery(); const dispatch = useDispatch(); @@ -47,5 +26,12 @@ export const QueryTypeSelector = () => { dispatch(changeMetricType({ id: firstMetric.id, type: queryTypeToMetricType(newQueryType) })); }; - return fullWidth={false} options={OPTIONS} value={queryType} onChange={onChange} />; + return ( + + fullWidth={false} + options={QUERY_TYPE_SELECTOR_OPTIONS} + value={queryType} + onChange={onChange} + /> + ); }; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/RawQueryEditor.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/RawQueryEditor.tsx new file mode 100644 index 00000000000..92a5a8b0b9e --- /dev/null +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/RawQueryEditor.tsx @@ -0,0 +1,108 @@ +import { css } from '@emotion/css'; +import { useCallback, useRef } from 'react'; + +import { GrafanaTheme2 } from '@grafana/data'; +import { CodeEditor, Monaco, CodeEditorMonacoOptions, monacoTypes, useStyles2, Button, Stack, Box } from '@grafana/ui'; + +interface Props { + value?: string; + onChange: (value: string) => void; + onRunQuery: () => void; +} + +export function RawQueryEditor({ value, onChange, onRunQuery }: Props) { + const styles = useStyles2(getStyles); + const editorRef = useRef(null); + + const handleEditorDidMount = useCallback( + (editor: monacoTypes.editor.IStandaloneCodeEditor, monaco: Monaco) => { + editorRef.current = editor; + + // Add keyboard shortcut for running query (Ctrl/Cmd+Enter) + editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter, () => { + onRunQuery(); + }); + }, + [onRunQuery] + ); + + const handleFormat = useCallback(() => { + if (editorRef.current) { + editorRef.current.getAction('editor.action.formatDocument')?.run(); + } + }, []); + + const handleQueryChange = useCallback( + (newValue: string) => { + if (!newValue) { + return; + } + onChange(newValue); + }, + [onChange] + ); + + const monacoOptions: CodeEditorMonacoOptions = { + fontSize: 14, + lineNumbers: 'on', + minimap: { enabled: false }, + scrollBeyondLastLine: false, + wordWrap: 'on', + automaticLayout: true, + fixedOverflowWidgets: true, + folding: true, + renderLineHighlight: 'all', + suggest: { + showProperties: true, + showMethods: true, + showKeywords: true, + }, + quickSuggestions: { + other: true, + strings: true, + }, + }; + + return ( + +
+ + + + +
+ +
+ ); +} + +const getStyles = (theme: GrafanaTheme2) => ({ + container: css({ + display: 'flex', + flexDirection: 'column', + gap: theme.spacing(1), + }), + header: css({ + display: 'flex', + justifyContent: 'flex-end', + padding: theme.spacing(0.5, 0), + }), +}); diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/index.tsx b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/index.tsx index 927ef6aa544..b54de44bb63 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/index.tsx +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/index.tsx @@ -3,6 +3,7 @@ import { useEffect, useId, useState } from 'react'; import { SemVer } from 'semver'; import { getDefaultTimeRange, GrafanaTheme2, QueryEditorProps } from '@grafana/data'; +import { config } from '@grafana/runtime'; import { Alert, InlineField, InlineLabel, Input, QueryField, useStyles2 } from '@grafana/ui'; import { ElasticsearchDataQuery } from '../../dataquery.gen'; @@ -13,11 +14,13 @@ import { ElasticsearchOptions } from '../../types'; import { isSupportedVersion, isTimeSeriesQuery, unsupportedVersionMessage } from '../../utils'; import { BucketAggregationsEditor } from './BucketAggregationsEditor'; +import { EditorTypeSelector } from './EditorTypeSelector'; import { ElasticsearchProvider } from './ElasticsearchQueryContext'; import { MetricAggregationsEditor } from './MetricAggregationsEditor'; import { metricAggregationConfig } from './MetricAggregationsEditor/utils'; import { QueryTypeSelector } from './QueryTypeSelector'; -import { changeAliasPattern, changeQuery } from './state'; +import { RawQueryEditor } from './RawQueryEditor'; +import { changeAliasPattern, changeQuery, changeRawDSLQuery } from './state'; export type ElasticQueryEditorProps = QueryEditorProps; @@ -59,7 +62,7 @@ export const QueryEditor = ({ query, onChange, onRunQuery, datasource, range }: range={range || getDefaultTimeRange()} > {showUnsupportedMessage && } - + ); }; @@ -88,7 +91,7 @@ export const ElasticSearchQueryField = ({ value, onChange }: { value?: string; o ); }; -const QueryEditorForm = ({ value }: Props) => { +const QueryEditorForm = ({ value, onRunQuery }: Props & { onRunQuery: () => void }) => { const dispatch = useDispatch(); const nextId = useNextId(); const inputId = useId(); @@ -96,6 +99,9 @@ const QueryEditorForm = ({ value }: Props) => { const isTimeSeries = isTimeSeriesQuery(value); + const isCodeEditor = value.editorType === 'code'; + const rawDSLFeatureEnabled = config.featureToggles.elasticsearchRawDSLQuery; + const showBucketAggregationsEditor = value.metrics?.every( (metric) => metricAggregationConfig[metric.type].impliedQueryType === 'metrics' ); @@ -108,29 +114,50 @@ const QueryEditorForm = ({ value }: Props) => { -
- Lucene Query - dispatch(changeQuery(query))} value={value?.query} /> + {rawDSLFeatureEnabled && ( +
+ Editor type +
+ +
+
+ )} - {isTimeSeries && ( - - dispatch(changeAliasPattern(e.currentTarget.value))} - defaultValue={value.alias} - /> - - )} -
+ {isCodeEditor && rawDSLFeatureEnabled && ( + dispatch(changeRawDSLQuery(rawDSLQuery))} + onRunQuery={onRunQuery} + /> + )} - - {showBucketAggregationsEditor && } + {!isCodeEditor && ( + <> +
+ Lucene Query + dispatch(changeQuery(query))} value={value?.query} /> + + {isTimeSeries && ( + + dispatch(changeAliasPattern(e.currentTarget.value))} + defaultValue={value.alias} + /> + + )} +
+ + + {showBucketAggregationsEditor && } + + )} ); }; diff --git a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/state.ts b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/state.ts index 4785e371642..a9ed51b39ff 100644 --- a/public/app/plugins/datasource/elasticsearch/components/QueryEditor/state.ts +++ b/public/app/plugins/datasource/elasticsearch/components/QueryEditor/state.ts @@ -1,22 +1,35 @@ import { Action, createAction } from '@reduxjs/toolkit'; import { ElasticsearchDataQuery } from '../../dataquery.gen'; +import { QueryType } from '../../types'; /** * When the `initQuery` Action is dispatched, the query gets populated with default values where values are not present. * This means it won't override any existing value in place, but just ensure the query is in a "runnable" state. */ -export const initQuery = createAction('init'); +export const initQuery = createAction('init'); export const changeQuery = createAction('change_query'); +export const changeRawDSLQuery = createAction('change_raw_dsl_query'); + export const changeAliasPattern = createAction('change_alias_pattern'); +export const changeEditorType = createAction('change_editor_type'); + +export const changeEditorTypeAndResetQuery = createAction( + 'change_editor_type_and_reset_query' +); + export const queryReducer = (prevQuery: ElasticsearchDataQuery['query'], action: Action) => { if (changeQuery.match(action)) { return action.payload; } + if (changeEditorTypeAndResetQuery.match(action)) { + return ''; + } + if (initQuery.match(action)) { return prevQuery || ''; } @@ -24,6 +37,22 @@ export const queryReducer = (prevQuery: ElasticsearchDataQuery['query'], action: return prevQuery; }; +export const rawDSLQueryReducer = (prevRawDSLQuery: ElasticsearchDataQuery['rawDSLQuery'], action: Action) => { + if (changeRawDSLQuery.match(action)) { + return action.payload; + } + + if (changeEditorTypeAndResetQuery.match(action)) { + return ''; + } + + if (initQuery.match(action)) { + return prevRawDSLQuery || ''; + } + + return prevRawDSLQuery; +}; + export const aliasPatternReducer = (prevAliasPattern: ElasticsearchDataQuery['alias'], action: Action) => { if (changeAliasPattern.match(action)) { return action.payload; @@ -35,3 +64,19 @@ export const aliasPatternReducer = (prevAliasPattern: ElasticsearchDataQuery['al return prevAliasPattern; }; + +export const editorTypeReducer = (prevEditorType: ElasticsearchDataQuery['editorType'], action: Action) => { + if (changeEditorType.match(action)) { + return action.payload; + } + + if (changeEditorTypeAndResetQuery.match(action)) { + return action.payload; + } + + if (initQuery.match(action)) { + return prevEditorType || 'builder'; + } + + return prevEditorType; +}; diff --git a/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.test.tsx b/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.test.tsx index a0df1278d9f..1b4c284303a 100644 --- a/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.test.tsx +++ b/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.test.tsx @@ -41,4 +41,16 @@ describe('ElasticDetails', () => { }) ); }); + + it('should change default query mode when selected', async () => { + const onChangeMock = jest.fn(); + render(); + const selectEl = screen.getByLabelText('Default query mode'); + + await selectEvent.select(selectEl, 'Logs', { container: document.body }); + + expect(onChangeMock).toHaveBeenLastCalledWith( + expect.objectContaining({ jsonData: expect.objectContaining({ defaultQueryMode: 'logs' }) }) + ); + }); }); diff --git a/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.tsx b/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.tsx index 232276d0124..fee941b3fc3 100644 --- a/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.tsx +++ b/public/app/plugins/datasource/elasticsearch/configuration/ElasticDetails.tsx @@ -1,10 +1,12 @@ import * as React from 'react'; -import { DataSourceSettings, SelectableValue } from '@grafana/data'; +import type { DataSourceSettings, SelectableValue } from '@grafana/data'; import { ConfigDescriptionLink, ConfigSubSection } from '@grafana/plugin-ui'; import { InlineField, Input, Select, InlineSwitch } from '@grafana/ui'; -import { ElasticsearchOptions, Interval } from '../types'; +import type { ElasticsearchOptions, Interval, QueryType } from '../types'; + +import { QUERY_TYPE_SELECTOR_OPTIONS } from './utils'; const indexPatternTypes: Array> = [ { label: 'No pattern', value: 'none' }, @@ -127,6 +129,29 @@ export const ElasticDetails = ({ value, onChange }: Props) => { onChange={jsonDataSwitchChangeHandler('includeFrozen', value, onChange)} /> + + + onChangeTableSelection(val, props)} /> +